简体   繁体   中英

adding required files to custom user when registration in django

I'm really new in Django and I would like to create a register form to login user. I would like this form have additional and required fields. the problem is when I try to fill the sign up registration directly on the web, the user is not registered, but if I do it in /admin section, the user is saved, so I have used custom user So first I have created class in model.py file:

class Account (AbstractBaseUser):
    email = models.EmailField(verbose_name="email", max_length=60, unique=True)
    username = models.CharField(max_length=30, unique=True)
    date_joined = models.DateTimeField(
        verbose_name='date joined', auto_now_add=True)
    last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    phone_regex = RegexValidator(
        regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(
        validators=[phone_regex], max_length=17, blank=True)  # validators should be a list
    role = models.CharField(max_length=50)
    store = models.CharField(max_length=50)
    aisle = models.CharField(max_length=50, unique=True)
    user_identification = models.CharField(max_length=30, unique=True)
 
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name',
                       'phone_number', 'role', 'store', 'aisle', 'user_identification']
 
    objects = MyAccountManager()
 
    def __str__(self):
        return self.email
 
    # if user is admin, can chenge
    def has_perm(self, perm, obj=None):
        return self.is_admin
 
    def has_module_perms(self, app_label):
        return True
 
    @property
    def staff(self):
        return self.is_staff
 
    @property
    def active(self):
        return self.is_active

after I have created the Account Manager in the same models.py

class MyAccountManager(BaseUserManager):
    def create_user(self, email, username, first_name, last_name,
                    phone_number, role, store, aisle, user_identification,  password=None):
        if not email:
            raise ValueError("Users must have an email address")
        if not username:
            raise ValueError("Users must have an user name")
        if not first_name:
            raise ValueError("Users must have an user name")
        if not last_name:
            raise ValueError("Users must have an user name")
        if not phone_number:
            raise ValueError("Users must have an user name")
        if not role:
            raise ValueError("Users must have an user name")
        if not store:
            raise ValueError("Users must have an user name")
        if not aisle:
            raise ValueError("Users must have an user name")
        if not user_identification:
            raise ValueError("Users must have an user name")
 
        user = self.model(
            email=self.normalize_email(email),
            username=username,
            first_name=first_name,
            last_name=last_name,
            phone_number=phone_number,
            role=role,
            store=store,
            aisle=aisle,
            user_identification=user_identification,
        )
 
        user.set_password(password)
        user.save(using=self._db)
        return user
 
    def create_superuser(self, email, username, first_name, last_name,
                         phone_number, role, store, aisle, user_identification,  password=None):
        user = self.create_user(
            email=self.normalize_email(email),
            username=username,
            first_name=first_name,
            last_name=last_name,
            phone_number=phone_number,
            role=role,
            store=store,
            aisle=aisle,
            user_identification=user_identification,
            password=password,
 
        )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

then in the forms.py file I have created the register method:

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(
        max_length=60, help_text='Required. Add a valid email address')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    phone_number = forms.CharField(max_length=30)
    role = forms.CharField(max_length=30)
    aisle = forms.CharField(max_length=30)
    user_identification = forms.CharField(max_length=30)
 
    class Meta:
        model = Account
        fields = ["email", "username", "password1", "password2", 'first_name', 'last_name',
                  'phone_number', 'role', 'store', 'aisle', 'user_identification', ]
 
    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2
 
    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
 
        user.set_password(self.cleaned_data["password1"])
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.phone_number = self.cleaned_data['phone_number']
        user.role = self.cleaned_data['role']
        user.aisle = self.cleaned_data['aisle']
        user.user_identification = self.cleaned_data['user_identification']
 
        if commit:
            user.save()
        return user

and the view looks like that:

def registration_view(request):  # request, GET from the web
    form = RegistrationForm()
    context = {}
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            email = form.cleaned_data.get('email')
            raw_password = form.cleaned_data.get('password1')
            account = authenticate(email=email, password=raw_password)
            # name = form.cleaned_data.get('email')
            login(request, account)
            return redirect('home')
        else:
            context['registration_form'] = form
    else:
        form = RegistrationForm()
        context['registration_form'] = form
    # here we inflate and return the view
    return render(request, 'account/register.html', context)

I have configured in settings.py the user custom model: AUTH_USER_MODEL = 'account.Account'

Also I have configured the admin.py file

class AccountAdmin (UserAdmin):
    list_display = ('email', 'username', 'date_joined',
                    'last_login', 'is_admin', 'is_staff',)
    search_fields = ('email', 'username',)
    readonly_fields = ('date_joined', 'last_login')
 
    filter_horizontal = ()
    list_filter = ()
    fieldsets = ()
 
 
admin.site.register(Account, AccountAdmin)
admin.site.register(UserProfile)

thanks a lot for your help guys!

Perhaps are you always setting commit=false in order to work with it before saving, but then always is going to avoid saving because the if sentence at the end of the Def?

    class RegistrationForm(UserCreationForm):
    ...

    def save(self, commit=True):
    user = super(RegistrationForm, self).save(**commit=False**)

    user.set_password(self.cleaned_data["password1"])
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']
    user.phone_number = self.cleaned_data['phone_number']
    user.role = self.cleaned_data['role']
    user.aisle = self.cleaned_data['aisle']
    user.user_identification = self.cleaned_data['user_identification']

    **if commit:**
        user.save()
    return user

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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