Django自定义用户创建表单

时间:2014-10-13 19:44:18

标签: python django

我试图在我的Django应用中创建一个新用户,但没有任何反应。我使用自定义用户身份验证模型。我从文档编辑的部分代码。为什么错误消息"用户必须拥有电子邮件地址"是由模型报告而不是表格?为什么我无法创建用户?我没有收到任何错误。

我的模特:

from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.utils import timezone


class MyUserManager(BaseUserManager):

    def create_user(self, email, name, neighborhood, password=None):

        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            name=name,
            neighborhood=neighborhood
        )

        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, email, name, neighborhood, password):

        user = self.create_user(
            email=email,
            name=name,
            password=password,
            neighborhood=neighborhood
        )

        user.is_admin = True
        user.save(using=self._db)

        return user


class MyUser(AbstractBaseUser):

    name = models.CharField(max_length=255)
    email = models.EmailField(max_length=255, unique=True)
    created_at = models.DateTimeField(default=timezone.now, blank=True)
    neighborhood = models.CharField(max_length=255)
    consultant_id = models.IntegerField(null=True)
    moip_id = models.IntegerField(null=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name', 'neighborhood']

    def __str__(self):
        return self.name

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

我的表格:

from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from dashboard.models import MyUser


class UserCreationForm(forms.ModelForm):

    password = forms.CharField(label='Senha', widget=forms.PasswordInput)
    confirm_password = forms.CharField(label='Confirmar senha', widget=forms.PasswordInput)

    class Meta:

        model = MyUser

        # Note - include all *required* MyUser fields here,
        # but don't need to include password and confirm_password as they are
        # already included since they are defined above.
        fields = ('email', 'name', 'neighborhood',)

    def clean(self):

        cleaned_data = super(UserCreationForm, self).clean()

        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')

        if password and confirm_password and password != confirm_password:
            raise forms.ValidationError('As senhas nao batem.')

    def save(self, commit=True):

        user = super(UserCreationForm, self).save(commit=False)

        user.set_password(self.cleaned_data['password'])

        if commit:
            user.save()

        return user

我的观点:

from django.shortcuts import render

from frontend.forms import UserCreationForm

# Create your views here.

def register(request):

    message = None

    if request.method == 'POST':

        form = UserCreationForm(request.POST)

        if form.is_valid():

            form.save()

    return render(request, 'frontend/register.html', {'message': message})

1 个答案:

答案 0 :(得分:0)

到目前为止,我知道,你不会从表单中引发错误,只是 -

1)在其中添加错误,然后它会自动被django无效并且会被错误地回发并且

2)因为你要覆盖clean方法,所以你必须返回cleaned data。因此,请使用这些详细信息更改clean方法 -

def clean(self):
    cleaned_data = self.cleaned_data

    password = cleaned_data.get('password')
    confirm_password = cleaned_data.get('confirm_password')

    if password and confirm_password and password != confirm_password:
        #raise forms.ValidationError('As senhas nao batem.') => we do not raise error in form clean, instead we add it in validation error.
        self.add_error('confirm_password', 'As senhas nao batem.')
    return super(UserCreationForm, self).clean() # =>this line is IMPORTANT to not break the calling hierarchy

稍短 -

def clean(self):
    if self.cleaned_data['password'] != self.cleaned_data['confirm_password']:
        self.add_error('confirm_password', 'Password & Confirm Password must match.')

    return super().clean()

正确的你没有返回任何内容,表单的cleaned_data为空,因此django会将你返回到没有数据的表单页面。