Django : django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found. 'detail'不是有效的视图函



我正在做一个简单的博客,我用项目名称作为Blogger_Vip 和应用名称作为博客

我有以下代码:

在项目级别模块 Blogger_Vip 中:

urls.py 包含:

from django.contrib import admin
from django.urls import path
from django.conf.urls import url , include
from django.conf import settings
from django.conf.urls.static import static
from .views import home_page , contact_page , about_page , register_page , 
login_page
urlpatterns = [
path('admin/', admin.site.urls),
url('^blog/', include('enc_vip_blog.urls',namespace='enc_vip_blog')),
url(r'^$',home_page,name='home'),
url(r'^login/$',login_page,name='login'),
url(r'^register/$',register_page,name='register'),
url(r'^about/$',about_page,name='about'),
url(r'^contact/$',contact_page,name='contact'),
]

views.py 包含:

from django.shortcuts import render , redirect
from django.http import HttpResponse
from .forms import ContactForm,LoginForm,RegisterForm
from django.contrib.auth import authenticate,login
from django.contrib.auth import get_user_model


def home_page(r):
context = {
'title':'Hello World!',
'content':'Welcome to the Home Page!'
}
if r.user.is_authenticated:
context['premium_content']='Yeahhhh!'
return render(r,'home_page.html',context)
def about_page(r):
context = {
'title': 'ABOUT PAGE',
'content': 'Welcome to the About Page!'
}
return render(r,'about_page.html',context)
def contact_page(r):
contact_form = ContactForm(r.POST or None)
context = {
'title': 'CONTACT PAGE',
'content': 'Welcome to the Contact Page!',
'form':contact_form,
'brand':'new brand',
}
if contact_form.is_valid():
print(contact_form.cleaned_data)
return render(r,'contacts/view.html',context)
User = get_user_model()
#This captures the default fields of User Model
def register_page(r):
register_form = RegisterForm(r.POST or None)
context = {
'register_form':register_form
}
if register_form.is_valid():
username = register_form.cleaned_data.get('username')
email = register_form.cleaned_data.get('email')
password = register_form.cleaned_data.get('password')
new_user = User.objects.create_user(username,email,password)
print(new_user)
# print(password)
return render(r,'auth/register.html',context)

def login_page(r):
login_form = LoginForm(r.POST or None)
context = {
'login_form':login_form
}
print('User Logged in :')
print(r.user.is_authenticated)
if login_form.is_valid():
print(login_form.cleaned_data)
username = login_form.cleaned_data.get('username')
password = login_form.cleaned_data.get('password')
user = authenticate(r,username=username,password=password)
print("User Logged in:")
print(r.user.is_authenticated)
print(user)
if user is not None:
print(r.user.is_authenticated)
login(r,user)
# login_form['login_form']=login_form
return redirect('/')
else:
print('Error')

return render(r,'auth/login.html',context)

forms.py 包含:

from django import forms
from django.core.validators import ValidationError
from django.contrib.auth import get_user_model


User = get_user_model()
class ContactForm(forms.Form):
fullname = forms.CharField(max_length=100,widget=forms.TextInput(
attrs={'class':'form- 
control','placeholder':'Your name here',
'id':'fullname'}
),help_text="Max 100 
characters")
email = forms.EmailField(widget=forms.TextInput(
attrs={'class':'form- 
control','placeholder':'Your email here',
'id':'email'}
))
content = forms.CharField(max_length=300,widget=forms.Textarea(attrs= 
{'class':'form-control',
'placeholder':'Leave 
your message here',
'id':'content'}),
help_text='300 characters max')

def clean_email(self):
email = self.cleaned_data.get('email')
if not 'gmail.com' in email:
raise forms.ValidationError("Email must be Gmail id!")
return email

class RegisterForm(forms.Form):
username = forms.CharField()
email = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(label="Confirm 
Password",widget=forms.PasswordInput)
#Unique username constraint setup
def clean_username(self):
username = self.cleaned_data.get('username')
#Queryset to get all logged in or registered user objects from User 
model
user_queries = User.objects.filter(username=username)#Got all usernames 
that are already registered
#Checking if current username matches any other username from the 
results
if user_queries.exists():
raise forms.ValidationError('Username Exists!')
return username
# Unique email id constraint setup
def clean_email(self):
email = self.cleaned_data.get('email')
email_queries = User.objects.filter(email=email)
if email_queries.exists():
raise forms.ValidationError('This Email Id is taken!')
return email

#Password confirmation during registration
def clean(self):
data = self.cleaned_data
password = self.cleaned_data.get('password')
confirmation_password = self.cleaned_data.get('confirm_password')
if password!=confirmation_password:
raise forms.ValidationError("Passwords must match!")
return data


class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)

现在我有一个名为enc_vip_blog的应用程序: 这包含以下内容: 从 Django 导入模型.db 从 django.urls 反向导入

# Create your models here.
class EntryManager(models.Manager):
def published(self):
return self.get_queryset().filter(publish = True)

class Tag(models.Model):
slug = models.SlugField(max_length=200 , unique=True)

def __str__(self):
return self.slug

class Entry(models.Model):
title = models.CharField(max_length=100)
body = models.TextField(max_length=1000)
short_body = models.CharField(max_length=200,default='Click link to know 
more')
slug = models.SlugField(max_length=100 , unique=True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='blog/',null=True,blank=True)
tags = models.ManyToManyField(Tag)
objects = EntryManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('enc_vip_blog:detail',kwargs={'slug':self.slug})
#To make admin representations look better override class Meta
class Meta:
verbose_name = 'Blog Entry'
verbose_name_plural = 'Blog Entries'
#Set ordering to reverse chronological order
ordering = ['-created']

urls.py 包含: 从 django.conf.urls 导入网址 从 .views 导入博客列表视图,博客详细信息视图

app_name = 'enc_vip_blog'
urlpatterns = [
url(r'^$', BlogListView.as_view() , name='list'),
url(r'^(?P<slug>S+)$', BlogDetailView.as_view() , name='detail'),
]

最后列出我列出的所有内容.html:

{%extends 'base/base.html'%}
{%load static%}
{%block content%}
<ul>{%for object in object_list%}
{%include 'blog/card.html' with instance=object%}
{%endfor%}
</ul>
{%endblock%}

和卡.html:

<div class="card-body">
<h5 class="card-title"> <a href="{{ instance.get_absolute_url }}">{{ 
instance.title }}</a></h5>
{%if instance.image%}
<a href="{{ instance.get_absolute_url }}" >
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<img class="card-img-top" src="{{ instance.image.url }}" style="width: 
100%;" alt="{{ instance.title }}">
</div>
<div class="col-md-4"></div>
</div>
</a>
{%endif%}
<p class="card-text">{{ instance.short_body }}</p>
<p class="Meta">{{ instance.created }}</p>
<p class="Meta">tagged under {{ instance.tags.all|join:', ' }}</p>
<a href="{{ instance.get_absolute_url }}" class="btn btn- 
primary">View</a>
</div>
</div>

我希望当用户登录时,他/她将被重定向到主页,并且主页必须包含一个链接,上面写着"访问博客" 在那里我使用了 {%url 'enc_vip_blog:list'%}

我收到以下错误:

django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found. 
'detail' is not a valid view function or pattern name.

我试图找出这个细节的链接...... 此外,如果我不使用命名空间的东西,博客运行良好 但仍然在主页上,甚至将 url 部分硬编码为 href 作为 {%url 'blog/'%} 不起作用?

有人可以帮忙吗? 帮助我解决命名空间的问题以及硬编码之类的东西?

尝试url(r'^(?P<slug>[w-]+)/$', views.BlogDetailView.as_view(), ...)并确保数据库中有 slug,只需在管理面板中检查即可

相关内容

  • 没有找到相关文章

最新更新