且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

django:使用一对一扩展用户模型:如何保存()配置文件模型的字段

更新时间:2022-12-05 21:07:35

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

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.