【问题标题】:Having trouble with slug蛞蝓有问题
【发布时间】:2016-07-22 20:24:24
【问题描述】:

我正在编写一个模型在线商店 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>

这是我的 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'),
       ]

是模板的问题吗?怎么了?

【问题讨论】:

  • 你能用urls.py编辑你的问题吗?

标签: django django-templates slug


【解决方案1】:

我希望你已经定义了你的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

【讨论】:

  • 我在模板中询问问题的原因是,在模板中,当我用 customer.id 替换 customer.slug 时,至少成功调用了 views.customer。在那里我不会遇到任何麻烦。当我在模板中有 customer.slug 时,问题就出现了。
  • 你能发布一个示例 slug 吗?
  • 好的,找到问题了,TY。我不得不将 url 中 slug 的正则表达式从 (?P[\w-]+) 修改为 (?P[\w-]*) 并在查看代码的顺序中稍作修改我还没有发布。 :)
猜你喜欢
  • 2011-10-18
  • 1970-01-01
  • 1970-01-01
  • 2011-02-09
  • 2013-02-02
  • 1970-01-01
  • 2011-02-28
  • 2014-07-30
  • 2016-06-02
相关资源
最近更新 更多