繁体   English   中英

您如何在Django中生成自定义表单?

[英]How do you generate a custom form in Django?

在我的Django应用程序的模板页面之一中,该页面要求用户从复选框列表中选择他想要的选择。

要注意的是,不同的用户有不同的选择(例如,根据他们过去的兴趣,有不同的选择)。

如何使用CheckboxSelectMultiple()字段生成Django表单,该表单为每个用户生成自定义选项?

在forms.py中,您需要重写__init__方法,并在其中设置调用表单类时从视图传递的选择。

这是一个例子:

class UserOptionsForm(forms.Form):
    user_personal_options = forms.ChoiceField(choices=(),
                                              widget=forms.CheckboxSelectMultiple)

    def __init__(self, *args, **kwargs):
        choices = kwargs.pop('choices', None) # return the choices or None
        super(UserOptionsForm, self).__init__(*args, **kwargs)
        if choices is not None:
            self.fields['user_personal_options'].choices = choices

所以在您看来:

def user_options(request, user_id):
    if request.method == 'POST':
        form = UserOptionsForm(request.POST)
            if form.is_valid():
                # proccess form data here
                form.save()
    else:
        # render the form with user personal choices
        user_choices = [] # do shometing here to make the choices dict by user_id
        form = UserOptionsForm(choices=user_choices)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM