来自DetailView中类别的url路径

时间:2018-10-11 10:15:15

标签: django django-urls

我使用DetailView来显示类别内的所有元素。

我正在尝试将我的类别标签作为url中的变量。但是我不知道如何在类别和细节之间建立联系。

到目前为止,当我单击Index.html中生成的链接之一(例如http://localhost:8000/oneofthecategories)时,出现以下错误:

Exception Type: FieldError
Exception Value:    
Cannot resolve keyword 'slug' into field. Choices are: author, category, category_id, id, title

文件:

#Models.py

class categories(models.Model):
    name = models.CharField(max_length=50,unique=True)
    slug = models.SlugField(max_length=100,unique=True)

    def __str__(self):
        return self.name

class details(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=42)
    category = models.ForeignKey('categories', on_delete=models.CASCADE,related_name="detail")

def __str__(self):
    return self.title

#Views.py

class IndexView(generic.ListView):
    model = categories
    context_object_name = "list_categories"
    template_name='show/index.html'

class CategoryDetails(DetailView):
    model = details
    context_object_name = "detail"
    template_name = "show/categories.html"
    slug_url_kwarg = 'slug'

#Urls.py

urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<slug:slug>', views.CategoryDetails.as_view(), name='category_details'),
]

#Index.html

{% load staticfiles %}

<p>These is a list of categories</p>

{% for category in list_categories %}
    <div class="article">
    <h3>{{ category.name }}</h3>

    {% for detail in category.categories.all %}
        <p> {{detail.title}} </p>
        <li><a href="{% url 'category_details' category.slug %}">URLS</a></li>
    {% endfor %}
</div>

0 个答案:

没有答案