限制modelformset字段中的值

时间:2013-01-05 20:47:53

标签: django django-forms django-views

我一直试图解决这个问题几天,变得非常绝望。请参阅已注释掉的代码片段,了解我尝试但未奏效的一些内容。

问题:如何将category的{​​{1}}字段中的值仅限制为属于当前登录用户的字段?

enter image description here

views.py

IngredientForm

models.py:

@login_required
def apphome(request):
    IngrFormSet = modelformset_factory(Ingredient, extra=1, fields=('name', 'category'))

    # Attempt #1 (not working; error: 'IngredientFormFormSet' object has no attribute 'fields')
    # ingrformset = IngrFormSet(prefix='ingr', queryset=Ingredient.objects.none())
    # ingrformset.fields['category'].queryset = Category.objects.filter(user=request.user)

    # Attempt #2 (doesn't work)
    # ingrformset = IngrFormSet(prefix='ingr', queryset=Ingredient.objects.filter(category__user_id = request.user.id))

forms.py:

class Category(models.Model):
    name = models.CharField(max_length=30, unique=True)
    user = models.ForeignKey(User, null=True, blank=True)       

class Ingredient(models.Model):
    name = models.CharField(max_length=30, unique=True)
    user = models.ForeignKey(User, null=True, blank=True)
    category = models.ForeignKey(Category, null=True, blank=True)
    counter = models.IntegerField(default=0)

更新:我已经取得了一些进展,但解决方案目前是硬编码的,并不是真正可用的:

我发现我可以通过表单类控制class IngredientForm(ModelForm): class Meta: model = Ingredient fields = ('name', 'category') 表单字段,然后在视图中传递表单,如下所示:

category

以上产生了我需要的结果,但显然#forms.py class IngredientForm(ModelForm): category = forms.ModelChoiceField(queryset = Category.objects.filter(user_id = 1)) class Meta: model = Ingredient fields = ('name', 'category') #views.py IngrFormSet = modelformset_factory(Ingredient, form = IngredientForm, extra=1, fields=('name', 'category')) 是硬编码的。我需要它是动态的(即当前用户)。我尝试了一些解决方案来访问forms.py中的request.user,但那些没有用。

任何想法如何前进?

2 个答案:

答案 0 :(得分:2)

您不需要任何形式的自定义表单。您可以将category字段的查询集更改为:

IngrFormSet = modelformset_factory(Ingredient, extra=1, fields=('name', 'category'))
IngrFormSet.form.base_fields['category'].queryset = Category.objects.filter(user__id=request.user.id)

答案 1 :(得分:0)

Category.objects.filter(user=request.user)

返回表单中初始值的列表对象,这没什么意义。

尝试改为

Category.objects.get(user=request.user)

Category.objects.filter(user=request.user)[0]