【问题标题】:Django Abstract User - how to implement it with allauthDjango Abstract User - 如何用 allauth 实现它
【发布时间】:2021-08-08 18:37:33
【问题描述】:

我没有可依赖的标准 Django 用户模型。您将如何结合 AbstractUser 和 Allauth。我应该先构建视图“SignUpView.as_view”还是应该弄清楚路径“accounts/”应该如何与 allauth 关联?

我试图通过删除/包含方面来调整正常运行的电子商务网站,其中一种调整是自定义用户模型。

我正在学习本教程:

https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html

非常好,只是不知道如何容纳 allauth,由于其社交登录的便利性,它必须在这个项目中。

urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    path('', include('home.urls')),
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')),
    path('projects/', include('projects.urls')),
    # path('profiles/', include('profiles.urls')),
    # path('accounts/signup/', users.SignUpView.as_view(), name='signup'),
    # path('accounts/signup/volunteer/', volunteers.VolunteerSignUpView.as_view(), name='volunteer_signup'),
    # path('accounts/signup/organisation/', organisations.OrganisationsSignUpView.as_view(), name='organisation_signup'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

models.py

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.html import escape, mark_safe


class User(AbstractUser):
    is_volunteer = models.BooleanField(default=False)
    is_organisation = models.BooleanField(default=False)



class Volunteer(models.Model):
   
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)

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

这是我的 settings.py 文件

settings.py

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.linkedin_oauth2',
    'home',
    'projects',
    'profiles' , 

    # Other
    'crispy_forms',

]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'projectSaasy.urls'

CRISPY_TEMPLATE_PACK = 'bootstrap4'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
            os.path.join(BASE_DIR, 'templates', 'allauth'), 
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'builtins': [
                'crispy_forms.templatetags.crispy_forms_tags',
                'crispy_forms.templatetags.crispy_forms_field',
            ]
        },
    },
]

AUTHENTICATION_BACKENDS = [
    
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
    
]

SITE_ID = 1

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = True
ACCOUNT_USERNAME_MIN_LENGTH = 4
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/'

# Social accounts
# This is the most helpful guide: 
# https://python.plainenglish.io/why-you-should-let-the-user-to-authenticate-with-social-accounts-df30b0ba4793

SOCIALACCOUNT_PROVIDERS = {
    'linkedin': {
        'SCOPE': [
            'r_basicprofile',
            'r_emailaddress'
        ],
        'PROFILE_FIELDS': [
            'id',
            'first-name',
            'last-name',
            'email-address',
            'picture-url',
            'public-profile-url',
        ]
    }
}

# This allows social sign-up to be instantaneous (change back to "True")
SOCIALACCOUNT_AUTO_SIGNUP = True


WSGI_APPLICATION = 'projectSaasy.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

AUTH_USER_MODEL = "profiles.User"


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

这是forms.py

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.db import transaction

from profiles.models import Volunteer, User

class VolunteerSignUpForm(UserCreationForm):

    class Meta(UserCreationForm.Meta):
        model = User

    @transaction.atomic
    def save(self):
        user = super().save(commit=False)
        user.is_volunteer = True
        user.save()
        volunteer = Volunteer.objects.create(user=user)
        volunteer.interests.add(*self.cleaned_data.get('interests'))
        return user

还有views.py

views.py

from django.contrib.auth import login
from django.shortcuts import redirect
from django.views.generic import CreateView

from .forms import VolunteerSignUpForm
from .models import User

class VolunteerSignUpView(CreateView):
    model = User
    form_class = VolunteerSignUpForm
    template_name = 'registration/signup_form.html'

【问题讨论】:

    标签: python django django-authentication django-allauth django-custom-user


    【解决方案1】:

    如果您的信号效果不佳,那么您可以单独使用以下信号功能:

    @receiver(post_save, sender=User)
    def create_profile(sender, instance, created, **kwargs):
        if created:
            User.objects.create(user=instance)
    
    @receiver(post_save, sender=User)
    def save_profile(sender, instance, **kwargs):
        instance.user.save()
    

    如果仍然无法正常工作,那么您可以创建一个名为 signals.py 的单独文件,然后复制并粘贴我上面编写的所有代码。 问候阿布巴卡尔

    【讨论】:

    • bill 你能像我一样更新你的信号吗?
    【解决方案2】:

    首先删除您的数据库和所有迁移文件夹,然后进行以下更改

    在你的models.py中,做一些改变

    from django.conf import settings
    
    class Volunteer(models.Model):
       
        user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True)
    
        def __str__(self):
            return self.user.username 
    

    并在 admin.py 中注册这个模型

    from django.contrib import admin
    
    from .models import *
    
    admin.site.register(User)
    

    进行以下更改后 运行以下命令

    python manage.py makemigrations <your_app_name_in_which_AbstractUserModel_is_present>
    python manage.py migrate
    

    【讨论】:

      猜你喜欢
      • 2013-04-16
      • 2016-10-06
      • 2011-01-01
      • 2014-05-15
      • 2014-07-24
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      相关资源
      最近更新 更多