django:使用一对一扩展用户模型:如何保存()配置文件模型的字段 [英] django: Extending user model using one-to-one: how to save() Profile model's fields

查看:101
本文介绍了django:使用一对一扩展用户模型:如何保存()配置文件模型的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的Django应用程序,其中我与用户模型一起使用一对一字段扩展了Profile模型。

I have a basic Django application, wherein along with the User model I have extended the Profile model using One-to-one field.

Models.py

Models.py

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE,  null=True)
  profile_picture = models.ImageField(upload_to='customer_profile_images/%Y/%m/%d/', null=True, blank=True, verbose_name="Profile Picture")
  phone_number = models.CharField(null=True, blank=True, max_length=10)

  # no need for following two methods
  # def create_user_profile(sender, instance, created, **kwargs):
    # if created:
        # Profile.objects.get_or_create(user=instance)

  # post_save.connect(create_user_profile, sender=User)

  def __str__(self):
     return f'{self.user.first_name} {self.user.last_name}'

admin.py 中,我已将个人资料模型注册为遵循:

In admin.py I have registered the Profile model as follow:

from myapp import Profile


class ProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'phone_number')

admin.site.register(Profile, ProfileAdmin)

,并且已在User模型中成功创建了个人档案模型。

And a Profile model is being successfully created within the User model.

并且在创建新帐户时用户 in views.py

And at the time of creating a new account for a user in views.py

class CustomerSignUpView(View):
def post(self, request):
    name_r = request.POST.get('customer_username')
    password_r = request.POST.get('customer_password')
    email_r = request.POST.get('customer_email')
    contact_number_r = request.POST.get('customer_contact_number')
    profile_picture_r = request.FILES['customer_profile_picture']

     # this is how i am saving contact number, profile picture for Profile model.

    if checkemail(email_r):
        c = User.objects.create_user(username=name_r, password=password_r, email=email_r)
        c.save()

        # add the following code
        p = Profile(user=c, phone_number=contact_number_r, profile_picture=profile_picture_r)
        p.save()       

        return render(request, 'catalog/customer_login.html')
    else:
        return render(request, 'catalog/customer_signup.html')

def get(self, request):
    return render(request, 'catalog/customer_signup.html')

但是,在创建新用户时帐户在注册页面中,我遇到以下错误:

However, while creating a new user account in sign up page, i encounter the following error:

我不知道如何使用save()方法保存这些新创建的Profile模型字段。

更新:找到解决方案-

在views.py中,这就是我在其中保存字段的方式个人资料模型

In views.py, this is how I am saving fields inside Profile model

     p = Profile(user=c, phone_number=contact_number_r, profile_picture=profile_picture_r)
     p.save()

现在,每当我注册新用户时,用户名,个人资料图片和电话号码也会添加到个人资料模型中,甚至在删除/更新个人资料详细信息期间,更改也会反映在用户和个人资料模型中

以下链接对于我的项目要求非常有用:

Following link is useful for my project requirements:

http://books.agiliq.com/projects/django-orm-cookbook/zh-CN/latest/one_to_one.html

推荐答案

首先,保存用户后无需保存配置文件实例:

First of all, there is none need of saving the instance of the profile after saving a User:

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

删除上面的代码。要回答您的问题,如果未创建用户实例,则您不想创建配置文件实例,因此无需为此担心。请在您的 admin.py 中添加以下代码,以将admin用户表单与配置文件1合并。

delete above code. To answer your question, if User instance is not created then you don't want to create a profile instance so no need of worrying on that part. Please, add below code to your admin.py to have admin User form merged with profile one.

class ProfileInline(admin.StackedInline):    
    model = Profile
    can_delete = False
    verbose_name_plural = 'Profile'
    fk_name = 'user'

此外,建议您阅读

您不应获取值直接从职位。这不是安全的方法。我可以使用基本形式并从 cleaned_data 字典中获取数据,也可以使用ModelForm。

You should not get the values directly from the post. This is not a secure way. Either use basic form and get data from cleaned_data dictionary or use ModelForm.

我假设您是Django的新手如果您不太着迷于使用基于类的视图,则建议您使用基于函数的视图。您会很容易的,因为您将看到所有步骤。

I assume you are new in the Django and if you are not too obsessed with using a class-based view, would suggest you use function-based one. It will be easy for you are you will see all the steps.

关注一个。如果没有,则将解决您的问题,因此您可以将代码调整为该代码。

Follow this one. If not this will solve your issue, so you can adjust your code to this one.

这篇关于django:使用一对一扩展用户模型:如何保存()配置文件模型的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆