如何为用户模型Django创建自定义表单

时间:2013-07-01 05:37:42

标签: python django forms

我想在Django中为用户创建django.contrib.auth.models.User创建自己的表单,但我找不到一个很好的例子。有人能帮助我吗?

1 个答案:

答案 0 :(得分:6)

you want to create a form?

创建一个表格say forms.py

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

class CreateUserForm(forms.Form):        
    required_css_class = 'required'        
    username = forms.RegexField(regex=r'^[\w.@+-]+$',
                                max_length=30,
                                label="Username",
                                error_messages={'invalid': "This value may contain only letters, numbers and @/./+/-/_ characters."})
    email = forms.EmailField(label="E-mail")
    password1 = forms.CharField(widget=forms.PasswordInput,
                                label="Password")
    password2 = forms.CharField(widget=forms.PasswordInput,
                                label="Password (again)")

    def clean_username(self):            
        existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
        if existing.exists():
            raise forms.ValidationError("A user with that username already exists.")
        else:
            return self.cleaned_data['username']

    def clean_email(self):
        #if you want unique email address. else delete this function
        if User.objects.filter(email__iexact=self.cleaned_data['email']):
            raise forms.ValidationError("This email address is already in use. Please supply a different email address.")
        return self.cleaned_data['email']

    def clean(self):            
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("The two password fields didn't match.")
        return self.cleaned_data

创建一个视图说views.py

def create_inactive_user(request):
    if request.method=='POST':
        frm=CreateUserForm(request.POST)
        if frm.is_valid():
            username, email, password = frm.cleaned_data['username'], frm.cleaned_data['email'], frm.cleaned_data['password1']
            new_user = User.objects.create_user(username, email, password)
            new_user.is_active = True # if you want to set active
            new_user.save()
    else:
        frm=CreateUserForm()
    return render(request,'<templatepath>',{'form'=frm})

最好使用django-registration