1

I have the following view:

def addtolist(request):
  var1 = request.session.get('session_pmids', False)
  pmids = request.POST.get('pmids', '')
  pmids = pmids.split(",")

  if var1:
    pmids = pmids + var1
    request.session["session_pmids"] = pmids

  if not var1:
    request.session["session_pmids"] = pmids

  return HttpResponse(None, request)

and in the template I have the following:

    <form id="go" action="/addtolist/" method="post" data_url>{% csrf_token %}
    <input type="hidden" name="pmids" id="pmids" value="">
    <button class = "btn btn-default" onclick="getChecked()">Get selected abstracts as reference</button> 
    </form>

The button press will retrieve some data via the getChecked() function. which will add data to the input box 'pmids'. These will be cast to the view and the variables will be added to the session.

How can I let Django return nothing from the view? so, no new page, no reload. Only the request object (to keep the session)

Henkes
  • 288
  • 4
  • 16
  • You mean something like this? http://stackoverflow.com/a/28341345/940098 – Wtower Jun 12 '15 at 11:54
  • So you suggest making an Ajaxable response object and return that response? what would the object look like knowing that i only want to return the request? (so the `request.session["session_pmids"] = pmids ` – Henkes Jun 12 '15 at 12:05

1 Answers1

4

You dont need to return request object to keep the session data. Use Ajax

In django

from django.http import JsonResponse

def addtolist(request):
  var1 = request.session.get('session_pmids', False)
  pmids = request.POST.get('pmids', '')
  pmids = pmids.split(",")

  if var1:
    pmids = pmids + var1
    request.session["session_pmids"] = pmids

  if not var1:
    request.session["session_pmids"] = pmids

  return JsonResponse({'status': 'ok')

javascript

$('form#go').submit(function(e){
  e.preventDefault();
  $.post('view-url', $(this).serialize());
});

links:

Community
  • 1
  • 1
Alexander Sysoev
  • 825
  • 6
  • 16
  • I got **Forbidden (403) CSRF verification failed. Request aborted.** I'm not using any form, I'm using a button that updates a models value – AnonymousUser Nov 29 '21 at 07:07