表單通過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/即可訪問。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章