0

我正在尝试显示一个表单(ModelForm),其中包含select由当前登录用户过滤的字段。在这种情况下,选择字段包含类别列表。我只想显示“属于”当前登录用户的类别。类别字段是 IngredienceCategory 模型的外键。

到目前为止,这是我想出的,但它给了我一个错误(意外的关键字查询集)。任何想法我做错了什么?

# models.py
class IngredienceCategory(models.Model):
    name = models.CharField(max_length=30)
    user = models.ForeignKey(User, null=True, blank=True)

    class Meta:
    verbose_name_plural = "Ingredience Categories"

    def __unicode__(self):
        return self.name


class Ingredience(models.Model):
    name = models.CharField(max_length=30)
    user = models.ForeignKey(User, null=True, blank=True)
    category = models.ForeignKey(IngredienceCategory, null=True, blank=True)

    class Meta:
         verbose_name_plural = "Ingredients"

    def __unicode__(self):
        return self.name


class IngredienceForm(ModelForm):
    class Meta:
        model = Ingredience
        fields = ('name', 'category')


# views.py
def home(request):
    if request.user.is_authenticated():
        username = request.user.username
        email = request.user.email
        foods = Food.objects.filter(user=request.user).order_by('name')
        ingredients = Ingredience.objects.filter(user=request.user).order_by('name')
        ingrcat = IngredienceCategory.objects.filter(user=request.user)

        if request.method == 'POST':
            form = IngredienceForm(request.POST)
            if form.is_valid():
                # Create an instance of Ingredience without saving to the database
                ingredience = form.save(commit=False)
                ingredience.user = request.user
                ingredience.save()
        else:
            # How to display form with 'category' select list filtered by current user?
            form = IngredienceForm(queryset=IngredienceCategory.objects.filter(user=request.user))

        context = {}
        for i in ingredients:
            context[i.category.name.lower()] = context.get(i.category.name.lower(), []) + [i]

        context2 = {'username': username, 'email': email, 'foods': foods, 'ingrcat': ingrcat, 'form': form,}
        context = dict(context.items() + context2.items())
    else:
        context = {}

    return render_to_response('home.html', context, context_instance=RequestContext(request))
4

2 回答 2

2

发生这种情况是因为 ModelForm 没有使用 queryset 关键字。

您可以通过在视图上设置查询集来实现这一点:

form = IngredienceForm()
form.fields["category"].queryset = 
        IngredienceCategory.objects.filter(user=request.user)

在此处查看相关问题。

于 2012-11-07T21:51:52.367 回答
1

在这里,我有另一个解决问题的建议。您可以在视图内的表单对象中传递请求对象。

view.py只需传递请求对象。

form = IngredienceForm(request)

在您的forms.py __init__函数中还添加request对象

from models import  IngredienceCategory as IC

class IngredienceForm(ModelForm):
    class Meta:
        model = Ingredience
        fields = ('name', 'category')

    def __init__(self, request, *args, **kwargs):
        super(IngredienceForm, self).__init__(*args, **kwargs)
        self.fields['name'].queryset = IC.objects.filter(user=request.user)

每当您初始化表单时,总会应用此过滤器。

于 2018-07-10T14:32:26.903 回答