[英]Editing profile user Django
我正在尝试编辑配置文件,但出现此错误“ / blog / edit /中的DoesNotExist,用户匹配查询不存在。”
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'),
此错误来自user = User.objects.get(username=username)
行。 get()
函数仅给出1个匹配项,如果不存在任何匹配项,则会引发DoesNotExist
错误。 要解决该问题,您将需要使用try-除外:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# There is no such user, throw 404 or do anything else
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.