【问题标题】:Why When i try to open a link using object id then it's not working in django 3.2?为什么当我尝试使用对象 ID 打开链接时,它在 django 3.2 中不起作用?
【发布时间】:2021-09-01 16:15:55
【问题描述】:

我正在使用 django 3.2,我正在尝试学习如何在我的 html 页面上打印 models.py 数据。在此期间,我想在主页上添加一个 href 标记,该标记将重定向到带有对象 ID 的关于页面并显示其他详细信息。但它不起作用。

应用名称是 greeting_app

greeting_app/urls.py

from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('/about/<int:pk>/', views.about, name="about"),
]

greeting_app/models.py

from django.db import models
from django.db.models.enums import Choices

# Create your models here.
gender_choice = (
    ("0", "Nothing"),
    ("1", "Male"),
    ("2", "Female"),
)

class basicinformation(models.Model):
    name = models.CharField(max_length=50)
    age = models.IntegerField()
    gender = models.CharField(choices=gender_choice, max_length=10)
    description = models.TextField()

    def __str__(self):
        return self.name

greeting_app/views.py

from django.shortcuts import render, HttpResponse
from .models import basicinformation

# Create your views here.
def home(request):
    information = basicinformation.objects.all()
    return render(request, 'index.html', {"info":information})

def about(request, id):
    data = basicinformation.objects.get(id=id)
    return render(request, 'about.html', {"data":data})

【问题讨论】:

  • 您在哪里呈现该链接?能否提供insex.html模板的相关部分?
  • 我还没有在 index.html 中使用它,我只是想通过在 url 中直接输入 /about/object.id 来确保它正常工作。例如:127.0.0.1:8000/about/1
  • 如果你使用127.0.0.1:8000/about/1/,那么尾随斜杠呢?
  • @WillemVanOnsem 我仍然使用尾部斜杠得到相同的错误。这是我得到的错误的屏幕截图。请看ibb.co/86d2w3r
  • @BhaweshChaudhary 您没有在屏幕截图上附加斜杠。

标签: python django


【解决方案1】:

试试这个:

path('about/int:id/', views.about, name="about"),

【讨论】:

  • 好的,谢谢!几分钟前我做了同样的事情,它奏效了,我也提交了答案。 :)
  • 是的,我们的大部分错误都来自我们不太期望的地方。祝你的项目好运。
【解决方案2】:

在 greeting_app/urls.py 中

我只是在 about 之前删除了 / 并将 pk 更改为 id 并且它起作用了。
从此

from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('/about/<int:pk>/', views.about, name="about"),
] 

到这里:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('about/<int:id>/', views.about, name="about"),
]

【讨论】:

    【解决方案3】:

    改变

    path('/about/<int:pk>/', views.about, name="about"),
    

    path('/about/<int:id>/', views.about, name="about"),
    

    views.about 中,您试图获取id 作为参数,但在urls.py 中,主键作为pk (&lt;int:pk&gt;) 而不是id 传递。

    【讨论】:

    • 您好!我完全按照你说的做了,但我仍然收到错误消息。这是错误页面的链接。 ibb.co/KWtKRTD
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 2018-06-29
    • 2018-09-08
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多