0

I have a code of adding products list. when the user clicked the button a function is called which send the products list to the views by using ajax

function submition(container){
     $.ajax({
        url :'/compare_in/',
        type : "POST",
        data : {
            com_list : container,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        },
        success : function() {
            console.log('success')
        },
        error : function() {
            console.log('Failure');
        }
    });

}

urls:

urlpatterns = [path('compare_in/', views.compare_in)]

now in the views code, the product's list value is manipulating and scraping the data by the list value and storing the data in the dictionary

def compare_in(request):
  if request.method == 'POST':
    compare_res = request.POST.getlist('com_list[]')
    for item in range(len(compare_res)):
        if re.compile('edmi').search(compare_res[item]):
            compare_res[item] = 'xiaomi ' + compare_res[item]
    phone_list = ','.join(e.lower() for e in compare_res)
    phone_list = '-'.join(phone_list.split())
    .
    .
    .
    return HTTPResponse()

now I want to redirect to the different page with the value of the dictionary.

Note-return render() is not working

  • The `django` view will not be able to redirect to a new page. You should return a new url as part of your response, and do a `window.location('redirect_url')` inside the `sucess` function... – drec4s May 11 '19 at 10:27
  • nothing happing..i updated success fun to success : function() { window.location.url='http://127.0.0.1:8000/compare_in'; } – sourav kukreti May 11 '19 at 10:37
  • 1
    You need to do `window.location.assign("127.0.0.1:8000/compare_in")` – drec4s May 11 '19 at 10:40
  • but how to pass the dictionary to the template – sourav kukreti May 11 '19 at 10:49
  • Well, if you need to pass some `context` data, then I believe you will need to use a regular `django` form. Otherwise you can build an `url` and pass the data you need as a `querystring` like: `window.location.assign("127.0.0.1:8000/compare_in?param1=x&param2=y")` – drec4s May 11 '19 at 10:59
  • I want to build a URL but don't know how to do using ajax. can you explain to me. – sourav kukreti May 11 '19 at 11:19

1 Answers1

0

See this answer from another thread: Django: How do I redirect a post and pass on the post data

Also, it might be a good idea that you pass the data via URL param when redirecting.

from django.shortcuts import redirect

def compare_in(request):
    # rest of your code

    return redirect('https://example.com/{0}'.format(some['data']))

Django Docs: https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#redirect

Sample codes: https://simpleisbetterthancomplex.com/tips/2016/05/05/django-tip-1-redirect.html

bgsuello
  • 582
  • 5
  • 12