簡體   English   中英

為什么我在 Django 4.0.6 中練習來自 github 的初學者項目時出現 NoReverseMatch 錯誤?

[英]why i am getting NoReverseMatch error while i am practicing beginner projects from github in Django 4.0.6?

將主鍵添加到 urls.py 文件中的 URL 鏈接后,出現 NoReverseMatch 錯誤。 請解決它。 我是編程初學者,所以我找不到這個問題的解決方案。 感謝您的時間和精力。 我從 Github 得到了這個練習。 代碼寫在下面。

設置.py

from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR=os.path.join(BASE_DIR,"templates")

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-6mtsgnhk=-=5ka0-e4619v0_uq)s+t=dtybe8^ojwmg1gwoj**'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'g7app',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'g7.urls'

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [TEMPLATES_DIR,],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
    },
]

WSGI_APPLICATION = 'g7.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': BASE_DIR / 'db.sqlite3',
}
}


urls.py

from django.contrib import admin
from django.urls import path
from g7app.views import CreatePost,View1,View2,EditPost,DeleteView,CreatePost

urlpatterns = [
path('admin/', admin.site.urls),
path("",View1.as_view(),name="home"),
path("post/<int:pk>/",View2.as_view(),name="post_detail"),
path("post/<int:pk>/post_edit/",EditPost.as_view(),name="post_edit"),
path("post/<int:pk>/post_delete/",DeleteView.as_view(),name="post_delete"),
path("post/new/",CreatePost.as_view(),name="post_new"),

]


admin.py

from django.contrib import admin
from .models import Student
# Register your models here.
admin.site.register(Student)


models.py


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


# Create your models here.
class Student(models.Model):
name=models.CharField(max_length=100)
description=models.CharField(max_length=100)

def __str__(self):
    return self.name

def get_absolute_url(self):
    return reverse("post_detail", args=[self.pk])


views.py


from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView  # new
from django.urls import reverse_lazy  # new
from .models import Student

# Create your views here.
    class View1(ListView):
    context_object_name="con1"
    template_name="home.html"
    model=Student

class View2(DetailView):
    context_object_name="con2"
    template_name="post_detail.html"
    model=Student

class CreatePost(CreateView):
    fields=["name","description"]
    template_name="create_post.html"
    model=Student

class EditPost(UpdateView):
    fields=["description"]
    template_name="edit_post.html"
    model=Student

class DeleteView(DeleteView):
    template_name="delete_post.html"
    model=Student
    success_url=reverse_lazy("home")


base.html


<!DOCTYPE HTML>
<HTML>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <h1>Blog Application</h1>

    {% block c1 %}
        <h2><a href="{% url 'post_new' %}">+Create_Post</a></h2>
    {% endblock c1 %}
  </body>
</html>


home.html

<!DOCTYPE HTML>

{% extends "base.html" %}

{% block c1 %}

  {% for Student in con1 %}

    <h2><a href="{% url 'post_detail' Student.pk %}">{{Student.name}}</a></h2>
    <h4>{{Student.description}}</h4>


  {% endfor %}
{% endblock c1 %}


post_detail.html

{% extends "base.html" %}

{% block c1 %}
    <div>

      <h2>{{con2.name}}</h2>
      <h4>{{con2.description}}</h4>
    </div>

  <p><a href="{% url 'post_edit' Student.pk %}">Edit post</a></p>
  <p><a href="{% url 'post_delete' Student.pk %}">Delete post</a></p>

{% endblock c1 %}


create_post.html

<!DOCTYPE HTML>
<HTML>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {% extends "base.html" %}
    {% block c1 %}

    <form method="post">
      {csrf_token}
      {{form.as_p}}
      <input type="submit" value="save">
    </form>
{% endblock c1 %}

</body>
</html>


edit_post.html

{% extends "base.html" %}

{% block c1 %}

<div>

<h3>edit information</h3>
<form method="post">
  {csrf_token}
  {{form.as_p}}

  <input type="submit" value="save">

</form>
</div>
{% endblock c1 %}



delete_post.html

{% extends "base.html" %}

{% block c1 %}
<div>


    <h3>delet post</h3>
    <form method="post">
      {csrf_token}
      {{form.as_p}}

      <input type="submit" value="save">

   </form>
</div>
{% endblock c1 %}

編輯你的 urls.py 文件:

from django.contrib import admin
from django.urls import path
from g7app.views import CreatePost,View1,View2,EditPost,DeleteView,CreatePost

app_name = 'my_app' #add this line

urlpatterns = [
path('admin/', admin.site.urls),
path("",View1.as_view(),name="home"),
path("post/<int:pk>/",View2.as_view(),name="post_detail"),
path("post/<int:pk>/post_edit/",EditPost.as_view(),name="post_edit"),
path("post/<int:pk>/post_delete/",DeleteView.as_view(),name="post_delete"),
path("post/new/",CreatePost.as_view(),name="post_new"),

]

編輯您的 base.html 文件:

<!DOCTYPE HTML>
<HTML>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <h1>Blog Application</h1>

    {% block c1 %}
        <!-- here I added app_name to url -->
        <h2><a href="{% url 'my_app:post_new' %}">+Create_Post</a></h2>
    {% endblock c1 %}
  </body>
</html>

編輯你的家。html

<!DOCTYPE HTML>

{% extends "base.html" %}

{% block c1 %}

  {% for Student in con1 %}
    <!-- here I added app_name to url -->
    <h2><a href="{% url 'my_app:post_detail' Student.pk %}">{{Student.name}}</a></h2>
    <h4>{{Student.description}}</h4>


  {% endfor %}
{% endblock c1 %}

編輯您的 post_detail.html

{% extends "base.html" %}

{% block c1 %}
    <div>

      <h2>{{con2.name}}</h2>
      <h4>{{con2.description}}</h4>
    </div>
  <!-- here I added app_name to urls -->
  <p><a href="{% url 'my_app:post_edit' Student.pk %}">Edit post</a></p>
  <p><a href="{% url 'my_app:post_delete' Student.pk %}">Delete post</a></p>

{% endblock c1 %}

希望它應該工作:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM