这是问题所在:我正试图“刷新”我的Django网络博客,因此,我不想拥有/post/2/
的那条链接就像我的标题一样(像这样:{{1} }
这里有一些代码,我已经尝试了几件事,但是没有任何效果:
models.py
/post/today-is-friday
urls.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.template.defaultfilters import slugify
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User,on_delete=models.CASCADE)
categories = models.ManyToManyField('Category',related_name='posts')
image = models.ImageField(upload_to='images/',default="images/None/no-img.jpg")
slug= models.SlugField(max_length=500,unique=True,null=True,blank=True)
def save(self,*args,**kwargs):
self.url= slugify(self.title)
super(Post,self).save(*args,**kwargs)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail',kwargs={'pk': self.pk})
class Category(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
user_posts.html (用于访问博客本身)
from django.urls import path
from django.conf.urls import include,url
from . import views
from .views import PostListView,PostDetailView,PostCreateView,PostUpdateView,PostDeleteView,UserPostListView
urlpatterns = [
#Blog section
path("",PostListView.as_view(),name='blog-home'),path("user/<str:username>",UserPostListView.as_view(),name='user-posts'),path("<slug:slug>/",PostDetailView.as_view(),name='post-detail'),path("post/new/",PostCreateView.as_view(),name='post-create'),path("<slug:slug>/update/",PostUpdateView.as_view(),name='post-update'),path("<slug:slug>/delete/",PostDeleteView.as_view(),name='post-delete'),path("about/",views.about,name="blog-about"),path("<category>/",views.blog_category,name="blog_category"),]
post_form.html (用于创建新帖子,创建帖子后无法重定向)
{% extends 'blog/base.html' %}
{% block content %}
<h1 class='mb-3'>Post by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1>
{% for post in posts %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}" alt="">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2 author_title" href="{% url 'user-posts' post.author.username %}">@{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"N d,Y" }}</small>
<div>
<!-- category section -->
<small class="text-muted">
Categories:
{% for category in post.categories.all %}
<a href="{% url 'blog_category' category.name %}">
{{ category.name }}
</a>
{% endfor %}
</small>
</div>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content|slice:200 }}</p>
</div>
</article>
{% endfor %}
{% endblock content %}