中基于类的通用视图发送到

中基于类的通用视图发送到

本文介绍了将 request.user 对象从 Django 中基于类的通用视图发送到 ModelForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我的目标是能够在我的 ModelForm 中过滤 ModelChoiceField 查询集以仅包含 request.user 创建的地点.

So, my goal is to be able to filter a ModelChoiceField queryset in my ModelForm to only include Places that request.user has created.

我的 ModelForm 很简单:

My ModelForm is simply:

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

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

I'd like to be able to add something like:

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

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

However, I can't seem to find a way to access the request in the 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)

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

I'm not sure if this is even close to what I should do, but I tried:

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

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

But I got the error: init() got an unexpected keyword argument 'place_user'

对此有任何想法吗?或者任何人都可以想出一种方法来在视图中过滤我的 ModelChoiceField 而无需将我的请求传递给 ModelForm?

Any ideas on this one? Or can anyone think of a way to filter my ModelChoiceField in the view without needing to pass my request to the ModelForm?

推荐答案

你需要在 PlaceEventForm.__init__()kwargs 中弹出 key usercode> 方法,防止它转到 ModelForm.__init__() 方法:

You need to pop key user from kwargs in PlaceEventForm.__init__() method, to prevent it from going to ModelForm.__init__() method:

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)

这篇关于将 request.user 对象从 Django 中基于类的通用视图发送到 ModelForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 20:42