采用POST请求输入url:127.0.0.1:3000/add2/(在这里我修改了端口号为3000
标签:
客户端与处事器之间最常用的两种请求方法: 1. GET请求一般是用来向处事器索取数据,但不会向处事器提交数据,,不会对处事器的状态进行变动。 2.POST请求一般是用来向处事器提交数据,会对处事器的状态进行变动。 限制请求装饰器: Django内置的视图装饰器可以给视图供给一下限制,好比正视图只能通过GET的method访谒等。常用的内置视图装饰器: 1. django.http.decorators.http.require_http_methods: 这个装饰器需要通报一个允许访谒的要领的列表。 (1)好比,如果客户端发送的是GET请求,就返回给用户一个添加文章的界面;如果发送的是POST请求,就将提交的数据进行生存到数据库中。views.py文件中示例代码如下: from django.views.decorators.http import require_http_methods from django.http import HttpResponse from django.shortcuts import render from .models import Article @require_http_methods(['GET', 'POST']) def index2(request): <!--首先判断客户端发送的是哪种请求GET OR POST--> <!--注意这里必然要是“==” 只有“==”才会返回True or False--> if request.method == 'GET': return render(request,'static/add.html') else: title = request.POST.get('title') content = request.POST.get('content') price = request.POST.get('price') Article.objects.create(title=title, content=content, price=price) articles = Article.objects.all() return render(request, 'static/index.html', context={'articles': articles} (2)index.html示例代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table> <thead> <tr style="width: 20px">标题</tr> <tr style="width: 20px">内容</tr> <tr style="width: 20px">价格</tr> <tr style="width: 20px">创建时间</tr> </thead> <tbody> {% for article in articles %} <tr> <td><a href="#">{{ article.title }}</a></td> <td><a href=http://www.mamicode.com/"">{{ article.content }}</a></td> <td><a href=http://www.mamicode.com/"">{{ article.price }}</a></td> <td>{{ article.create_time }}</td> </tr> {% endfor %} </tbody> </table> </body> </html> (3)urls.py文件中示例代码如下: from django.urls import path from article import views urlpatterns = [ path('', views.index, name='index'), path('add/', views.add, name='add'), path('add2/', views.index2, name='add2'), ] 在Postman软件中,给与POST请求输入url:127.0.0.1:3000/add2/(在这里我改削了端标语为3000,默认情况为8000),并且在URL下面的Body中传入需要的参数值title,content,price.返回这样的功效:102.限制请求的method装饰器:require_http_methods,require_GET,require_POST,require_safe
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30249.html