Django 鼻涕虫有问题吗
我在写一个网上商店django的应用程序,想把slug加入其中。在打开一页时有困难。 这是我的模型:Django 鼻涕虫有问题吗,django,django-templates,slug,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_n
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>
客户名单:
{customer_list%}中的客户为%
-
这是我的URL.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'),
]
从django.conf.url导入url
从…起导入视图
URL模式=[
url(r'^$',views.customer,name='customer'),
url(r'^customer/(?P[\w-]+)$”,views.order,name='order'),
]
模板中是否存在问题?怎么了?我希望您已经像下面那样定义了url.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)),
# ...
]
从django.conf.url导入url,包括
从…起导入视图
网上购物模式=[
url(r'^$',views.customer,name='customer'),
url(r'^customer/(?P[\w-]+)$”,views.order,name='order'),
]
URL模式=[
# ...
url(r“^OnlineShop/”,包括(OnlineShop_模式)),
# ...
]
阅读并。你能用url.py
编辑你的问题吗?我之所以在模板中询问这个问题,是因为在模板中,当我用customer.id替换customer.slug时,在这种情况下至少调用了views.customer。在那里,我没有面临任何麻烦。当我在模板中有customer.slug时,问题就出现了。你能发布一个slug示例吗?好的,我解决了问题,TY。我不得不将url中slug的正则表达式从(?P[\w-]+)修改为(?P[\w-]*),并在order视图中稍作修改,我还没有发布代码。:)