如何使用Django中的视图处理与特定URL无关的表单?

时间:2017-10-23 17:46:48

标签: django django-forms django-templates django-views

我正在创建一个工作板网站,我有以下urls.py(不是那么重要,只是包含它们以使问题更清晰):

urlpatterns = [
    url(r'^admin/', admin.site.urls),

    url(r'^$', views.index, name = "index"),

    url(r'^job_info/(?P<job_id>[0-9]+)/$', views.job_info , name = "job_info"),

    url(r'^employer_signup', views.employer_signup, name="employer_signup"),

    url(r'^employer_home', views.employer_home, name = "employer_home"),

    url(r'^login/$', login, {'template_name':'core/employer_login.html'}, name = 'employer_login'),
]

我有一个包含在所有HTML文件中的base.html。这包括带有内嵌搜索栏的Navbar:

<form class="form-inline my-2 my-lg-0 navbar-toggler-right" method = "post" >
        {% csrf_token %}
        <input class="form-control mr-sm-2" type="text" placeholder="Search">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>

有没有办法用View处理这个表单?因为它没有直接绑定到任何特定的URL?

1 个答案:

答案 0 :(得分:0)

是的,每个问题都有办法。

听说过AJAX吗?

您可以在AJAX通话中通过POST请求提交表单。这是如何

<强> views.py

我写了一个简单的视图,从ajax请求获取值并打印它,您可以根据需要进行修改。

from django.shortcuts import render
from django.http import HttpResponse
import json

def NavbarForm(request):
    if request.method == "POST" and request.is_ajax():
        json_dict = json.loads( request.body.decode('utf-8'))
        input_value = json_dict['input_value']

        print(input_value)

        return HttpResponse(json.dumps({"status": 1}), content_type='application/json')

    return HttpResponse(json.dumps({"status": 0}), content_type='application/json')

def Index(request):
    return render(request, "index.html", {})

<强> urls.py

from .views import NavbarForm, Index

urlpatterns += [
    url(r'^$', Index, name = "index"),
    url(r'^ajax/navbar_form/submit$', NavbarForm)
]

<强>模板/ base.html文件

以下是您使用某些修改所做的相同HTML部分,例如添加&#34; id&#34;形成和输入(相应地改变)

<form class="form-inline my-2 my-lg-0 navbar-toggler-right" method = "post" id = "navbar_form">
        {% csrf_token %}
        <input class="form-control mr-sm-2" type="text" placeholder="Search" id = "input_value">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>

<强>模板/ base.html文件

以下是答案的主要CRUX,Jquery中的AJAX代码,有关更多信息,请阅读官方文档https://docs.djangoproject.com/en/1.11/ref/csrf/#ajax

<script type="text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
//GENERATE CSRF TOKEN
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});


$(document).ready(function(){
    $("#navbar_form").submit(function(e){
        e.preventDefault();
        var input_value = $("#input_value").val();
        var data = {"csrftoken": csrftoken, "input_value": input_value};
        data = JSON.stringify(data)
        $.ajax({
            type : 'POST',
            contentType: "application/json; charset=utf-8",
            url :  "/ajax/navbar_form/submit",
            datatype : 'json',
            data : data,

            success : function(data){
                if(data.status == 1){
                    $("#input_value").val("");
                    alert("Form submitted");
                }
            },
            error : function(data){
                console.log(data);
            }
        });

    })  
})


</script>