该网站非常简单,只有 3 页,主页和 urls.py 中显示的第二个 URL 效果很好,但是当我从主题转到单元页面时,我得到了:
类型错误在/主题/单位/英语
units(( 有一个意外的关键字参数 'slug'
我不知道为什么我会收到此错误.. 在 Django 2.0 中对 URL 和路径进行的新修改我阅读了文档,但我不太了解<slug>
部分,是不是<slug> or <slug:slug>
我不明白它,第一个和第二个的含义是什么???..在模板文件夹中,{% url 'units' item.slug %}
单位是路径的名称,但是 - item.slug - 对吗?如果有人向我解释,我将不胜感激。
models.py
class Unit(models.Model):
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
name = models.CharField(max_length=250)
description = models.TextField(blank=True, null=True)
archived = models.BooleanField(default=False)
slug = models.SlugField(max_length=250, unique=True)
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
updated = models.DateTimeField(auto_now=True, null=True, blank=True)
seo_name = models.CharField(max_length=60, blank=True, null=True)
seo_description = models.CharField(max_length=165, blank=True,
null=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Unit, self).save(*args, **kwargs)
def __str__(self):
return self.name
views.py
from django.http import HttpResponse
from django.template import loader
from .models import Subject, Unit, Lesson
def units(request):
all_units = Unit.objects.filter(active=True).order_by('-id')[:]
template = loader.get_template('sheets/units.html')
context = {
'all_units': all_units
}
return HttpResponse(template.render(context, request))
urls.py
from django.urls import path
from .views import subjects, units, lessons
urlpatterns = [
path('subjects/', subjects, name='subjects'),
path('units/<slug:slug>', units, name='units'),
path('lessons/<slug:slug>', lessons, name='lessons'),
]
单位.html
<div class="blog-posts">
<div class="row text-center">
{% for item in all_units %}
<div class="col-sm-4 wow fadeInUp animated" data-wow-duration="1000ms" data-wow-delay="400ms"
style="visibility: visible;animation-duration: 1000ms;animation-delay: 400ms;animation-name: fadeInUp; margin-bottom: 15px">
<div class="post-thumb">
<a href="#"><img class="img-responsive" src="/static/img/blog/1.jpg" alt=""></a>
</div>
<div class="entry-header">
<h3><a href="{% url 'units' item.slug %}">{{ item.name }}</a></h3>
<span class="date">{{ item.created }}</span>
</div>
<div class="entry-content">
<p>{{ item.description|truncatechars:120 }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
def units(request,slug):
all_units = Unit.objects.filter(active=True).order_by('-id')[:]
template = loader.get_template('sheets/units.html')
context = {
'all_units': all_units
}
return HttpResponse(template.render(context, request))
您还需要在视图函数中传递 slug,因为您在 URL 中提到了一个名为 slug
的参数