如何在 Django 中注册自定义用户模型(逐一类型)



如何在 django 中创建正确的登录并使用自定义用户模型(OneToOneField)进行注册? im使用正常的HTML表单。 im 使用 Django 2.2.3 . 我的数据库是Postgeres。

嗨,我创建了一个网站,可以在OK的地方登录和注册,但是...我需要自定义用户模型..所以我创建了一个自定义用户模型(使用一对一字段),但我不知道如何为它创建登录和注册......所以我试了... 但它无法正常工作...我无法在我的自定义用户模型中使用其他字段进行注册,它仅使用用户而不是配置文件注册,并给我此错误"'经理'对象没有属性'create_profile'"。 和我的登录.我认为它是使用 Django 的用户登录的。 im 使用 Django 2.2.3 . 我的数据库是Postgeres。 如何创建正确的登录和注册?

我 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)
address        =   models.TextField(max_length=500)
phone          =   models.CharField(max_length=50)
postcode       =   models.CharField(max_length=50, blank=True)
isManager      =   models.BooleanField(default=False)
isAccountment  =   models.BooleanField(default=False)
isStorekeeper  =   models.BooleanField(default=False)
isSeller       =   models.BooleanField(default=False)
isNormal       =   models.BooleanField(default=True)
def __str__(self):
return self.user.email
def create_profile(sender,**kwargs):
if kwargs['created']:
user_profile=Profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile,sender=User)

我的 views.py :

from django.shortcuts import render , redirect
from django.contrib.auth.models import User
from accounts.models import Profile
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.core.mail import send_mail

def signup(request):
if request.method == 'POST':
#USER HAS INFO AND WANTS ACCOUNT___NOW!
if request.POST['password1'] == request.POST['password2']:
try:
user =  User.objects.get(username=request.POST['username'],)
return render(request,'accounts/signup.html',{'error':'Username Exist...Try Something Else !','username':user})
except User.DoesNotExist :
user = User.objects.create_user(request.POST['username'] , password = request.POST['password1'],first_name=request.POST['fname'],last_name=request.POST['lname'],email=request.POST['email'],)
profile = user.profile # because of signal and one2one relation
profile.phone = request.POST['mobile_num']
profile.address = request.POST['address']
profile.postcode = request.POST['post_code']
profile.save()
auth.login(request,user)              
return redirect('homepage')
return render(request,'accounts/signup.html',{'error':"Passwords Don't Match"})
else:
#USER wants enter info
return render(request,'accounts/signup.html')    
def login(request):
if request.method == 'POST':
user=auth.authenticate(username=request.POST['username'],password=request.POST['password'])
if user is not None:
auth.login(request,user)
return render(request,'products/home.html')
#return redirect('homepage')
else:
return render(request,'accounts/login.html',{'error':'Username Or Password Is Incorrect !'})
else:
return render(request,'accounts/login.html')
def logout(request):
if request.method =='POST':
auth.logout(request)
return redirect('homepage')
@login_required
def myproducts(request):
user_id=request.user.id
products=Products.objects.all().filter(creator__exact=user_id)
return render(request,'accounts/myproducts.html',{'products':products})
def about_us(request):
return render(request,'accounts/aboutus.html')
def connect_us(request):
return render(request,'accounts/connectus.html')

这是我的表单页面:

{% extends 'base.html' %}
{% block content%}
<h1 style="margin-left:490px"> Register </h1>
<div class="left" style="margin-left:465px">
<form method="POST" action="{% url 'signup' %}">
{% csrf_token %}
First Name:
<br/>
<input type="text" name="fname"/><br/>
Last Name:
<br/>
<input type="text" name="lname"/><br/>
UserName:
<br/>
<input type="text" name="username"/><br/>
Mobile:
<br/>
<input type="text" name="mobile_num"/><br/>
Email:
<br/>
<input type="text" name="email"/><br/>
Address:
<br/>
<input type="text" name="address"/><br/>
Post Code
<br/>
<input type="text" name="post_code"/><br/>
Password:
<br/>
<input type="password" name="password1"/><br/>
Confirm password:
<br/>
<input type="password" name="password2"/>
<br/>
<br/>
<input class="btn btn-primary" type="submit" name="signup-btn" value="SignUp" style="margin-top:-23px;margin-left:49px;"/>
</form>
{% if error %}
<p style="color:red">{{error}}</p>
<br/>
{% endif%}
</div>
{% endblock %}

请帮忙.

我认为您混淆了signalsmanager方法。不能将信号方法调用为管理器方法。

我的意思是create_profile()是一个信号,它将在创建User时自动触发。因此,与其创建Profile,不如创建User实例。喜欢这个:

def signup(request):
if request.method == 'POST':
#USER HAS INFO AND WANTS ACCOUNT___NOW!
if request.POST['password1'] == request.POST['password2']:
try:
# rest of the code...
except User.DoesNotExist :
user = User.objects.create_user(username=request.POST['username'] ,first_name=request.POST['fname'],last_name=request.POST['lname'],email=request.POST['email'],password = request.POST['password1'])
profile = user.profile # because of signal and one2one relation
profile.phone_no = request.POST['phone'] 
profile.post_code = request.POST['post_code']
profile.save()
auth.login(request,user)
return redirect('homepage')
return render(request,'accounts/signup.html',{'error':"Passwords Don't Match"})
else:
#USER wants enter info
return render(request,'accounts/signup.html')

但是,当你尝试创建一个User时,你可能会遇到错误NOT NULL constraint failed,因为在Profile中有两个字段(phoneaddress)不是空的。所以我建议你把它们null=True.

最新更新