用户匹配查询不存在 - django

时间:2015-01-15 10:43:20

标签: django django-views django-users

我有一个页面显示用户及其关于。在那里,有一个链接来更新他们的关于。但是,当我打开该链接时,它会向我显示此错误:

DoesNotExist at /profile/user/update_about/

User matching query does not exist.

回溯突出显示此行,该行来自视图中的profile方法:

13.  user = User.objects.get(username=unquote(user_name)) 

但是,当我加载profile方法时,不会发生此错误。它仅出现在视图中的update_profile方法上。

views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from urllib import unquote

from django.contrib.auth.models import User

from models import About
from forms import AboutForm
# Create your views here.


def profile(request, user_name):
    user = User.objects.get(username=unquote(user_name))
    about = About.objects.get_or_create(user=user)
    about = about[0]

    return render(request, 'user_profile.html', {
        'user':user,
        'about_user':about
    })

def update_about(request, user_name):
    user = User.objects.get(username=unquote(user_name))
    if request.method == 'POST':
        form = AboutForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        about = About.objects.get(user=user)
        form = AboutForm(initial={'dob':about.dob})
        return render(request, 'update_about.html',{
            'form':form
        })

urls.py

urlpatterns = patterns('',
    # Examples:
    url(r'(?P<user_name>[\w@%.]+)/$', 'user_related.views.profile', name='profile'),
    url(r'(?P<user_name>[\w@%.]+)/update_about/$', 'user_related.views.update_about', name='update_about'),

造成这种情况的原因是什么?非常感谢您的帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

您忘记在正则表达式的第一个位置添加插入符号(^)。因此,第一个正则表达式与URL的“update_about /”部分匹配。

固定代码:

url(r'^(?P<user_name>[\w@%.]+)/$', 'user_related.views.profile', name='profile'),
url(r'^(?P<user_name>[\w@%.]+)/update_about/$', 'user_related.views.update_about', name='update_about'),