我有一个基本的 Django 应用程序,其中除了用户模型之外,我还使用扩展了配置文件模型一对一字段.
模型.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}'
In admin.py我已经注册了 Profile 模型,如下所示:
from myapp import Profile
class ProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'phone_number')
admin.site.register(Profile, ProfileAdmin)
并且在用户模型中成功创建了配置文件模型。
在为用户创建新帐户时在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')
但是,在注册页面创建新用户帐户时,我遇到以下错误:
我不明白如何使用 save() 方法保存配置文件模型的那些新创建的字段。
更新:找到解决方案-
在views.py中,这就是我在Profile模型中保存字段的方式
p = Profile(user=c, phone_number=contact_number_r, profile_picture=profile_picture_r)
p.save()
现在,每当我注册新用户时,用户名、个人资料图片和电话号码也会添加到个人资料模型中,甚至在删除/更新个人资料详细信息期间,更改也会反映在用户和个人资料模型中
以下链接对我的项目要求很有用:
http://books.agiliq.com/projects/django-orm-cookbook/en/latest/one_to_one.html http://books.agiliq.com/projects/django-orm-cookbook/en/latest/one_to_one.html