How to make Redirect on the page with Django

Asked

Viewed 1,309 times

0

How to redirect passing an object as parameter in Django already tried redirect() and HttpResponseRedirect but I can’t send an object to page in Sponse, every time I hit F5 it wants to resend the request. How solve this problem ?

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from webapp.metodos.gauss import Gauss
from django.urls import reverse


import numpy as np
import csv
import io


def index(request):
    if request.method == 'POST':
        matriz = readCSV(request)
        return render(request, 'index.html', {'matriz': matriz})
    return render(request, 'index.html')


def gauss(request):
    if request.method == 'POST':
        g = Gauss()
        matriz = readCSV(request)
        resultado = g.executar(matriz)  
        return render(request, 'gauss.html', {'resultado': resultado})
    return render(request, 'gauss.html')


def gaussjordan(request):
    return render(request, 'gaussjordan.html')


def fatoracaolu(request):
    return render(request, 'fatoracaolu.html')


def readCSV(request):
    data = request.FILES['file'].read().decode('UTF-8')
    io_string = io.StringIO(data)
    matriz = np.loadtxt(io_string, delimiter=',', dtype=int)
    return matriz



    <form class="form-group" action="{% url 'index' %}" method="POST" 
                   enctype="multipart/form-data">
                        {{ form.file }}
                        {% csrf_token %}
            <input type="submit" value="Executar">
            <input type="file" name="file" id="arquivo" required />
    <form>
  • Are you looking to redirect to a page after the Submit of a form? Could you post the full view code?

  • correct I want to redirect passing an object that will be loaded on the page changed code put form

  • Put the view code, where you process the form, all the code if possible, because I think using a CCBV will be better, but to tell you how to do it, I’ll need to see the view.

  • I put all view and form code in html

2 answers

0

Try changing the Return render from your if to Redirect. Ex:

def gauss(request):
    if request.method == 'POST':
        g = Gauss()
        matriz = readCSV(request)
        resultado = g.executar(matriz)  
        return redirect('gauss')
    return render(request, 'gauss.html')

0

Apparently its problem is the structure of views that you’re thinking about. It would be much simpler for you to pass resultado or None for the template, and in the template you show the result only if it exists. Example:

def gauss(request):
    resultado = None
    if request.method == 'POST':
        g = Gauss()
        matriz = readCSV(request)
        resultado = g.executar(matriz)  

    return render(request, 'gauss.html',  {'resultado': resultado})

Already to redirect the user to another URL in Django you must return an object of type HttpResponseRedirect passing a URL to the constructor.

from django.http import HttpResponseRedirect

def my_view(request):
    return HttpResponseRedirect("/")
    # ou
    return HttpResponseRedirect("/minha-pagina/")
    # ou
    return HttpResponseRedirect("minha-pagina/relativa")

But this is no more common way to redirect, usually if you use a utility function provided by Django himself, it would be the function django.shortcuts.redirect.

It is most commonly used because it comes to mount the URL automatically for you, just have you pass:

  1. A model that implements the method get_absolute_url():

    from django.shortcuts import redirect
    
    def my_view(request):
        ...
        obj = MyModel.objects.get(...)
        return redirect(obj)
    

    If you check the source code you will see that it is enough to be any object that has an invocable attribute called get_absolute_url, it is not mandatory to be a Model.

  2. A string representing a view (you can pass the arguments to the view just like you do when you use django.urls.reverse):

    from django.shortcuts import redirect
    
    def my_view(request):
        ...
        return redirect('some-view-name', foo='bar')
    
  3. Pass a string that represents a URL (same behavior as when you use HttpResponseRedirect)

    from django.shortcuts import redirect
    
    def my_view(request):
        ...
        return redirect('/')
    

To better understand, you can (and should) check the function code django.shortcut.redirect, you will see that she does not do much more than call the function resolve_url. The code of the function resolve_url is short and lies below redirect in the same file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.