在用户表单django中设置默认值

时间:2018-07-03 20:06:07

标签: python django django-forms

我需要用户形式的其他默认值,但是默认情况下不会要求用户将其保存在每个用户的数据中,但是我该怎么做呢? 这是我的表格

from django import forms
from django.contrib.auth.models import User


class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput, min_length=6) 
    confirm_password = forms.CharField(widget=forms.PasswordInput(), min_length=6) 
    first_name = forms.CharField(max_length=30) 
    last_name = forms.CharField(max_length=30) 
    email = forms.EmailField(max_length=254) 

1 个答案:

答案 0 :(得分:0)

我想我理解您的要求。如果您要使用ModelForm,则应在这里了解类meta:如何用于ModelForm。这应该使您开始在表单中添加一个附加字段。如果要向用户模型添加一些额外的数据,则需要使用AbstractUser扩展用户模型并添加'additional_field'。

from django import forms
from django.contrib.auth.models import User


class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput, min_length=6)
    confirm_password = forms.CharField(widget=forms.PasswordInput(), min_length=6)
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField(max_length=254)
    additional_field = forms.CharField(max_length=100)

    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        self.fields['additional_field'].disabled = True
        self.fields['additional_field'].initial = 'SOME INITIAL VALUE'