dynamic form requirements from model

落爺英雄遲暮 提交于 2019-12-25 03:42:11

问题


I'm trying to generate a dynamic registration form, based on on specific client needs. I've created a UserProfile model with most of the fields set as blank=True.

When the form gets generated, I pull the client specified fields from another db table and generate the registration form. All this works, except that all the fields allow blank values. So far I have this

def RegProfileForm(include_list, *args, **kwargs):
    class ProfileForm(forms.ModelForm):
        class Meta:
            model = hr.UserProfile
            fields = include_list

        def __init__(self):
            super(ProfileForm, self).__init__(*args, **kwargs)

    return ProfileForm()

Then I call this form like this:

includes = ['gender','work_phone'] # dynamic fields
of = RegProfileForm(includes)

How do I dynamically remove the blank=True requirement from certain specified fields during runtime, or when I generate the form?


回答1:


I figured out I can just do something like this to override the default values from the model:

form = MyAuthForm(data)
form.fields['first_name'].required = True
form.fields['email'].required = False


来源:https://stackoverflow.com/questions/5740837/dynamic-form-requirements-from-model

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