Python django简单的评论区

该博客主要围绕Python开发展开,介绍了创建数据表、编写视图、增加url和编写模板的操作。具体涉及到models.py、views.py、urls.py和page.html等文件的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建数据表

models.py

class Article(models.Model):
    title = models.CharField(max_length=32, default='title')
    content = models.TextField(null=True)

执行

python manage.py makemigrations
python manage.py migrate

编写视图

views.py

def page(request):
    if request.method == 'POST':
        article = models.Article.objects.all()
        title = request.POST.get('title')
        content = request.POST.get('content')
        if title == '' or content == '':
            pass
        else:
            models.Article.objects.create(title=title, content=content)
    if request.method == 'GET':
        article = models.Article.objects.all()

    return render(request, 'login/page.html', locals())

增加url

urls.py

urlpatterns = [    
	...
	url(r'^page/', views.page),
]

编写模板

page.html


{% extends 'login/base.html' %}
{% load staticfiles %}
{% block title %}讨论{% endblock %}
{% block css %}
    <link href="{% static 'css/login.css' %}" rel="stylesheet"/>
    <link href="{% static 'css/page.css' %}" rel="stylesheet"/>
{% endblock %}


{% block content %}
    <div class="a" style=" overflow-y:auto;overflow-x:auto; height:390px; width:40%;">
    <div style="position: absolute;left: 6%">
    <h2 style="color: red">欢迎讨论</h2>
{% for t in article %}
    <h3><a href=""></a>{{ t.title }}:</h3><h4>{{ t.content }}</h4>
{#    {% if request.session.is_login %}#}
{#       {{ request.session.user_name }}#}
{#    {% endif %}#}
    <hr width="650px">
{% endfor %}
    </div>
    </div>
    <div class="c">
<form action="/page/" method="post">
    {% csrf_token %}
    <div style="position:relative;left: 6%;top:40px">
    <label>标题
        <input type="text" name="title" />
    </label>
    <p></p>
    <label>内容
        <input type="text" name="content" style="width: 600px"/>
    </label>
    <p></p>
    <input type="submit" value="提交" class="btn btn-primary pull-right" style="position: relative;left:-93%;">
    </div>
</form>
    </div>
{% endblock %}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值