NoReverseMatch(与pk相关):django

时间:2012-11-04 23:50:15

标签: django django-forms django-templates primary-key

我想从表单中获取发布数据并显示它们。 我使用“{%url uasite1.views.sell_detail sell_detail.pk%}”来根据他们的pk提取数据。

然而,只有[NoReverseMatch···,反向'uasite1.views.sell_detail'与参数'('',)'和关键字参数'{}'找不到。]出现了。 我的代码出了什么问题?

models.py

from django.db import models
from django.forms import ModelForm

class Sell(models.Model):
    subject = models.CharField(max_length=100)
    price = models.CharField(max_length=100)
    condition = models.CharField(max_length=100)
    email = models.EmailField()
    body = models.CharField(max_length=200)

forms.py

from django.forms import ModelForm
from uasite1.models import Sell

class SellForm(ModelForm):
    class Meta:
        model = Sell

views.py

from django.shortcuts import render_to_response,get_object_or_404
from django.http import HttpResponseRedirect
from uasite1.forms import SellForm
from uasite1.models import Sell
from django.template import RequestContext


def sell_detail(request, pk):
    sell = get_object_or_404(Sell, pk=int(pk))
    return render_to_response('sell_display.html',{'sell':sell})

def sell_create(request):
    context = {}
    if request.method == 'POST':
        form = SellForm(request.POST)
        if form.is_valid():
            new_sell = form.save()
            return HttpResponseRedirect('/sechand/%d/' % new_sell.pk)
    else:
        form = SellForm()
    context['form'] = form
    return render_to_response('sell.html',context,context_instance = RequestContext(request))

def Electronics(request):
    latest_sell_list = Sell.objects.all()[:5]
    return render_to_response('electronics.html',{'latest_sell_list':latest_sell_list})

urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^sechand/$','uasite1.views.sell_create'),
    url(r'^sechand/(\d+)/$', 'uasite1.views.sell_detail'),
    url(r'^electronics/$', 'uasite1.views.Electronics'),
    url(r'^admin/', include(admin.site.urls)),
)

electronics.html

{% extends 'base.html' %}
{% block extrahead %}
    <p><strong>Electronics</strong></p>

{% endblock %}

{% block content %}

    <p><a href="{% url uasite1.views.sell_detail sell_detail.pk %}">{{ sell.subject }}</a></p>

{% endblock %}

2 个答案:

答案 0 :(得分:2)

更改
<a href="{% url uasite1.views.sell_detail sell_detail.pk %}">

于:
<a href="{% url uasite1.views.sell_detail sell.pk %}">

答案 1 :(得分:0)

有几个错误。

1:更改您的网址

url(r'^sechand/(\d+)/$', 'uasite1.views.sell_detail'),

url(r'^sechand/(P<pk>\d+)/$', 'uasite1.views.sell_detail'),

这使得url接受通过pk传递给视图的参数。

2:您的Electronics()视图建议您将列表传递给模板,因此您需要更新模板以迭代此列表并适当地呈现列表中的每个项目。并确保正确使用变量名称。

{% block content %}

    {%for sell in latest_sell_list %}
        <p><a href="{% url uasite1.views.sell_detail sell.pk %}">{{ sell.subject }}</a></p>

    {%endfor%}
{% endblock %}