我已经阅读了一些帖子,但我无法找到我想要的内容。
我试图找出如何获取用户的UserProfile。我在创建用户配置文件时创建了一对一的字段关系。我以为我可以按原样查询UserProfile,但我无法让它工作。
def profile_edit(request):
user = UserProfile.objects.get(user=request.user)
return render(request, 'medium/profile_edit.html', {'user_profile_form': form,
'current_user': user})
有什么想法?这是我的models.py和views
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,)
bio = models.TextField(blank=True)
avatar = models.ImageField(upload_to='avatars', blank=True)
def register_user(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
user_profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and user_profile_form.is_valid():
new_user = user_form.save()
new_user.set_password(new_user.password)
new_user.save()
new_user_profile = user_profile_form.save(commit=False)
new_user_profile.user = new_user
if 'avatar' in request.FILES:
new_user_profile.avatar = request.FILES['avatar']
new_user_profile.save()
registered = True
else:
print(user_form.errors, user_profile_form.errors)
else:
user_form = UserForm()
user_profile_form = UserProfileForm()
return render(request, 'medium/registration.html', {
'user_form': user_form,
'user_profile_form': user_profile_form,
'registered': registered
})
答案 0 :(得分:0)
当然,经过2小时的谷歌搜索,我终于明白了。
我在我的模型上放了一个related_name,然后在视图中添加了它
def profile_edit(request):
user_form = UserForm(instance=request.user)
user_profile_form = UserProfileForm(instance=request.user.profile)
return render(request, 'medium/profile_edit.html', {
'user_profile_form': user_profile_form,
'user_form': user_form,
})