简体   繁体   English

更新UserProfile(将OneToOne模型更新为Django用户模型)

[英]updating UserProfile (OneToOne model to Django User model)

I am new to Django and creating a Django project with an account system. 我刚接触Django,并使用帐户系统创建Django项目。 I extended the User model with a one-to-one UserProfile model. 我用一对一的UserProfile模型扩展了User模型。

However, I am having problems saving the data in the UserProfile model (saving to User model is having no problem). 但是,我在将数据保存到UserProfile模型时遇到问题(保存到User模型没有问题)。 I tried to follow this guide to fix it but ran into AttributeError at /account/login/ 'User' object has no attribute 'UserProfile' errors which is saying there are errors with instance.UserProfile.save() under models.py 我试图按照本指南进行修复,但在/ account / login /遇到了AttributeError,“用户”对象没有属性“ UserProfile”错误,这表示在models.py下instance.UserProfile.save()存在错误

How do I get the UserProfile form to save and fix this no attribute error? 如何获取UserProfile表单以保存和修复此无属性错误?

models.py models.py

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

class UserProfile(models.Model):
        user = models.OneToOneField(
                User, 
                on_delete=models.CASCADE, 
                blank=True, 
                null=True, 
                unique=True,
                related_name='userprofile'
        )
        bio = models.CharField(max_length=200, default='', blank=True)
        campus = models.CharField(max_length=100, default='', blank=True)
        website = models.URLField(default='', blank=True)
        phone = models.IntegerField(default=0, blank=True)
        image = models.ImageField(upload_to='profile_image', blank=True)
        birthday = models.DateField(blank=True, default=datetime.date.today)
        gender = models.CharField(default='', blank=True, max_length=20)

        def __str__(self):
                return self.user.username

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

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

forms.py 表格

    # Edit User form
class EditProfileForm(UserChangeForm):

    class Meta:
        model = User
        fields = (
            'email',
            'first_name',
            'last_name',
            'password',
        )
# Edit User Profile form
class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = (
            'bio',
            'campus',
            'birthday',
            'gender',
            'website',
            'phone',
            'image',
        )

views.py views.py

@login_required
@transaction.atomic
def edit_profile(request):
    if request.method == 'POST':
        user_form = EditProfileForm(request.POST, instance=request.user)
        profile_form = UserProfileForm(request.POST, instance=request.user.UserProfile.user)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(commit=False)
            #user.username = user.email
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            return redirect('/account/profile')
    else:
        profile_form = UserProfileForm(instance=request.user.userprofile)
        user_form = EditProfileForm(instance=request.user)
    args = {
        'user_form': user_form, # basic user form
        'profile_form': profile_form # user profile form
        }
    return render(request, 'accounts/edit_profile.html', args)

templates accounts/edit_profile.html 模板account / edit_profile.html

<form method="POST">
        {% csrf_token %}
        {{ user_form.as_p }}
        {{ profile_form.as_p }}
        <button type="submit">Submit</button>
    </form>

urls.py urls.py

url(r'^profile/edit/$', views.edit_profile, name='edit_profile')

SOLUTION: 解:

in models.py only have one receiver and change else: instance.UserProfile().save() to else: instance.userprofile().save() models.py中只有一个接收者,并更改else: instance.UserProfile().save()接收者else: instance.UserProfile().save()else: instance.userprofile().save()接收者else: instance.userprofile().save()

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
    else:
        instance.userprofile.save()

in views.py fix typos views.py中修正错别字

change profile_form = UserProfileForm(request.POST, instance=request.user.UserProfile.user) to profile_form = UserProfileForm(request.POST, instance=request.user.userprofile) profile_form = UserProfileForm(request.POST, instance=request.user.UserProfile.user)更改为profile_form = UserProfileForm(request.POST, instance=request.user.userprofile)

You have two handlers listening on the same signal ( post_save ) and your save_user_profile function runs before create_user_profile can find a chance to create the UserProfile instance. 您有两个处理程序侦听相同的信号( post_save ),并且在create_user_profile找到机会创建UserProfile实例之前, save_user_profile函数运行。

I would suggest consolidating both handlers into one, such as: 我建议将两个处理程序合并为一个,例如:

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
    else:
        instance.userprofile.save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么django对User模型的作用与对userprofile模型的作用不同? - Why does django not do for the User model the same as it does for the userprofile model? Django:检索用户模型时自动选择相关模型UserProfile - Django: Automatically selecting related model UserProfile when retrieving User model ValueError:无法解析相关模型“ user.UserProfile” - ValueError: Related model 'user.UserProfile' cannot be resolved Django 2.1 无法访问Django中模板中的UserProfile模型字段。 尝试过{{user.userprofile}} - Unable to access UserProfile model fields in templates in Django. Tried {{ user.userprofile }} Django-从另一个使用User作为OneToOne的模型创建User实例 - Django - Create a User instance from another model that uses User as a OneToOne 扩展Django用户模型OneToOne-用户配置文件未保存 - Extending the Django User Model OneToOne - User profile not saving Django用户每日更新模型 - Django user daily updating model 从 OneToOne 用户 model 加载时,Django 管理员非常慢 - Django admin is very slow when loading from the OneToOne user model 使用Auth,用户模型,视图,序列化器的Django API OneToOne关系 - Django API OneToOne relationship using Auth, User model, Views, Serializers 在Django模型中提取OneToOne字段 - Extract OneToOne Field in django model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM