我无法使用html访问我的类别模型。
我通过点击“ Category.objects.all()”从外壳访问。我访问我的项目模型,但不能访问类别模型。我猜这是关于类别模型的结构的。但是我不知道如何解决这个问题。即使使用“ {{categories}}”,我也无法到达
这是我的模型。py:
class Category(models.Model):
title = models.CharField(max_length=255, verbose_name="Title")
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['title']
def __str__(self):
return self.title
class Item(models.Model):
seller = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.PROTECT)
title_image = models.ImageField(upload_to='media/img', default='None')
created_date = models.DateTimeField(default=timezone.now)
updated_date = models.DateTimeField(auto_now=True, verbose_name="Updated at")
published_date = models.DateTimeField(blank=True, null=True)
is_published = models.BooleanField(default=False, verbose_name="Is published?")
end_date = models.DateTimeField(blank=False, default=seven_days_hence)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
views.py:
def category_list(request):
categories = Category.objects.all()
return render(request, 'blog/item_list.html', {'categories': categories})
def item_list(request):
items = Item.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/item_list.html', {'items': items})
urls.py:
urlpatterns = [
path('', views.item_list, name='item_list'),
path('', views.category_list, name='category_list'),
path('item/<int:pk>/', views.item_detail, name='item_detail'),
path('item/new/', views.item_new, name='item_new'),
path('item/<int:pk>/edit/', views.item_edit, name='item_edit'),
]
base.html:
% load staticfiles %}
<html>
<head>
<title>İkinci El Eşya Al Sat</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
</head>
<body>
<div class="page-header">
<a href="{% url 'item_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a>
<h1><a href="/">İkinci El Eşya Al Sat</a></h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-8">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
item_list.html:
{% extends 'blog/base.html' %}
{% block content %}
{% for category in categories %} {{ category.title }} {% endfor %}
{% for item in items %}
<div class="item">
<div class="date">
{{ item.published_date }}
</div>
<h1><a href="{% url 'item_detail' pk=item.pk %}">{{ item.title }}</a></h1>
<img src="{{ item.title_image.url }}" alt="img">
<p>{{ item.text|linebreaksbr }}</p>
</div>
{% endfor %}
{% endblock %}