猿问

字段“id”需要一个数字,但得到“create”

我一直在尝试创建此模型对象,但不断收到此错误:字段“id”需要一个数字,但得到“创建”。错误图片分享如下。我正在使用 djangi 3.0.3 view.py 文件:-


from django.shortcuts import render

from . import models

from django.views.generic import (View,TemplateView,ListView,DetailView,

                                    CreateView,UpdateView,DetailView)


# Create your views here.

class IndexView(TemplateView):

    template_name = 'index.html'


class SchoolListView(ListView):

    context_object_name = 'schools'

    model = models.School



class SchoolDetailView(DetailView):

    context_object_name = 'school_detail'

    model = models.School

    template_name = 'basic_app/school_detail.html'


class SchoolCreateView(CreateView):

    fields = ('name','principal','location')

    model = models.School


model.py


from django.db import models

from django.urls import reverse

# Create your models here.


class School(models.Model):

    name = models.CharField(max_length=265)

    principal = models.CharField(max_length=256)

    location = models.CharField(max_length=256)


    def __str__(self):

        return self.name


    def get_absolute_url(self):

        return reverse("basic_app:detail", kwargs={'pk':self.pk})


class Student(models.Model):

    name = models.CharField(max_length=256)

    age = models.PositiveIntegerField()

    school = models.ForeignKey(School, related_name='student', on_delete=models.CASCADE)


    def __str__(self):

        return self.name


子衿沉夜
浏览 67回答 1
1回答

慕尼黑5688855

这看起来像是您的 urls.py 的错误。只要确保当您在 urls.py 中提到 URL 路径时,明确的路径在前,变量路径在后。例如,这段代码会给你一个错误:path('<int:id>/'&nbsp;,&nbsp;view.DetailView.as_view(),&nbsp;name="detail") path('create/'&nbsp;,&nbsp;view.CreateView.as_view(),&nbsp;name="create")为了避免错误,只需更改顺序,如下所示:path('create/'&nbsp;,&nbsp;view.CreateView.as_view(),&nbsp;name="create") path('<int:id>/'&nbsp;,&nbsp;view.DetailView.as_view(),&nbsp;name="detail")发生这种情况是因为在后面的代码中,django 将查找路径 /create,如果无法匹配,它将查找路径 int:id/。现在,由于 int:id/ 是一个变量,如果 django 首先查找它,它将尝试将“create”分配给 id 变量,这将产生验证问题。
随时随地看视频慕课网APP

相关分类

Python
我要回答