【问题标题】:How do you generate a custom form in Django?如何在 Django 中生成自定义表单?
【发布时间】:2014-08-05 05:03:13
【问题描述】:

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

问题在于,不同的用户有不同的选择(例如,根据他们过去的兴趣,有不同的选择)。

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

【问题讨论】:

标签: python django forms templates django-1.5


【解决方案1】:

在 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)

【讨论】:

    猜你喜欢
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 2017-02-19
    • 2018-08-24
    • 2018-10-02
    相关资源
    最近更新 更多