如何在CreateView中覆盖表单字段 [英] How to override form field in CreateView

查看:75
本文介绍了如何在CreateView中覆盖表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在模型表单中,我可以像这样覆盖表单字段

In model form I can override form field like so

class waypointForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ModelChoiceField(queryset=Waypoint.objects.filter(user=user))

如何使用相同的功能在基于类的视图 CreateView 中,以便我可以覆盖表单字段?

How can I use the same functionality in class based view CreateView, so that I can override form field?

我尝试了 get_form_kwargs get_form 都是徒劳的。我需要创建模型表单吗?

I tried get_form_kwargs and get_form but all in vain. Do I need to create a model form?

推荐答案

您可以覆盖 get_form_kwargs 并将用户传递给 kwargs 词典。然后在 __ init __()方法中,在表单上设置字段。

You can override the get_form_kwargs and pass the user to kwargs dictionary. Then in your __init__() method, set your field on the form.

views.py

通过 kwargs 中的用户覆盖 get_form_kwargs()

class MyCreateView(CreateView):

    form_class = waypointForm

    def get_form_kwargs(self):
        kwargs = super(MyCreateView, self).get_form_kwargs()
        kwargs['user'] = self.request.user # pass the 'user' in kwargs
        return kwargs 

forms.py

现在,覆盖 __ init __()方法。在其中,从 kwargs 弹出 user 键,然后使用该值创建字段。

Now, override the __init__() method. In that, pop the user key from kwargs and use that value to create your field.

class waypointForm(forms.ModelForm):

    def __init__(self, *args, **kwargs): 
        user = kwargs.pop('user', None) # pop the 'user' from kwargs dictionary      
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ModelChoiceField(queryset=Waypoint.objects.filter(user=user)) 

这篇关于如何在CreateView中覆盖表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆