views.py for onetoone 扩展用户模型添加个人资料信息

views.py for extended user model by onetoone to add profile information

我正在扩展 User 模型以使用一对一关系添加个人资料信息。用户应该能够更改基本的用户个人资料信息。 views 应该是什么来添加这样的功能?

这是我的模型

Models.py

class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.CharField(max_length=100, default='No description field')
city = models.CharField(max_length=100, default='Location not added')
phone = models.CharField(max_length=10, default='',blank= True)
image = models.ImageField(upload_to='products/profile/%Y%/%m/%d', blank=True)

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

这是我的表格

forms.py

class UserForm(forms.ModelForm):

class Meta():
    model = UserProfile
    fields = ['description', 'city', 'phone', 'image']

我的观点应该包括什么?

views.py

@login_required()
def edit_profile(request):
pass

我想更新扩展 UserProfile 实例的模型,以覆盖以前的信息并更新新信息。

您需要像处理任何其他常用表单一样处理视图中的 UserForm

这里是你需要做的:

views.py

def edit_profile(request):
    if request.method == 'POST':
        # don't forget to pass request.FILES since you have imageField
        form = UserForm(request.POST,
                        request.FILES,
                        instance=request.user.userprofile)
        if form.is_valid():
            form.save()
            return redirect(reverse('to_user_profile_url'))
    else:
        form = UserForm(instance=request.user.userprofile)
    context = {'form': form}
    return render(request, 'edit_profile_template', context)