How do you generate a custom form in Django?

China☆狼群 提交于 2019-12-09 22:37:14

问题


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

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


回答1:


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.

Here is an example:

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

So in your view:

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)


来源:https://stackoverflow.com/questions/24225605/how-do-you-generate-a-custom-form-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!