从Django中基于类的通用视图向ModelForm发送request.user对象

时间:2011-04-27 15:01:20

标签: django django-forms django-class-based-views

所以,我的目标是能够在ModelForm中过滤ModelChoiceField查询集,只包含request.user创建的Places。

我的ModelForm很简单:

class PlaceEventForm(models.ModelForm):
    class Meta:
        model = Event

我希望能够添加以下内容:

def __init__(self, *args, **kwargs):
    super(PlaceEventForm, self).__init__(*args, **kwargs)
    self.fields['place'].queryset = Place.objects.filter(created_by=request.user)

但是,我似乎找不到在ModelForm中访问请求的方法。

我的观点是这样的:

class PlaceEventFormView(CreateView):
    form_class = PlaceEventForm
    template_name = 'events/event_create.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(PlaceEventFormView, self).dispatch(*args, **kwargs)

我不确定这是否接近我应该做的,但我试过了:

def get_form_kwargs(self):
    kwargs = super(PlaceEventFormView, self).get_form_kwargs()
    kwargs.update({'place_user': self.request.user})
    return kwargs

但是我收到了错误: init ()得到了一个意外的关键字参数'place_user'

关于这个的任何想法?或者有人可以想到一种方法来过滤我的ModelChoiceField而不需要将我的请求传递给ModelForm吗?

3 个答案:

答案 0 :(得分:23)

您需要在user方法中从kwargs弹出关键PlaceEventForm.__init__(),以防止它转到ModelForm.__init__()方法:

views.py:

class PlaceEventFormView(CreateView):
    form_class = PlaceEventForm
    template_name = 'events/event_create.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(PlaceEventFormView, self).dispatch(*args, **kwargs)

    def get_form_kwargs(self):
        kwargs = super(PlaceEventFormView, self).get_form_kwargs()
        kwargs.update({'place_user': self.request.user})
        return kwargs

forms.py:

class PlaceEventForm(models.ModelForm):
    class Meta:
        model = Event

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('place_user')
        # now kwargs doesn't contain 'place_user', so we can safely pass it to the base class method
        super(PlaceEventForm, self).__init__(*args, **kwargs)
        self.fields['place'].queryset = Place.objects.filter(created_by=user)

答案 1 :(得分:2)

我在iPhone上,但这样做:

def get_form(self, form_class):
     form = super(MyView, self).get_form(form_class)
     form.fields['place'].querset = Place....
     return form
哇,这太难了!没有缩进支持!

答案 2 :(得分:0)

要更新Yuji对Django 1.10+(包括Django 2.0+)的回答,请参阅下面的示例(请注意更新的方法签名)。 Yuji的建议方法将查询集与其他业务逻辑一起保留在视图中,并有助于保持任何扩展models.ModelForm的表单类干净简洁。

def get_form(self, form_class=None):
    if form_class is None:
        form_class = self.get_form_class()
    form = super(MyView, self).get_form()
    form.fields['place'].queryset = Place.objects.filter(created_by=self.request.user)
    return form

更短:

def get_form(self, form_class=None):
    form = super(MyView, self).get_form(form_class)
    form.fields['place'].queryset = Place.objects.filter(created_by=self.request.user)
    return form