如何解决如何在管理面板的用户部分添加自定义用户模型-Django 3.1.1
我在django项目中添加了一个自定义用户模型,对此进行了here的解释。
我在models.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
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
company = models.CharField(max_length=25,blank=True)
address = models.TextField(max_length=500,blank=True)
zipcode = models.CharField(max_length=15,blank=True)
city = models.CharField(max_length=25,blank=True)
country = models.CharField(max_length=25,blank=True)
phone = models.CharField(max_length=15)
@receiver(post_save,sender=User)
def create_user_profile(sender,instance,created,**kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save,sender=User)
def save_user_profile(sender,**kwargs):
instance.profile.save()
在我的views.py
中,注册过程如下:
from django.shortcuts import render,redirect
from django.contrib.auth.models import User
def update_profile(request,user_id,company,address,zipcode,city,country,phonenumber):
user = User.objects.get(pk=user_id)
user.profile.company = company
user.profile.address = address
user.profile.zipcode = zipcode
user.profile.city = city
user.profile.country = country
user.profile.phoneNumber = phonenumber
user.save()
def register(request):
if request.method == 'POST':
# Get form values
first_name = request.POST['firstname']
last_name = request.POST['lastname']
company = request.POST['company']
address = request.POST['address']
zipcode = request.POST['zipcode']
city = request.POST['city']
country = request.POST['country']
phoneNumber = request.POST['phoneNumber']
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
password2 = request.POST['password2']
# Check if password match
if password == password2:
# Check username
if User.objects.filter(username=username).exists():
return redirect('register')
else:
if User.objects.filter(email=email).exists():
return redirect('register')
else:
# looks good
user = User.objects.create_user(username=username,password=password,email=email,first_name=first_name,last_name=last_name)
user.save()
update_profile(request,user.id,phoneNumber)
return redirect('login')
else:
return redirect('register')
else:
return render(request,'users/register.html')
现在,在管理面板中,应该在这样的单独部分中添加自定义模型:
from django.contrib import admin
from .models import Profile
admin.site.register(Profile)
如何在users
部分下的AUTHENTICATION AND AUTHORIZATION
页面中添加自定义用户模型(即个人资料)的字段?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。