You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django博客作者自动归属与内容排版问题求助

Django博客问题解决方案

问题1:用户权限与作者自动赋值

问题分析

  • 发布文章时未关联当前登录用户,导致所有文章作者显示一致
  • 删除按钮未做权限校验,任意登录用户可删除所有文章
  • 表单若显示作者字段会允许选择其他用户,不符合需求

解决方案

1. 自动设置文章作者为当前登录用户

在处理文章创建的视图函数中,提交表单后手动将author字段赋值为当前登录用户:

# views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from .models import post
from .forms import postform

@login_required
def create_post(request):
    if request.method == 'POST':
        form = postform(request.POST)
        if form.is_valid():
            # 先暂存表单数据,不立即保存到数据库
            new_post = form.save(commit=False)
            # 绑定当前登录用户为作者
            new_post.author = request.user
            new_post.save()
            return redirect('post_list')  # 替换为你的文章列表路由名
    else:
        form = postform()
    return render(request, 'new.html', {'form': form})

2. 限制删除权限,仅作者可删除

  • 模板层:修改post.html中的删除按钮显示逻辑,仅当当前用户是文章作者时才显示:
<!-- post.html 中删除按钮部分 -->
{% if user.is_authenticated and user == post.author %}
<a href="#myModal" class="btn btn-danger btn-small" id="deleteButton" data-toggle="modal" data-target="#myModal">Delete <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 16">
    <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5Zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5Zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6Z"/>
    <path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1ZM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118ZM2.5 3h11V2h-11v1Z"/>
  </svg></a>
{% endif %}
  • 视图层:删除视图中添加权限校验,防止直接通过URL删除他人文章:
# views.py
from django.http import HttpResponseForbidden

@login_required
def delete_post(request, post_id):
    post_obj = post.objects.get(id=post_id)
    # 校验当前用户是否为文章作者
    if request.user != post_obj.author:
        return HttpResponseForbidden("你无权删除这篇文章")
    post_obj.delete()
    return redirect('post_list')

3. 保持表单隐藏作者字段

当前forms.py已排除author字段,无需修改:

# forms.py
class postform(ModelForm):
    class Meta:
        model = post
        exclude = ('author',)
        widgets = {
            'body': Textarea()
        }

问题2:文章内容发布后无行间距

问题分析

编辑时文本框的纯文本换行,在HTML中不会被识别为段落或换行,导致内容堆叠。

解决方案

使用Django的linebreaks过滤器,将纯文本换行转换为HTML段落标签,自动生成行间距:

修改detail.html的内容渲染:

<!-- detail.html -->
<p style="margin-top: 15px;">{{ post.body|linebreaks }}</p>

修改post.html的摘要渲染:

<!-- post.html -->
{{ post.body|truncatewords_html:30|linebreaks }}

如果仅需要换行而非段落,可替换为linebreaksbr过滤器,将换行转换为<br>标签。


内容的提问来源于stack exchange,提问作者Rin Hyakuya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:07:22