django在网址中使用Pk字段 [英] django use Pk field in a url

查看:273
本文介绍了django在网址中使用Pk字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个pk字段(不是由模型自动创建的)。
当我想使用此pk名称(在我的情况下为school_id)时出现此错误:

I have created a pk field(not automatically created by the model). when I want to use this pk name(in my case school_id) I got this error:

Generic detail view SchoolDetailView must be called with either an object pk or a slug.

尽管我使用的是我在网址中的模型中使用的正确的pk名称(school_pk)。
我的代码如下:
models.py:

although I am using the correct pk name(school_pk) I have used in my model in the url. my code is as follows: models.py:

from django.db import models
from django.urls import reverse
class School(models.Model):
    school_pk = models.AutoField(primary_key=True)
    name = models.CharField(max_length=256)
    principal = models.CharField(max_length=256)
    location = models.CharField(max_length=256)
    def __str__(self):
        return str(self.name)
    def get_absolute_url(self):
        return reverse("basic_app:school_detail",kwargs={'school_pk':self.school_pk})

views.py:

class SchoolListView(ListView):

    model = models.School
    template_name = 'basic_app/school_list.html'


class SchoolDetailView(DetailView):
    context_object_name = 'school'
    model = models.School
    template_name = 'basic_app/school_detail.html'

urls .py:

urlpatterns = [
path('',views.SchoolListView.as_view(),name='school_list'),
path('<int:school_pk>/',views.SchoolDetailView.as_view(),name='school_detail'),]

当我尝试通过转到 http://127.0.0.1转到school_detail页面时: 8000 / basic_app / 1 / 例如
我有此错误:

when I try to go to school_detail page by going to http://127.0.0.1:8000/basic_app/1/ for example I have this error:

Request Method: GET
Request URL:    http://127.0.0.1:8000/basic_app/1/
Django Version: 2.0
Exception Type: AttributeError
Exception Value:    
Generic detail view SchoolDetailView must be called with either an object pk or a slug.

我尝试使用get_object和/或get_queryset,但是我认为我做错了方法。如果有人可以帮助您,那将是很棒的,并受到高度赞赏。谢谢。
注意:我不想从模型中省略school_pk字段,而是使用自动生成的PK)。

I have tried to use get_object and/or get_queryset but I believe I am doing it the wrong way. if any one can help that will be great and highly appreciated. Thanks. note:I dont want to omit school_pk field from my model and use PK that is automatically genertaed).

推荐答案

添加 pk_url_kwarg ='school_pk'来查看 SchoolDetailView 。默认情况下,它设置为 pk

Add pk_url_kwarg = 'school_pk' to view SchoolDetailView. By default it is set to pk.

class SchoolDetailView(DetailView):
    context_object_name = 'school'
    model = models.School
    template_name = 'basic_app/school_detail.html'
    pk_url_kwarg = 'school_pk'

这篇关于django在网址中使用Pk字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆