Models.py:
from django.contrib.auth.models import User
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=225)
class Meta:
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
class Item(models.Model):
Category = models.ForeignKey(Category,related_name='items', on_delete=models.CASCADE )
name = models.CharField(max_length=225)
description = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to='item_images', blank=True, null=True)
created_by = models.ForeignKey(User, related_name='items', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
views.py:
from django.shortcuts import render , get_object_or_404
from .models import Item
def detail(request, pk):
item = get_object_or_404(Item, pk=pk)
return render(request, 'item/detail.html',{
'item': item
})
detail.html:
{% extends 'core/base.html' %}
{% block title %}{{ item.name }}{% endblock %}
{% block content %}
<div class="grid grid-cols-5 gap-6">
<div class="col-span-3">
<img src="{{ item.image.url }}" class="rounded-xl">
</div>
</div>
{% endblock %}
index.html:
{% extends 'core/base.html' %}
{% block title %}Welcome{% endblock %}
{% block content %}
<div class="mt-6 px-6 py-12 bg-gray-100 rounded-xl">
<h2 class="mb-12 text-2xl text-center">Newest Oportunity</h2>
<div class="grid grid-cols-3 gap-3">
{% for item in items %}
<div>
<a href="#">
<div>
<img src="{{ item.image.url }}" class="rounded-t-xl">
</div>
<div class="p-6 bg-white rounded-b-xl">
<h2 class="text-2xl">{{ item.name }}</h2>
</div>
</a>
</div>
{% endfor %}
</div>
</div>
<div class="mt-6 px-6 py-12 bg-gray-100 rounded-xl">
<h2 class="mb-12 text-2xl text-center">Categories</h2>
<div class="grid grid-cols-3 gap-3">
{% for category in categories %}
<div>
<a href="{% url 'item:detail' item.id %}">
<div class="p-6 bg-white rounded-b-xl">
<h2 class="text-2xl">{{ category.name }}</h2>
<p class="text-gray-500">{{ category.items.count }} items</p>
</div>
</a>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
url.py:
from django.urls import path
from . import views
app_name = 'item'
urlpatterns = [
path('<int:pk>/', views.detail, name='detail'),
]
url.py:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from core.views import index, contact
urlpatterns = [
path('contact/',contact, name='contact'),
path('items/', include('item.urls')),
path('', index, name='index'),
path("admin/", admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
错误:
Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['items/(?P<pk>[0-9]+)/\\Z']
我希望当我点击项目时,它会在不同的页面上给予我它的具体细节,因为每个类别都有不同的项目,问题似乎在于我传递主键的方式。我正在使用Anaconda 3和Visual Studio代码。
1条答案
按热度按时间nwo49xxi1#
在item.idfor循环的类别中有www.example.com。我猜你想在items for循环之前拥有它。在for循环的类别中,它是空的: