3

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

4

1 回答 1

7
you want to create a form?

创建一个表单说 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

于 2013-07-01T06:02:50.827 回答