Home > other >  django redirect update to detail view after ajax update
django redirect update to detail view after ajax update

Time:12-08

I want to redirect to detail view after an update that uses ajax form submission.

Urls

path('<uuid:pk>', concept_detail, name='concept_detail'),
path('<uuid:pk>/update/', update_concept, name='update-concept'),

Detail View

def concept_detail(request, pk):
  context = {}

  context['concept'] = Concept.objects.get(id=pk)
  return render(request, 'concepts/concept_detail.html', context)

Update View

@login_required
def update_concept(request, pk):
  if request.method == 'POST':
    try:
      ## I GET THE FORM DATA - I haven't included the querysets because I haven't figured it out yet, just want to get the redirect to work
      print(request.POST)

   
      ## THIS DOESN'T WORK, BUT IT WORKS BELOW
      ##concept = Concept.objects.filter(id=pk).first()
      ##return redirect(concept)

      

    except Exception as e:
      print(e)
     
  else:
    ## this populates the update form
    context = {}
    obj = get_object_or_404(Concept, pk=pk)
    context['concept'] = obj
    if (request.user == obj.user):
      return render(request, 'concepts/concept_update.html', context)
      
    else:
      ## If user didn't create the post but tried to go to update url, redirect to detail page - WORKS
      concept = Concept.objects.filter(id=pk).first()
      
      return redirect(concept)

Response Codes Don't know why I'm getting 302 for update view -- don't get that for my create view, and the forms and ajax are basically the same.

"POST /concepts/1241955d-1392-4f85-b8ed-e3e0b89b4e50/update/ HTTP/1.1" 302 0
"GET /concepts/1241955d-1392-4f85-b8ed-e3e0b89b4e50 HTTP/1.1" 200 7577

AJAX FORM SUBMIT The form is a lot more dynamic than this which is why I'm using Ajax. The data gets sent to server, but the update page stays on the screen and doesn't go to the detail page.

conceptForm.addEventListener('submit', function(e){
  e.preventDefault();
  var formdata = new FormData();

  formdata.append('concept', conceptInput.value)
  formdata.append('definition', definitionInput.value)

  $.ajax({
    url: "",
    method: "POST",
    data: formdata,
    enctype: 'multipart/form-data',
    processData: false,
    contentType: false,
    success: function(json){
      console.log('SUCCESS')
     
      conceptInput.value = ''
      definitionInput.value = ''      
    },
    error: function(xhr, errmsg, err){
      console.log('ERROR')
      console.log(xhr.status   ": "   xhr.responseText);
    }
  })
  
})

I use this code from the Real Python blog to handle the csrf token creation.

WORKING NOW

def update_concept(request, pk):
   is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

   if request.method == 'POST' and is_ajax:
      redirect_url = 'http://127.0.0.1:8000/concepts/' str(pk)
      return JsonResponse({'redirect_url':redirect_url})


## IN Javascript


$.ajax({
  success: function(json){
    window.location.replace(json['redirect_url'])
  }

})
 

CodePudding user response:

You cannot redirect a user after an ajax request using your backend. The redirect needs to be handled in your ajax call.

In your update view, check if it's an ajax request. For example, using is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'.

If it's an ajax request don't return a redirect but a JsonResponse, such as return JsonResponse({'concept':concept}).

In your ajax success option, you can then handle the redirect.

    success: function(data){
      console.log('SUCCESS');
     
      conceptInput.value = '';
      definitionInput.value = '';
      
      concept = data['concept'];
      redirect_url = #define your redirect url
      window.location.replace(redirect_url);
    
    },

Instead of returning the concept value, you can also construct the url in your update view and return it to the ajax call.

  • Related