Django博客新增分类不更新、点击提示页面不存在问题求助
问题1:新增分类后分类下拉列表不更新
你的AddCategoryView没有配置添加成功后的跳转地址,Django通用创建视图默认会尝试跳转至新增对象的详情地址,但你的Category模型没有定义get_absolute_url方法,所以添加完分类后要么报错,要么停留在原页面,导航栏的分类菜单还是加载的旧数据。
解决方法:
在AddCategoryView类里添加成功跳转配置,添加完分类直接跳转到首页,自动加载最新分类列表:
class AddCategoryView(CreateView): model = Category template_name = 'add_category.html' fields = '__all__' # 新增下面这行,跳转至首页 success_url = reverse_lazy('home') # 剩下的原有代码不变 def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(AddCategoryView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context
另外你add_category.html里的form标签没有闭合,补上避免出现提交异常:
<div class="form-group"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-secondary">Add Category</button> </form> <!-- 补上这行闭合标签 --> </div>
问题2:点击分类链接提示页面不存在
你categories.html的判断逻辑是如果当前分类下没有文章,就直接显示「Sorry this page does not exist...」,刚新增的分类还没有发布对应分类的文章,就会触发这个提示,和路由本身没有关系。
如果你想要分类页面即使没有文章也不提示页面不存在,只需要修改categories.html的判断逻辑即可:
{% extends 'base.html' %} {% block content %} <h1>{{ cats }}</h1> {% if category_posts %} <ul> {% for post in category_posts %} <li><a href="{% url 'article-detail' post.pk %}">{{post.title}}</a> - {{post.author.first_name}} {{post.author.last_name}} - {{ post.post_date }} <small> {% if user.is_authenticated %} - <a href="{% url 'update_post' post.pk %}">(Edit)</a> <a href="{% url 'delete_post' post.pk %}">(Delete)</a> {% endif %} </small><br/> {{post.body|slice:":200"| safe }}</li> {% endfor %} </ul> {% else %} <p>该分类下暂无文章</p> <!-- 替换掉原来的页面不存在提示 --> {% endif %} {% endblock %}
如果你的Post模型的category字段是外键关联到Category模型,还需要修改CategoryView的过滤逻辑,避免查询报错:
def CategoryView(request, cats): # 先查找到对应的分类对象,再过滤该分类下的文章 category_obj = Category.objects.get(name=cats.replace('-', ' ')) category_posts = Post.objects.filter(category=category_obj) return render(request, 'categories.html',{'cats':cats.title().replace('-', ' '), 'category_posts':category_posts})
内容的提问来源于stack exchange,提问作者Kaushik Jayendirakumar
相关产品推荐
相关产品推荐

