表单通过POST方式往数据库中写入数据

工程名称为demo7

一、直接POST提交:

models.py:

from django.db import models

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

views.py:

from django.shortcuts import render
from django.views.decorators import csrf
from django.http import HttpResponse
from . import models

# Create your views here.

def add_article(request):
    ctx ={}
    if request.POST:
        ctx['title'] = request.POST['title']
        ctx['content'] = request.POST['content']
        test1  = models.Article(title=ctx['title'], content=ctx['content'])
        test1.save()
        all = models.Article.objects.all()
    return render(request, 'post.html', {'all': all})

post.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form action="/blog/add/" method="POST">
        {% csrf_token %}
        <input type="text" name="title"/><br/>
        <textarea name="content"></textarea><br/>
        <button>添加</button>
    </form>

    {% for a in all %}
        <p>{{a.title}}</p>
    {% endfor %}
</body>
</html>

blog/urls.py:

from django.urls import path, include
from . import views

urlpatterns = [
   path('add/', views.add_article)
]

 demo7/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls'))
]

项目结构如下:

通过http://ip:port/blog/add/即可访问。

二、异步提交:

views.py:

from django.shortcuts import render
from django.views.decorators import csrf
from django.http import HttpResponse
from . import models
from django.views.decorators.csrf import csrf_exempt
import json

# Create your views here.

@csrf_exempt
def add_article(request):
    ctx ={}
    if request.POST:
        ctx['title'] = request.POST['title']
        ctx['content'] = request.POST['content']
        test1  = models.Article(title=ctx['title'], content=ctx['content'])
        test1.save()
        
        data = {'ret': True, 'msg': '数据提交成功!'}
        return HttpResponse(json.dumps(data), content_type="application/json")

@csrf_exempt
def add_page(request):
    return render(request, 'post.html')

post.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
    <form action="/blog/add/" method="POST">
        <input type="text" id="title"/><br />
        <textarea id="content"></textarea><br />
        <input id="submit-button" type="button" value="提交" />
    </form>

    <script>
        $("#submit-button").click(function () {
            $.ajax({
                cache: false,
                type: "POST",
                url: "/blog/add/",
                //traditional: true, //加上此项可以传数组
                dataType: 'json',
                data: { title: $("#title").val(), content: $("#content").val()},
                success: function (data) {
                    if(data.ret){
                        alert(data.msg)
                    }
                }
            });
        })
    </script>
</body>

</html>

blog/urls.py:

from django.urls import path, include
from . import views

urlpatterns = [
   path('add/', views.add_article),
   path('add_page/', views.add_page),
]

通过http://ip:port/blog/add_page/即可访问。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值