ok fixed it myself
I should have used class variables and not instance variables inside formfield_for_foreignkey (actually implemented this in a ModelForm subclass. So feel free to ask me if you wanna do something similar and it doesn't work)

On 5 Aug 2011, at 18:04, Tobias Ottenweller wrote:

Hi,

what I'm trying to do seems to be a little hard. I've got three model-classes:

class A(models.Model):
 ...

class B(models.Model):
 ...

class C(models.Model):
 a = models.ForeignKey(A)
 b = models.ForeignKey(B)
 ...

 class Meta:
     unique_together = ('a', 'b')
 ...


In admin.py C is defined as a inline of B. I'm now trying to add inlines of C for each instance of A (that already works). Plus I want to preset the foreign keys to A in the inline forms & make it the only available choice - each inline gets it's own instance of A.
Here is want I already did in admin.py:

class CInline(admin.TabularInline):
        model = C
 ...

 def formfield_for_foreignkey(self, db_field, request, **kwargs):
     if db_field.name == 'a':
         a = self.as[self.a_counter]
         self.a_counter = (self.a_counter + 1) % len(self.as)

kwargs["queryset"] = A.objects.filter(pk=a.id) # bad for performance
         db_field.default = a


return super(CInline, self).formfield_for_foreignkey(db_field, request, **kwargs)


class BAdmin(admin.ModelAdmin):
 model = B
 inlines = ( CInline, )

 def add_view(self, request, form_url='', extra_context=None):

     inline = self.inlines[0]
     inline.max_num = len(a.objects.all())
     inline.extra = len(a.objects.all())

     inline.language_counter = 0
     inline.languages = a.objects.all()

return super(BAdmin, self).add_view(request, form_url, extra_context)


Problem is that formfield_for_foreign doesn't seem to be called for all foreign_keys in each inline element of the add page. Or maybe the formfield gets reused. The result is that all inline elements get the same queryset and default value.

I'm a lithe bit stuck here. Maybe there is a complete other way to solve my problem.

Cheers


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to