【问题标题】:Django Field 'id' expected a number but got '<string>'Django 字段 'id' 需要一个数字,但得到了 '<string>'
【发布时间】:2020-05-15 18:54:11
【问题描述】:

我正在尝试为我的 Django 项目创建一个类别页面。当我测试 url 时一切正常;但是当我尝试传入过滤帖子的类别对象时,我收到此错误:Field 'id' expected a number but got '&lt;string&gt;'

"category" 是我的 Post 模型中的外键,我知道它传递的默认值是 id。如何传递字符串本身而不是 id?

这是我的models.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 %} 

【问题讨论】:

    标签: python html django


    【解决方案1】:

    更改 urls.py,

        path('category/<str:cats>/', views.CategoryView, name='category'),
    

        path('category/<int:cats>/', views.CategoryView, name='category'),
    

    强制参数为整数类型。

    当你进行过滤查询时

    category_posts = Post.objects.filter(category=cats)
    

    category是外键,所以查询会取category的主键和输入参数“cats”比较,是整数值。

    【讨论】:

    • 并避免在模型Categoryname字段的参数中使用unique=True的重复类别
    【解决方案2】:

    但是,对于 django 3.0.6 和 python 3.6.9,我在使用不需要强制参数的简单 CBV(如 TemplateView 或 ListView)时遇到了同样的问题。

    下面的网址有效。

    path('blog/dummy', views.BlogView.as_view(), name='blog_list'),
    

    而下面的错误:Field 'id' expected a number but got 'blog_list' 被抛出。其中 blog_list 是 url 的名称...

    path('blog', views.BlogView.as_view(), name='blog_list'),
    

    在路径后添加任何带有斜杠(/)的东西?!...

    【讨论】:

      猜你喜欢
      • 2021-08-31
      • 1970-01-01
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 2021-06-03
      • 2021-01-22
      • 2021-07-30
      相关资源
      最近更新 更多