首页 > 解决方案 > 用户没有个人资料。RelatedObjectDoesNotExist

问题描述

我正在尝试创建一个基于用户的应用程序。个人资料图像与每个用户相关联。但是每当我尝试登录时,它都会显示上述错误并突出显示signals.py中的instance.profile.save()。我是 Django 的新手。

错误:

Request Method:     POST
Request URL:        http://127.0.0.1:8000/login/
Django Version:     2.2.5
Exception Type:     RelatedObjectDoesNotExist
Exception Value:    User has no profile.

用户/Signals.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()

用户/模型.py:

from django.db import models
from django.contrib.auth.models import User
from PIL import Image

# Create your models here.
class profile(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    image=models.ImageField(default='default.png',upload_to='profile_pics')

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

    def save(self,*args,**kwargs):
        super( profile, self ).save(*args,**kwargs)

        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 .forms import UserRegisterForm,UserUpdateForm,ProfileUpdateForm
from django.contrib.auth.decorators import  login_required
from .models import profile

# Create your views here.
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'Account created for {username}!')
            return redirect('login')
    else:
        form=UserRegisterForm()

    return render(request,'users/register.html',{'form':form})

@login_required
def profile(request):
    if request.method=='POST':
        u_form = UserUpdateForm( request.POST,instance=request.user )
        profile = profile.objects.get( user=request.user )
        Profile_form = ProfileForm( request.POST, instance=profile )
        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 is 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)

app2/models.py:

    from django.contrib.auth.models import User
    from django.db import models
    class resume( models.Model ):
    user = models.OneToOneField( User, on_delete=models.CASCADE,primary_key=True )
    username=models.CharField(max_length=150)
    email=models.EmailField(max_length=150)
    phone=models.BigIntegerField()
def __str__(self):
    return str(self.user.username)+str(self.country)

标签: pythondjangodjango-modelsmodeldjango-views

解决方案


This code

profile.objects.create(user=instance)

already saves the profile and doesn't need save() to be called separately in save_profile method.

Also please consider naming classes starting with uppercase. 'profile' -> 'Profile'


推荐阅读