Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add more field in SignupForm using django-allauth

Models:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    nationality = models.CharField(max_length=20)

    def __str__(self):
        return self.user.first_name

    @receiver(post_save, sender=User)
    def create_user_profile(self, sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(self, sender, instance, **kwargs):
        instance.profile.save()

Forms:

from allauth.account.forms import SignupForm

class CustomSignupForm(SignupForm):
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)

    class Meta:
        model = Profile
        fields = ('first_name', 'last_name', 'nationality', 'bio')

    def signup(self, request, user):
        # Save your user
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

        user.profile.nationality = self.cleaned_data['nationality']
        user.profile.gender = self.cleaned_data['bio']
        user.profile.save()

Views:

ACCOUNT_FORMS = {'signup': 'myproject.forms.CustomSignupForm',}

This process isn't work. Error is: Model class all_auth.models.Profile doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

How can I solve it? Or, How can i add more field with SignupForm using django-allauth?

like image 355
jhon arab Avatar asked Sep 13 '25 07:09

jhon arab


1 Answers

Create an application, such as accounts and it has this code, but you need to create a database only after creating this code, it is more accurate to perform the first migration in the project

accounts/models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    phone = models.CharField(max_length=12)


accounts/forms.py

from allauth.account.forms import SignupForm
from django import forms
from .models import *

class SimpleSignupForm(SignupForm):
    phone = forms.CharField(max_length=12, label='Телефон')
    def save(self, request):
        user = super(SimpleSignupForm, self).save(request)
        user.phone = self.cleaned_data['phone']
        user.save()
        return user


settings.py
...
ACCOUNT_FORMS = {'signup': 'accounts.forms.SimpleSignupForm'}
AUTH_USER_MODEL = 'accounts.CustomUser'


accounts/admin.py

from django.contrib import admin
from .models import *

admin.site.register(CustomUser)
like image 199
Yaroslav Miklin Avatar answered Sep 16 '25 07:09

Yaroslav Miklin