各位大神晚安,目前正在使用django架設練習網頁,在設置Django urls name一直發生錯誤,請問有無熟悉django的大神可以給點方向!
以下是我的程式碼
urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.showtemplate),
path('<int:id>/', views.singleVendor, name='vendor_id'), # 這一行
path('create', views.vendor_create_view),
]`
views.py
from django.shortcuts import render
from .models import Vendor
from .forms import VendorForm #import相對應的model Form
from .forms import RawVendorForm # 新增 RawVendorForm
from django.http import Http404
from django.shortcuts import get_object_or_404
# Create your views here.
def showtemplate(request):
vendor_list = Vendor.objects.all() # 把所有 Vendor 的資料取出來
context = {'vendor_list': vendor_list} # 建立 Dict對應到Vendor的資料,
return render(request, 'vendors/vendor_detail.html', context)
#建立class [vendor_create_view]
def vendor_create_view(request):
form = RawVendorForm(request.POST or None)
if form.is_valid():
Vendor.objects.create(**form.cleaned_data)
form = RawVendorForm()
context = {
'form' : form
}
return render(request, "vendors/vendor_create.html", context)
def singleVendor(request, id):
vendor_list = get_object_or_404(Vendor, id=id)
# try:
# vendor_list = Vendor.objects.get(id=id)
# except Vendor.DoesNotExist:
# raise Http404
context = {
'vendor_list': vendor_list
}
return render(request, 'vendors/vendor_detail.html', context)
modles.py
from django.db import models
# 新增
from django.contrib import admin
# 額外 import 這個過濾套件
from django.utils.translation import gettext_lazy as _
from django.urls import reverse #新增
# Create your models here.
class Vendor(models.Model):
vendor_name = models.CharField(max_length = 20) # 攤販的名稱
store_name = models.CharField(max_length = 10) # 攤販店家的名稱
phone_number = models.CharField(max_length = 20) # 攤販的電話號碼
address = models.CharField(max_length = 100) # 攤販的地址
#新增
def get_absolute_url(self):
return reverse("vendor_id", kwargs={"id": self.id})
vedor_detail.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% extends "base.html" %}
{% block title %} My store {% endblock %}
{% block content%}
{% for vlist in vendor_list %}
<h1> 店家 : {{vlist.vendor_name}} </h1>
<p> <a href= {{ vlist.get_absolute_url }}> More detail...</a> </p>
{% endfor %}
{% endblock %}
</body>
</html>
錯誤原因:TypeError at /vendor/1/
'Vendor' object is not iterable
Request Method: GET
Request URL: http://127.0.0.1:8000/vendor/1/
Django Version: 2.2.3
Exception Type: TypeError
Exception Value:
'Vendor' object is not iterable
有google原因是因對跌代,試著修改vedor_detail,還是會顯示失敗,請各位大神幫幫忙