表单通过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:




    
    
    
    Document


    
{% csrf_token %}

{% for a in all %}

{{a.title}}

{% endfor %}

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'))
]

项目结构如下:

表单通过POST方式往数据库中写入数据_第1张图片

通过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:





    
    
    
    Document
    



    


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/即可访问。

你可能感兴趣的:(Django)