我如何在 Django 中注册自定义用户模型(一种类型)?
how can i sign up with custom user model (One By One Type) in django?
如何在 django 中使用自定义用户模型 (OneToOneField) 创建正确的登录和注册?
我使用的是普通 HTML 表格。
我正在使用 Django 2.2.3。
我的数据库是 Postgeres。
你好,我创建了一个可以登录并注册的网站,但是......我需要自定义用户模型......所以我创建了一个自定义用户模型(在一个字段上使用一个),但我不我不知道如何为其创建登录和注册...所以我尝试了...但它无法正常工作...我无法在我的自定义用户模型中使用其他字段进行注册,它只注册了 User ,而不是 Profile 并给我这个错误“'Manager' object has no attribute 'create_profile'”。
对于我的登录……我认为它是通过 Django 的用户登录的。
我正在使用 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 %}
请帮忙。
我认为您混淆了 signals
and manager
方法。您不能将信号方法称为管理器方法。
我的意思是create_profile()
是一个信号,当User
被创建时会自动触发。因此,您应该创建 User
实例,而不是创建 Profile
。像这样:
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
中有两个字段(phone
和 address
) 不为空。所以我建议你制作它们 null=True
。
如何在 django 中使用自定义用户模型 (OneToOneField) 创建正确的登录和注册? 我使用的是普通 HTML 表格。 我正在使用 Django 2.2.3。 我的数据库是 Postgeres。
你好,我创建了一个可以登录并注册的网站,但是......我需要自定义用户模型......所以我创建了一个自定义用户模型(在一个字段上使用一个),但我不我不知道如何为其创建登录和注册...所以我尝试了...但它无法正常工作...我无法在我的自定义用户模型中使用其他字段进行注册,它只注册了 User ,而不是 Profile 并给我这个错误“'Manager' object has no attribute 'create_profile'”。 对于我的登录……我认为它是通过 Django 的用户登录的。 我正在使用 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 %}
请帮忙。
我认为您混淆了 signals
and manager
方法。您不能将信号方法称为管理器方法。
我的意思是create_profile()
是一个信号,当User
被创建时会自动触发。因此,您应该创建 User
实例,而不是创建 Profile
。像这样:
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
中有两个字段(phone
和 address
) 不为空。所以我建议你制作它们 null=True
。