django - How do I filter a model field on a form that is a foreignkey but not the main foreignkey -
i have inlineformset_factory group of shoppinglistitemform
view:
class shoppinglistitemform(modelform): @property def __name__(self): return self.__class__.__name__ def __init__(self, *args, **kwargs): if kwargs.get('instance'): thelist = kwargs['instance'] self.fields['category'] = forms.choicefield(choices=[(cat.id, cat.name) cat in listitemcategory.objects.filter(shoppinglist__id=thelist.id)]) return super(shoppinglistitemform, self).__init__(self, *args, **kwargs) class meta: model = shoppinglistitem fields = ('item', 'brand', 'quantity', 'current', 'category', 'size', ) @login_required def shoppinglist(request, shoppinglist_id, pod_id): profile = request.user.get_profile() shoppinglist = get_object_or_404(shoppinglist, pk=shoppinglist_id) listformset = inlineformset_factory(shoppinglist, shoppinglistitem, form=shoppinglistitemform, extra=1, can_delete=true) myforms = listformset(instance=shoppinglist)
...this works great, except 'category' foreign key of shoppinglistitem, , need filter 'category' options offered on form related listitemcategory 'shoppinglist'. 'shoppinglist' foreign key of both listitemcategory , shoppinglistitem.
models:
class listitemcategory(models.model): name = models.charfield(max_length=30, blank=true, null=true) shoppinglist = models.foreignkey(shoppinglist) class shoppinglistitem(models.model): shoppinglist = models.foreignkey(shoppinglist) category = models.foreignkey(listitemcategory, blank=true, null=true, default = none) item = models.charfield(max_length=200, blank=true, null=true) class shoppinglist(models.model): name = models.charfield(max_length=30, blank=true, null=true, default="pod list")
...i think there no need pass in 'shoppinglist' argument, passed instance of form, initialization added, rendered template has nothing @ in formset.
any further advice?
your issue you're not "initializing" variable shoppinglist_id
in form def init
try this:
class shoppinglistitemform(modelform): class meta: model = shoppinglistitem fields = ('item', 'brand', 'quantity', 'current', 'category', 'size', ) def __init__(self, *args, **kwargs): shoppinglist_id = kwargs.pop('shoppinglist_id', none) super(shoppinglistitemform, self).__init__(*args, **kwargs) self.fields['category'].queryset = listitemcategory.objects.filter(shoppinglist__id=shoppinglist_id)
and should edit how initialize form:
listformset = inlineformset_factory(shoppinglist, shoppinglistitem, form=shoppinglistitemform(shoppinglist_id=shoppinglist.id), extra=1, can_delete=true)
the changes made next ones:
- pass
shoppinglist_id
kwarg argument
...shoppinglistitemform(shoppinglist_id=shoppinglist.id)
get kwarg argument in form
def __init__(self, *args, **kwargs): shoppinglist_id = kwargs.pop('shoppinglist_id', none)
Comments
Post a Comment