gpt4 book ai didi

python - 如何在 Django 中使用配置文件注册不同类型的用户?

转载 作者:太空宇宙 更新时间:2023-11-04 02:16:46 25 4
gpt4 key购买 nike

我是 django 的新手,我开始了一个新项目。不久,我想用他们的个人资料图片注册不同类型的用户(教师、学生、员工)。我做了一个从用户到配置文件的一对一字段,下面是我的代码,我收到以下错误。如果您对我的注册目的有任何建议,我想用头像注册不同类型的用户。

models.py

from django.db import models
from django.contrib.auth.models import User,AbstractUser
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save

class User(AbstractUser):
USER_TYPE_CHOICES = (
(1,'Student'),
(2,'Teacher'),
(3,'Stuff')
)
profile = models.OneToOneField(on_delete=models.CASCADE, related_name='user')
user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)

class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='profile')
photo = models.ImageField(upload_to='users/%Y/%m/%d/')

def __str__(self):
return 'Profile {}'.format(self.user.username)

它的形式

from django import forms
from django.contrib.auth.models import User
from .models import Profile

class UserCreationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput, label='Password')
password2 = forms.CharField(widget=forms.PasswordInput, label='Repeat Password')

class Meta:
model = User
fields = ('username', 'first_name', 'last_name')

def clean_password(self):
cd = self.cleaned_data
if cd['password']!=cd['password2']:
raise forms.ValidationError('password no match')
return cd['password2']


class ProfileCreationForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('photo',)

它是我的 View 模块

from django.shortcuts import render
from .forms import ProfileCreationForm, UserCreationForm
from .models import Profile
from django.http import HttpResponse
def sign_up(request):
if request.method == 'POST':
user_form = UserCreationForm(instance=request.user,data=request.POST)
profile_form = ProfileCreationForm(instance=request.user.profile,data=request.POST,
files=request.FILES)
if user_form.is_valid() and profile_form.is_valid():
new_user = user_form.save(commit=False)
new_user.set_password(user_form.cleaned_data['password'])
new_user.save()
Profile.objects.create(user=new_user)
return HttpResponse('user created')

else:
user_form = UserCreationForm()
profile_form = ProfileCreationForm()
return render(request, '',{'user_form':user_form, 'profile_form':profile_form})

这里是错误:

Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Mahdi\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\Mahdi\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\Users\Mahdi\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Mahdi\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\Mahdi\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\Mahdi\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Mahdi\PycharmProjects\MyProject\accounts\models.py", line 7, in <module>
class User(AbstractUser):
File "C:\Users\Mahdi\PycharmProjects\MyProject\accounts\models.py", line 13, in User
profile = models.OneToOneField(on_delete=models.CASCADE, related_name='user')
TypeError: __init__() missing 1 required positional argument: 'to'

最佳答案

在您的模型中,您忘记指定 User 模型的 OneToOneField 应指向哪个模型(Profile),因为该配置文件稍后在 Python 文件中定义,您不能使用标识符,但是可以使用包含模型的名称的字符串文字:

class User(AbstractUser):
USER_TYPE_CHOICES = (
(1,'Student'),
(2,'Teacher'),
(3,'Stuff')
)
profile = models.OneToOneField(<b>'Profile'</b>, on_delete=models.CASCADE, related_name='user')
user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)

您将需要进行迁移,然后迁移以便在数据库中添加与您的模型相对应的表。

由于您引用了 Profile,这意味着您需要先构造一个 Profile,然后再保存 User(否则 profile 将为 NULL,此处不允许):

from django.shortcuts import render
from .forms import ProfileCreationForm, UserCreationForm
from .models import Profile
from django.http import HttpResponse

def sign_up(request):
if request.method == 'POST':
user_form = UserCreationForm(instance=request.user,data=request.POST)
profile_form = ProfileCreationForm(instance=request.user.profile,data=request.POST,
files=request.FILES)
if user_form.is_valid() and profile_form.is_valid():
profile = profile_form.save()
new_user = user_form.save(commit=False)
new_user.set_password(user_form.cleaned_data['password'])
<b>new_user.profile = profile</b>
new_user.save()
return HttpResponse('user created')

else:
user_form = UserCreationForm()
profile_form = ProfileCreationForm()
return render(request, <b>'my_template.html'</b>,{'user_form':user_form, 'profile_form':profile_form})

您还忘记指定模板。此外,建议将 redirect(..) 返回到 View ,否则如果用户刷新浏览器,将发出第二个 POST 请求,这可以因此触发创建另一个用户。

关于python - 如何在 Django 中使用配置文件注册不同类型的用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52496980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com