django - 从 Django 中基于类的通用 View 将 request.user 对象发送到 ModelForm

标签 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

但我得到了错误:初始化 () 得到了一个意外的关键字参数“place_user”

关于这个有什么想法吗?或者任何人都可以想出一种方法来过滤 View 中的 ModelChoiceField 而无需将我的请求传递给 ModelForm?

最佳答案

您需要弹出键user来自 kwargsPlaceEventForm.__init__()方法,以防止它转到 ModelForm.__init__()方法:

View .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

表格.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)

关于django - 从 Django 中基于类的通用 View 将 request.user 对象发送到 ModelForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5806224/

相关文章:

javascript - 基于类和基于对象的语言比较(ECMAScript 规范)

python - 将请求(用户)传递给基于类的 View

javascript - JS框架能够基于(django)rest api选项生成表单

python - 减少 Django 内存使用。低悬的果实?

python - 如何反转 SQL 查询以到达其 Django 源?

python - Django url正则表达式参数捕获

django - 在不知道输入名称和数量的情况下使用 request.POST

django - 返回带有当前 FormWizard 数据的新 FormWizard

python - 自动填充 Django ModelForms

python - Django:正确使用基于类的 View 继承?