Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

343
Vistas
Django Login POST hangs when i do HttpResponseRedirect (302)

I'm Juan Manuel and I have a problem with my Login page in Django 1.8.18 (Python 2.7).
When I do "POST" of username/password Form (passes authenticate() and login() well) and have to redirect (HttpResponseRedirect) to my index page, the browser hangs waiting for a response (it stays in the login page).
After POST it wants to redirect to to '/' with a HTTP 302 and stays like that.

[01/Apr/2020 16:19:43] "POST /login/ HTTP/1.1" 302 0

I've noticed a few things:
1) It doesn't happend everytime.
2) On Chrome's developer mode with "Disable cache" mode on works fine.
3) On Firefox works fine.
4) With reverse() it's the same problem (internally calls HttpResponseRedirect()).
5) The problem exists on the Developing Server (Django) and in Production Server (Apache).
When it's hanging like that, if I press F5 (reload), works fine and the redirection goes to the index.

url.py:

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from .views import *

admin.autodiscover()


urlpatterns = patterns('',
    url(r'^', include('tadese.urls')),    
    url(r'^login/$', login),
    url(r'^login_cuota/$', login_cuota),
    url(r'^logout/$', logout),
    url(r'^admin/', include(admin.site.urls)),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG is False:   #if DEBUG is True it will be served automatically
    urlpatterns += patterns('',
        url(r'^staticfiles/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
    )

handler500 = volverHome
handler404 = volverHome

view.py

# -*- coding: utf-8 -*-

from django.contrib.auth import login as django_login, authenticate, logout as django_logout
from django.shortcuts import *
from settings import *
from django.core.urlresolvers import reverse
from django.contrib import messages
from tadese.models import Configuracion, Cuotas, Tributo, UserProfile
from tadese.utilidades import TRIBUTOS_LOGIN
from django.db.models import Q
from django.template.defaulttags import register
from django.conf import settings


def login(request):
    error = None
    LOGIN_REDIRECT_URL = settings.LOGIN_REDIRECT_URL
    if request.method == 'GET':
        if request.user.is_authenticated():
            return volverHome(request)

    try:
        sitio = Configuracion.objects.all().first()
    except Configuracion.DoesNotExist:
        sitio = None

    if sitio <> None:
        unico_padr = (sitio.ver_unico_padron == 'S')
        if sitio.mantenimiento == 1:
            return render_to_response('mantenimiento.html', {'dirMuni': MUNI_DIR, 'sitio': sitio},
                                      context_instance=RequestContext(request))
    else:
        unico_padr = False

    if request.method == 'POST':

        user = authenticate(username=request.POST['username'], password=request.POST['password'],
                            tributo=request.POST['tributo'])
        if user is not None:
            if user.is_active:
                django_login(request, user)

                if user.userprofile.tipoUsr == 0:
                    request.session["usuario"] = request.POST['username']
                    if unico_padr:
                        try:
                            padr = Cuotas.objects.filter(padron=request.POST['username'], estado=0).order_by(
                                '-id_cuota').first()
                            if padr:
                                LOGIN_REDIRECT_URL = reverse('ver_cuotas', kwargs={'idp': padr.id_padron})
                                return HttpResponseRedirect(LOGIN_REDIRECT_URL)
                        except:
                            padr = None
                    else:
                        LOGIN_REDIRECT_URL = reverse('padrones_responsable')
                return volverHome(request)
            else:
                ## invalid login
                error = u'Verifique que:\n. Los datos sean correctos.\n. Posea cuotas generadas en el sistema.'
        else:
            ## invalid login
            error = u'Verifique que:\n. Los datos sean correctos.\n. Posea cuotas generadas en el sistema.'
        # return direct_to_template(request, 'invalid_login.html')

    if error:
        messages.add_message(request, messages.ERROR, u'%s' % (error))
    tributos = Tributo.objects.filter()
    return render_to_response('index.html', {'dirMuni': MUNI_DIR, 'sitio': sitio, 'tributos': tributos},
                              context_instance=RequestContext(request))


def logout(request):
    request.session.clear()
    django_logout(request)
    return HttpResponseRedirect(LOGIN_URL)


def volverHome(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(LOGIN_URL)

    if request.user.userprofile.tipoUsr == 0:
        LOGIN_REDIRECT_URL = reverse('padrones_responsable')
    elif request.user.userprofile.tipoUsr == 1:
        LOGIN_REDIRECT_URL = reverse('padrones_estudio')
    else:
        LOGIN_REDIRECT_URL = reverse('padrones_responsable')

    return HttpResponseRedirect(LOGIN_REDIRECT_URL)


over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

From https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302

The HyperText Transfer Protocol (HTTP) 302 Found redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the Location header. A browser redirects to this page but search engines don't update their links to the resource (in 'SEO-speak', it is said that the 'link-juice' is not sent to the new URL).

Even if the specification requires the method (and the body) not to be altered when the redirection is performed, not all user-agents conform here - you can still find this type of bugged software out there. It is therefore recommended to set the 302 code only as a response for GET or HEAD methods and to use 307 Temporary Redirect instead, as the method change is explicitly prohibited in that case.

In the cases where you want the method used to be changed to GET, use 303 See Other instead. This is useful when you want to give a response to a PUT method that is not the uploaded resource but a confirmation message such as: 'you successfully uploaded XYZ'.

Also can you share the finding after using a supported python 3 version and django 2.2 LTS

over 4 years ago · Santiago Trujillo Denunciar

0

basically, that problem refers to that the web page is exposed to circular redirect as if you use a recursion by calling "redirect" statement

This happen to me when I created code that looks like the following:

    if not request.user.is_superuser or role != 'SubAdmin':
        return redirect('accounts:profile', request.user.id)

and that in the pseudo-code says: return me to the current user profile when the superuser is not in request, knowing that: I don't in the request as well so that, the web page will be exposed to the redirect "recursion"

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda