slu with有问题

时间:2016-04-03 08:35:27

标签: django django-templates slug

我正在写一个模型在线商店django应用程序,想要在其中加入slug。打开页面时遇到问题。 这是我的模特:

from __future__ import unicode_literals
from django.db import models
from django.db.models.signals import pre_save
from django.utils .text import slugify

class Customer(models.Model):
    customer_name = models.CharField(max_length=200)
    slug = models.SlugField(unique = True)
    def __str__(self):
        return self.customer_name

    def get_absolute_url(self):
        return reverse("OnlineShop:order", kwargs={"slug": self.slug})

def pre_save_customer_receiver(sender, instance, *args, **kwargs):
    slug = slugify(instance.customer_name)
    exists = Customer.objects.filter(slug = slug).exists()
    if exists:
        slug = "%s-%s" % (slug,instance.id)
    instance.slug=slug

pre_save.connect(pre_save_customer_receiver, sender = Customer)

这是我的观点:

def customer(request):
    customer_list = Customer.objects.all()
    template_path = 'OnlineShop/customer.html'
    context={
        'customer_list':customer_list,
    }
    return render(request,template_path,context)

def order(request,slug):
    Customer = Customer.objects.filter(slug=slug)
    ''' some code from here '''

我的模板customer.html:

<h1>List of Customers:</h1>
<ul>
    {% for customer in customer_list %}
        <li><a href='{% url 'order' customer.slug %}'>{{ customer.customer_name }}<br></li>
    {% endfor %}
</ul>

NoReverseMatch at /OnlineShop/

这是我的urls.py

       from django.conf.urls import url
       from . import views

       urlpatterns=[
       url(r'^$',views.customer, name='customer'),
       url(r'^customer/(?P<slug>[\w-]+)$',views.order, name='order'),
       ]

模板中有问题吗?有什么问题?

1 个答案:

答案 0 :(得分:0)

我希望你已经定义了urls.py,如下所示

from django.conf.urls import url, include

from . import views

onlineshop_patterns = [
    url(r'^$', views.customer, name='customer'),
    url(r'^customer/(?P<slug>[\w-]+)$', views.order, name='order'),
]

urlpatterns = [
    # ...
    url(r'^OnlineShop/', include(onlineshop_patterns)),
    # ...
]

阅读Reverse resolution of URLsRegex for SlugField