好吧..我开始创建简单的应用程序。按照 Django 的官方文档,我在单独的应用程序中创建了身份验证逻辑 name users
,如下所示:
用户/urls.py:
from django.urls import path, re_path, include
from . import views
urlpatterns = [
path('', include('django.contrib.auth.urls')),
path('profile/', views.redirect_to_user_profile, name='redirect-user-profile'),
re_path('profile/(?P<pk>\d+)/', views.UserProfileView.as_view(), name='user-profile'),
path('register/', views.UserRegisterView.as_view(), name='user-register'),
用户/views.py:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.views import generic
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def redirect_to_user_profile(request):
url = f'/users/profile/{request.user.id}'
return HttpResponseRedirect(redirect_to=url)
class UserProfileView(generic.DetailView):
model = User
template_name = 'user_profile.html'
class UserRegisterView(generic.CreateView):
form_class = UserCreationForm
template_name = 'register.html'
success_url = '/users/login'
一切都很好,所以我决定扩展基本的 Django 用户,例如添加个人资料图像(以及稍后的更多字段),如下所示:
用户/模型.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class ProfileUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_image = models.URLField()
@receiver(post_save, sender=User) # Still don't know how, but next rows create ProfileUser when User is created
def create_user_profile(sender, instance, created, **kwargs):
if created:
ProfileUser.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profileuser.save()
def __str__(self):
return f"{self.user}"
仍然工作正常。然后我决定添加FB登录,经过一些研究我找到了django-allauth模块,按照它的文档并在users/urls.py中添加一行:
path('fb/', include('allauth.urls')),
它也可以工作,但是问题来了,目前我有两个单独的授权模块:
基本的 django 用户身份验证逻辑:
和django-allauth身份验证逻辑:
如何处理这个(最好的方法):
我的想法:只使用 Django-allauth,但是有没有办法用额外的 ProfileUser 来扩展它,比如现在用 Django User 来扩展它?