gpt4 book ai didi

python - 相关对象不存在。用户没有个人资料

转载 作者:行者123 更新时间:2023-12-04 10:34:22 24 4
gpt4 key购买 nike

我已经阅读了这个(几乎)问题的其他一些答案,但它们没有帮助。我为用户和个人资料应用程序(?)混合了以下 2 个文件。
在其他答案中,他们说如果您不使用 >objects.get_or_create 或不制作signals.py 文件,则会发生这种情况,您会收到此错误,但我已经通过了这两种方式,但没有结果。
这是我得到的回溯:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:3000/profile/

Django Version: 3.0.3
Python Version: 3.7.3
Installed Applications:
['blog',
'users',
'crispy_forms',
'django_cleanup',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/wss/Desktop/projects/python/django/mahour_sanat/mahoursanat/users/views.py", line 38, in profile
p_form = ProfileUpdateForm(instance=request.user.profile)
File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/utils/functional.py", line 225, in inner
return func(self._wrapped, *args)
File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 423, in __get__
self.related.get_accessor_name()

Exception Type: RelatedObjectDoesNotExist at /profile/
Exception Value: User has no profile.

表格.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile


class UserRegisterForm(UserCreationForm):
email = forms.EmailField()

class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']


class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()

class Meta:
model = User
fields = ['username', 'email']


class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']

信号.py:
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile


@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()

配置文件模型的models.py:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image


class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')

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

def save(self):
super().save()

img = Image.open(self.image.path)

if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)

这是 views.py 文件:
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, ProfileUpdateForm, UserUpdateForm


def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(
request, f'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
context = {
'form': form
}
return render(request, 'users/register.html', context)


@login_required
def profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(
request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile')
else:

u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/profile.html', context)

感谢您阅读本文:)。

附言正如我在管理页面中看到的,注册后没有配置文件(既不是来自站点也不是管理页面)。

最佳答案

很高兴看到有人在 Corey 的教程中练习 Django!我花了几天时间才发现出了什么问题。这是我如何做到的。

您的 views.py看起来像这样:

@login_required()
def profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance=request.user.profile)

views.py 中添加一个所以它看起来像下面
@login_required()
def profile(request):
Profile.objects.get_or_create(user=request.user)
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance=request.user.profile)

如果您碰巧遇到同样的问题,请创建一个新帐户并转到个人资料页面,看看它是否会引发任何错误。

关于python - 相关对象不存在。用户没有个人资料,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60258059/

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