i'm trying to edit a profile but I got this error "DoesNotExist at /blog/edit/, User matching query does not exist."
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 })
In the urls.py:
url(r'^(?P<username>\w+)/$', views.Profil, name = 'profil'),
url(r'^edit/$', views.update_profile, name='edit_profile'),
This error comes from user = User.objects.get(username=username)
line. get()
function gives only 1 match and if there is no any match it throws DoesNotExist
error. To solve the problem you will need to use try - except:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# There is no such user, throw 404 or do anything else
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.