RelatedObjectDoesNOTE存在-编辑配置文件 [英] RelatedObjectDoesNOTExist-Edit profile
问题描述
Django==1.10.5.我有一个问题 RelatedObjectDoesNotExist视图.py:
Django==1.10.5. I have a problem RelatedObjectDoesNotExist Views.py:
def register(request):
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# Create a new user object but avoid saving it yet
new_user = user_form.save(commit=False)
# Set the chosen password
new_user.set_password(user_form.cleaned_data['password'])
# Save the User object
new_user.save()
# Create the user profile
profile = Profile.objects.create(user=new_user)
return render(request,
'account/register_done.html',
{'new_user': new_user})
else:
user_form = UserRegistrationForm()
return render(request, 'account/register.html', {'user_form': user_form})
和
@login_required
def edit(request):
if request.method == 'POST':
user_form = UserEditForm(instance=request.user,
data=request.POST)
profile_form = ProfileEditForm(instance=request.user.profile,
data=request.POST,
files=request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
else:
user_form = UserEditForm(instance=request.user)
profile_form = ProfileEditForm(instance=request.user.profile)
return render(request, 'account/edit.html', {'user_form': user_form,
'profile_form': profile_form})
问题在于:profile_form = ProfileEditForm(instance=request.user.profile)
The problem is that: profile_form = ProfileEditForm(instance=request.user.profile)
推荐答案
我在这个特定的练习上有类似的经验.错误来自下面的代码
I have similar experience working on this particular exercise. The error is coming right from code below
Profile_form = ProfileForm(request.POST, instance=request.user.profile)
Profile_form = ProfileForm(request.POST, instance=request.user.profile)
我们试图让 "request.user.profile" 没有意识到模型中的 "User" 没有 "profile" 但 Profile 有一个 "User" .因此,获得个人资料"的更好方法是:
We are trying to get "request.user.profile" not realizing "User" in the model doesn't have a "profile" but a Profile has a"User" . Therefore a better way to get the "profile":
profile = Profile(user=request.user)
因此您的编辑方法应该与此类似:
Hence your edit method should look close to this:
@login_required
def edit(request):
profile = Profile(user=request.user)
if request.method == 'POST':
user_form = UserEditForm(instance=request.user,data=request.POST)
profile_form = ProfileEditForm(instance=profile,
data=request.POST,
files=request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, 'Profile updated successfully')
else:
messages.success(request, 'Error updating your profile')
user_form = UserEditForm(instance=request.user)
profile_form = ProfileEditForm(instance=profile)
return render(request,
'accounts/edit.html',
{'user_form': user_form,
'profile_form': profile_form})
这篇关于RelatedObjectDoesNOTE存在-编辑配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!