毕竟页面没有通过,我觉得我做的一切都是正确的。有人可以发现我的错误

时间:2015-03-08 13:54:55

标签: python html django

页面未通过。我无法发现我出错的地方。它显示:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/deals/2015/03/first-lady/

Django 1.6
Python 2.7

views.py

from django.shortcuts import render, Http404
from .models import Deal

def deal_detail(request, year, month, slug):
    try:
        post = Deal.objects.filter(publish_date__year=year).filter(publish_date__month=month).get(slug=slug)
    except Deal.MultipleObjectsReturned:
        post = Deal.objects.filter(publish_date__year=year).filter(publish_date__month=month).filter(slug=slug)[0]
    except:
        raise Http404

    context = {
        'year': year,
        'month': month,
        'slug': slug,
        'post': post,
    }

    return render(request, 'deals/deal_detail.html', context)

主页上有一个链接指向deal / deal_detail.html

<a href="/deals/{{ post.publish_date|date:'Y' }}/{{ post.publish_date|date:'m' }}/{{ post.slug }}" class="btn btn-primary" role="button">View</a>

deal_detail.html

{% extends 'base.html' %}
{% block content %}
{{ year }}

{{ month }}

{{ slug }}

<h2>{{ post.title }}</h2>
<p>{{ post.description }}</p>

{%  endblock %}

urls.py

url(r'^deals/(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>.*)/$', 'deals.views.deal_detail', name='deal_detail'),

2 个答案:

答案 0 :(得分:1)

?P仅在您希望组匹配的子字符串可通过符号组名称访问时使用。有关更详细的说明,请参阅Python regular expression docs

因为您没有按名称引用正则表达式,所以您只想完全排除?P

url(
    r'^deals/(\d{4})/(\d{2})/(.*)/$', 
    'deals.views.deal_detail',
    name='deal_detail'
),

答案 1 :(得分:0)

同样尝试只有一个filter,Django有时会在链接这样的查询时产生奇怪的SQL。

instance = Deal.objects.get(publish_date__year=year, publish_date__month=month, slug=slug)
queryset = Deal.objects.filter(publish_date__year=year, publish_date__month=month, slug=slug)