我试图编辑个人资料但我收到了这个错误 "在/ blog / edit /中不存在,用户匹配查询不存在。"
def Profil(request, username):
if request.user.is_authenticated():
base_template_name = 'blog/base.html'
else:
base_template_name = 'blog/visitor.html'
user = User.objects.get(username=username)
logged_in_user_posts = Post.objects.filter(user=user)
context = {'base_template_name':base_template_name}
return render(request, 'blog/profil.html', {'user':user, 'posts':logged_in_user_posts})
def update_profile(request):
if request.method == 'POST':
profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)
if profile_form.is_valid():
profile_form.save()
messages.success(request, ('Your profile was successfully updated!'))
return redirect('blog:index')
else:
messages.error(request, ('Please correct the error below.'))
else:
profile_form = ProfileForm(instance=request.user.profile)
return render(request, 'blog/edit_profile.html', {
'profile_form': profile_form })
在urls.py中:
url(r'^(?P<username>\w+)/$', views.Profil, name = 'profil'),
url(r'^edit/$', views.update_profile, name='edit_profile'),
答案 0 :(得分:0)
此错误来自user = User.objects.get(username=username)
行。 get()
函数只提供1个匹配项,如果没有任何匹配项,则会抛出DoesNotExist
错误。要解决此问题,您需要使用try - except:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# There is no such user, throw 404 or do anything else