skip to Main Content

Updated Question:

Wrong redirection of URL in Django. I have this:

views.py.

def graph(request):
    if request.method == 'POST' and 'text' in request.POST:
        print("testing....")
        print(request.POST.get('text'))
        name = request.POST.get('text')
        context = {
            'name': name,
        }
        print(context)
        return render(request, 'StockPrediction/chart.html', context)
    else:
        return render(request, 'StockPrediction/greet.html')

urls.py

urlpatterns = [
    path("", views.greet, name='greet'),
    path("index/", views.index, name='Stock Prediction'),
    path("prediction/", views.prediction, name='Prediction'),
    path("view/", views.graph, name='Graph'),
]

for testing purposes, I m using a print statement. So there is no problem until printing print(context) but the problem is it goes to 'StockPrediction/greet.html' not 'StockPrediction/chart.html'. which I need.

2

Answers


  1. You should use ajax request:

    $.ajax({
        type: 'POST',
        url: 'YOUR VIEW URL',
        data: {'row': row, 'text': text},
        success: function (data){
            DO SOMETHING HERE if VIEW has no errors
        })
    

    in your view:

    row = request.POST.get('row')    
    text = request.POST.get('text')
    

    also you should care about crsf-token. Documentation

    Login or Signup to reply.
  2. your can POST it GET it or put it as a variable in your url. here is a post approach:

    using jquery :

    $.ajax({
        url : "/URL/to/view", 
        type : "POST", // or GET depends on you
        data : { text: $text },
        async: false,
        // handle a successful response
        success : function(json) {
             // some code to do with response
             }
        },
    
        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
    

    In your view you can get the data as json and return josn as response

    import json
    def my_view(request):
        if request.method == 'POST':
             response_data = {}   // to return something as json response
             text = request.POST['text']
             ...
             return HttpResponse(
             json.dumps(response_data),
             content_type="application/json"
        else:
            return HttpResponse(
                json.dumps({"nothing to see": "this isn't happening"}),
                content_type="application/json"
            )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search