在同一视图中使用POST和GET django

时间:2015-11-17 21:22:34

标签: javascript python django

点击一个按钮(send_net),我想发送存储在输入" text"中的文本。从django模板到视图以及与该视图关联的URL。

关联的html:

<div class="search_box">
<form id="target" action="." method="post">{% csrf_token %}
  <input type="text" id = "sbox" placeholder="Search...">
  <a href = "create_network" type="button" id="send_net"></a>          
</form>
</div>

我使用POST请求将变量发送到视图:

$(document).ready(function(e){
 $('#send_net').click(function(e){
  var query = document.getElementById("sbox").value;
  var d = {'query':query};
  $.ajax( link, {
    type: "POST",
    data: d,
    success: function(data) {
      alert('call back');
    },
    error:   function(jqXHR, textStatus, errorThrown) {
      alert("Error, status = " + textStatus + ", " +
          "error thrown: " + errorThrown
    );
    }
  });
});

});

views.py

def create_network(request):
    c={}
    c.update(csrf(request))
    r=[]
    if request.method=='POST':
        if 'query' in request.POST:
            query = request.POST['query']
            r.append({'id':1, 'label':query})
    venues = Venue.objects.filter(title__contains="Life")
    for venue in venues:
        d={}
        d['id'] = venue.id
        d['label'] = venue.title
        r.append(d)
    data = json.dumps(r)
    edges = [{'from':15505, 'to':19092}]
    data_e = json.dumps(edges)
    con = RequestContext(request, {"nodes":data, "edges":data_e})
    return render_to_response('quir/network.html', c, con)

然而,r永远不会有&#39; {&#39; id&#39;:1,&#39;标签&#39;:查询}&#39;因为后续的GET请求会将其清除干净。如何在&#39; r&#39;中保留查询值?我对Django和javascript相对较新,很抱歉,如果这是基本的。 非常感谢。

2 个答案:

答案 0 :(得分:2)

你可以使用Class-based views为GET定义一个方法,为POST定义另一个方法:

class CreateNetwork(View):  # Extend from the view you need

    c = {}
    r = []

    def get(self, request, *args, **kwargs):

        # This code will be executen in a GET request

        # here you can access c or r with self
        self.c.update(csrf(request))  # this is just an example
        ...

    def post(self, request, *args, **kwargs):

        # This code will be executed in a POST request

        self.r.append(...)

答案 1 :(得分:1)

您需要使用

if request.method == 'POST':
   pass # Your code
else:
   pass # For GET

如果要同时处理POST和GET,则需要像这样指定它。