How do I write the problematic code to avoid getting the error?

时间:2019-04-17 02:41:51

标签: html django html5

I get the error after typing the code in the models.py field after determining the application name in urls.py

No problem before defining the application name.

Django==2.2

Python==3.x

Blog/urls.py

from django.contrib import admin
from django.urls import path, re_path, include
from Home.views import HomeView

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^$', HomeView),
    re_path(r'^Post/', include('Post.urls')),
]

Post/urls.py

from django.urls import path, re_path
from .views import *

AppName = 'Post'

urlpatterns = [
    re_path(r'^Index/$', PostIndex, name='Index'),
    re_path(r'^(?P<id>\d+)/$', PostDetail, name='Detail'),
    re_path(r'^Create/$', PostCreate, name='Create'),
    re_path(r'^Update/$', PostUpdate, name='Update'),
    re_path(r'^Delete/$', PostDelete, name='Delete'),
]

models.py

from django.db import models
from django.urls import reverse

# Create your models here.

    class Post(models.Model):
        Title = models.CharField(max_length=120)
        Content = models.TextField()
        PublishingDate = models.DateTimeField()

        def __str__(self):
            return self.Title

        def get_absolute_url(self):
            return reverse('Post:Detail', kwargs={'id':self.id})

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    {% for Post in Posts %}
        {{ Post.id }}<br>
        <a href="{{ Post.get_absolute_url }}">{{ Post.Title }}</a><br>
        {{ Post.Content }}<br>
        {{ Post.PublishingDate }}<br>
    {% endfor %}

</body>
</html>

I am not receiving an error without defining the application name in the models.py field. There is an error in code editing in the models.py field.

    def get_absolute_url(self):

seamless code => return reverse('Detail', kwargs={'id':self.id})
problematic code => return reverse('Post:Detail', kwargs={'id':self.id})

How do I write the problematic code to avoid getting the error?

1 个答案:

答案 0 :(得分:0)

您需要为您的帖子网址添加一个名称空间:

from django.contrib import admin
from django.urls import path, re_path, include
from Home.views import HomeView

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^$', HomeView),
    re_path(r'^Post/', include('Post.urls', namespace='Post')),
]