我正在制作一个简单的博客,我使用的项目名称为Blogger_Vip 和应用名称为Blog
我有以下代码:
在项目级别的模块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导入URL 从.views导入BlogListView,BlogDetailView
app_name = 'enc_vip_blog'
urlpatterns = [
url(r'^$', BlogListView.as_view() , name='list'),
url(r'^(?P<slug>\S+)$', BlogDetailView.as_view() , name='detail'),
]
最后列出所有我拥有的list.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%}
和card.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 /'%}无效?
有人可以帮忙吗? 帮助我解决名称空间问题和硬编码方面的问题?
答案 0 :(得分:0)
尝试url(r'^(?P<slug>[\w-]+)/$', views.BlogDetailView.as_view(), ...)
并确保在数据库中有子弹,只需在管理面板中检查