在Django中如何生成自定义表单? [英] How do you generate a custom form in Django?

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

问题描述

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

In one of the template pages of my Django app, the page asks for the user to select the choices he wants, from a checkbox list.

对于不同的用户有不同的选择(例如,根据他们以前的兴趣,有不同的选择)。

The catch is, that there are different choices for different users (for example, based on their past interests, there are different options).

如何使用<$ c生成Django表单$ c> CheckboxSelectMultiple()为每个用户生成自定义选项的字段

How do you generate Django forms with CheckboxSelectMultiple() fields that generate custom choices for each user?

推荐答案

在表单中。 py你需要覆盖 __ init __ 方法,并在您调用表单类时设置从视图传递的选项。

In forms.py you need to override the __init__ method, and set there the choices passed from the view when you call the form class.

这是一个例子:

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)

这篇关于在Django中如何生成自定义表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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