![](/img/trans.png)
[英]Django get returns ValueError: Field 'id' expected a number but got <string>
[英]Django Field 'id' expected a number but got '<string>'
我正在嘗試為我的 Django 項目制作一個類別頁面。 當我測試 url 時一切正常; 但是當我嘗試傳遞過濾帖子的類別 object 時,我收到此錯誤: Field 'id' expected a number but got '<string>'
。
“類別”是我的帖子 model 中的外鍵,我知道它傳遞的默認值是 ID。 如何傳遞字符串本身而不是 id?
這是我的模型.py:
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime, date
class Category(models.Model):
name = models.CharField(max_length = 32, default='Uncategorized')
def __str__(self):
return self.name
class Post(models.Model):
...
category = models.ForeignKey(Category, on_delete=models.CASCADE)
...
def __str__(self):
return self.title + ' | ' + str(self.author)
這是我的 views.py:
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post, Category
class BlogView(ListView):
model = Post
template_name = 'blog/blog.html'
ordering = ['-updated_on']
def get_context_data(self, *args, **kwargs):
categories = Category.objects.all()
context = super(BlogView, self).get_context_data(*args, **kwargs)
context['categories'] = categories
return context
def CategoryView(request, cats):
category_posts = Post.objects.filter(category=cats)
return render(request, 'blog/categories.html', {'cats': cats, 'category_posts': category_posts})
這是我的 urls.py:
from django.urls import path
from . import views
urlpatterns = [
...
path('blog', views.BlogView.as_view(), name='blog'),
path('blog/<int:pk>', views.BlogDetailView.as_view(), name='blog-detail'),
path('category/<str:cats>/', views.CategoryView, name='category'),
...
]
這是我的 HTML 文件:
{% extends 'blog/base.html' %}
{% block title %}
| {{ cats }}
{% endblock %}
{% block body %}
...
<div class="header-container" >
<h1>{{ cats }}</h1>
</div>
...
{% endblock %}
更改 urls.py,
path('category/<str:cats>/', views.CategoryView, name='category'),
到
path('category/<int:cats>/', views.CategoryView, name='category'),
強制參數為 integer 類型。
當您進行過濾器查詢時
category_posts = Post.objects.filter(category=cats)
category 是外鍵,所以查詢將取 category 的主鍵並與輸入參數“cats”進行比較,它有 integer 值。
但是,對於 django 3.0.6 和 python 3.6.9,我遇到了與不需要強制參數的簡單 CBV(如 TemplateView 或 ListView)相同的問題。
下面的 url 有效。
path('blog/dummy', views.BlogView.as_view(), name='blog_list'),
而下面的不是,錯誤:字段“id”需要一個數字但得到“blog_list”被拋出。 其中blog_list是 url 的名稱...
path('blog', views.BlogView.as_view(), name='blog_list'),
在路徑后添加任何帶有斜杠 (/) 的東西?....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.