RelatedObjectDoesNotExist at /account/edit/ 用户没有个人资料

问题描述 投票:0回答:1

我可以编辑没有管理员状态的其他用户,没有任何问题,但当我尝试编辑超级用户时,此错误消息显示

RelatedObjectDoesNotExist at /account/edit/ User has no profile
。我创建了这个超级用户之后我添加了 Profile 模块类及其属性,并进行迁移。花了几个小时试图弄清楚但没有成功。谢谢大家的帮助

模型.py

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

from django.conf import settings
class Profile(models.Model):
    print(f'------->{settings.AUTH_USER_MODEL}')
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    date_of_birth = models.DateField(blank=True, null=True, default=None)
    photo = models.ImageField(blank=True, upload_to="users/%Y/%m/%d/")
    def __str__(self):
        return f'Profile of {self.user.username}'
    

Views.py


from account.models import Profile

@login_required
def Edit(request):
    if request.method == "POST":
        user_form = UserEditForm(instance= request.user, data=request.POST)
        profile_form = ProfileEditForm(instance= request.user.profile,data=request.POST, files=request.FILES)
        if user_form.is_valid():
            user_form.save()
            profile_form.save()
            return render(request,'account/dashboard.html')
    else:
        user_form = UserEditForm(instance= request.user)
        profile_form = ProfileEditForm(instance= request.user.profile)
    return render(request, "account/edit.html",{'user_form':user_form})

forms.py

class UserEditForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name','email']
    def clean_email(self):
        data = self.cleaned_data['email']
        qs = User.objects.exclude(id=self.instance.id).filter(email=data)
        if qs.exists():
            raise forms.ValidationError('email already in use')
        else:
            return data
class ProfileEditForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['date_of_birth','photo']

edit.html

{% extends "base.html" %}
{% block content %}
    <html>
        <p>Please enter correct information bellow to edit</p>
        <form method="POST" enctype="multipart/form-data">
            {{user_form.as_p}}
            {{profile_form.as_p}}
            {% csrf_token %}
            <input type="submit" value="save changes" />
        </form>
    </html>
{% endblock %}

admin.py

from django.contrib import admin
from .models import Profile
# Register your models here.
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
    list_display = ['user','date_of_birth', 'photo']
    raw_id_fields = ['user']
django django-views django-forms django-templates
1个回答
0
投票

您可以通过使用

get_or_create()
为超级用户创建配置文件对象(如果该对象尚不存在)来处理此问题:

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

@login_required
def Edit(request):
    profile, created = Profile.objects.get_or_create(user=request.user)
    
    if request.method == "POST":
        user_form = UserEditForm(instance=request.user, data=request.POST)
        profile_form = ProfileEditForm(instance=profile, data=request.POST, files=request.FILES)
        
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            return render(request, 'account/dashboard.html')
    else:
        user_form = UserEditForm(instance=request.user)
        profile_form = ProfileEditForm(instance=profile)
    
    return render(request, "account/edit.html", {'user_form': user_form, 'profile_form': profile_form})

您需要确保每个用户,包括超级用户,都有一个对应的

Profile
对象。由于您在创建超级用户后添加了
Profile
模型,因此现有超级用户可能没有与其关联的配置文件。

© www.soinside.com 2019 - 2024. All rights reserved.