简体   繁体   English

Django自定义用户创建表单

[英]Django custom user creation form

I'm trying to create a new user in my Django app but nothing happens. 我正在尝试在Django应用中创建一个新用户,但没有任何反应。 I'm using a custom user auth model. 我正在使用自定义用户身份验证模型。 Part of the code I edited from the docs. 我从文档中编辑的部分代码。 Why the error message "Users must have an email address" is reported by the model and not the forms? 为什么模型而不是表格报告错误消息“用户必须具有电子邮件地址”? Why am I not able to create a user? 为什么我无法创建用户? I don't get any error back. 我没有收到任何错误。

My model: 我的模特:

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

My form: 我的表格:

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

And my view: 我的看法是:

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})

So far I know, you do not raise error from forms, you just - 到目前为止,我知道,您不会从表单中引发错误,而只是-

1) add the error in it, then it automatically gets invalided by django and is posted back with error and also 1)在其中添加错误,然后它会自动被django无效并被错误地发回,并且

2) since you are overriding the clean method you must return the cleaned data . 2)由于您要重写clean方法,因此必须返回cleaned data So change the clean method with these details - 因此,请使用以下详细信息更改清洁方法-

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

a little shorter - 短一点-

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()

Sine you are not returning anything, the cleaned_data of your form is empty and thus django is returning you back to the form page with no data in it. 假设您没有返回任何内容,那么表单的cleaned_data为空,因此django将您返回没有任何数据的表单页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM