【发布时间】:2015-07-26 20:40:12
【问题描述】:
我有一个 inlineformset_factory,它是一组 ShoppingListItemForm
查看:
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) for 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)
...这很好用,除了“类别”是 ShoppingListItem 的外键,我需要将表单上提供的“类别”选项过滤为仅通过“购物清单”与 ListItemCategory 相关的选项。 'shoppinglist' 是 ListItemCategory 和 ShoppingListItem 的外键。
型号:
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")
...我认为没有必要将“购物清单”作为额外的参数传递,因为它是作为表单的实例传递的,但是添加了这个初始化之后,我渲染的模板在表单集。
还有什么建议吗?
【问题讨论】:
标签: django foreign-key-relationship inline-formset