七、页面请求处理

1、后端处理请求的实现

一个提交数据的页面,会有get与post两种请求需要,这时候只需要写一个页面,在后端判断传过来的是get请求,还是post请求,就可以根据不同的请求得到不同的处理。

def add_article(request):
    # 一个页面对应两种请求
    # 如果是直接请求页面,就走get请求,如果是提交数据,就走post请求。
    if request.method == 'GET':
        return render(request,'add_article.html')
    if request.method == 'POST':
        title = request.POST.get('title') # 从页面中传过来的数据
        content = request.POST.get('content')
        nav_id = request.POST.get('nav_id')
        img = request.FILES.get('img') #如果是图片,要用FILES
        models.Article.objects.create(title=title,content=content,nav_id=nav_id,img=img)
        return HttpResponseRedirect('/index') # 跳转到页面

2、前端页面实现

前端通过form表单提交的方式实现,也可以写ajax请求实现

{#form表单上传文件或者图片,需要添加这个属性enctype="multipart/form-data"#}
<form action="/add/" method="post" enctype="multipart/form-data">
{% csrf_token %}
{#防止重复提交,前端会自动生成一段字符串给后端校验#}
    <p>title :<input name="title"></p>
    </p>content :<input name="content"></p>
    </p><select name="nav_id">  #需要在select标签里面写name
        {% for nav in daohang %} #这里的daohang是写在上下文管理器里面的变量
        <option  value="{{ nav.id }}">{{ nav.name }}</option>
        {% endfor %}
    </select></p>
    </p><input type="file" name="img"></p>
    </p><input type="submit" value="提交"></p>
</form>

猜你喜欢

转载自www.cnblogs.com/yanyan-/p/11743842.html
今日推荐