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

165
Vistas
Redirect to same page after form submitted in views.py not working while using Django paginator

I want to redirect to same page after submitting form which fetches view from views.py. The problem is paginator. After submitting Django form page reloads to page 1. I want browser to stay on the same page after submitting form. Error I get: django.urls.exceptions.NoReverseMatch: 'http' is not a registered namespace. Help would be greatly appreciated!

Code calling path in js:

let path = window.location.href

Fetching api:

            subedit[i].addEventListener('click', () => {
            fetch(`/edit/${content[i].id}`,
            {
                method: 'POST',
                headers: {'X-CSRFToken': csrftoken},
                mode: 'same-origin',
                body: JSON.stringify({
                post: textarea[i].value,
                page: path           
                })}).then(() => {
                    editdiv[i].style.display = 'none';
                    post[i].style.display = 'block';
                })})

views.py:

def edit(request, post_id):
    data = json.loads(request.body)
    content = data.get("post", "")
    post=Post.objects.get(id=post_id)
    page = data.get("page", "")
    if request.method == "POST":
        if post.user == request.user:
            post.post=content
            post.save()
            return HttpResponseRedirect(reverse(str(page)))
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I was able to get it working using sessions:

<a id="page" class="page-link">{{ num }}</a>
let page=document.querySelector("#page").innerHTML
            fetch(`/edit/${content[i].id}`,
            {
                method: 'POST',
                headers: {'X-CSRFToken': csrftoken},
                mode: 'same-origin',
                body: JSON.stringify({
                post: textarea[i].value,
                page: page             
                })}).then(() => {
                    editdiv[i].style.display = 'none';
                    post[i].style.display = 'block';
                })})
def edit(request, post_id):
    data = json.loads(request.body)
    content = data.get("post", "")
    post=Post.objects.get(id=post_id)
    page = data.get("page", "")
    request.session['page'] = page
    if request.method == "POST":
        if post.user == request.user:
            post.post=content
            post.save()
            return HttpResponse(page)
def index(request):
    posts = Post.objects.all().order_by('-date')
    paginator = Paginator(posts,10)
    page_number = request.GET.get('page')
    if request.session.has_key('page'):
        page_number = request.session['page']
        del request.session['page']
about 4 years ago · Juan Pablo Isaza Denunciar

0

reverse(…) [Django-doc] looks for a view with the given name, it does not take a URL as input. You can use this directly in the HttpResponseRedirect [Django-doc], so:

def edit(request, post_id):
    data = json.loads(request.body)
    content = data.get("post", "")
    post=Post.objects.get(id=post_id)
    page = data.get("page", "")
    if request.method == 'POST':
        if post.user == request.user:
            post.post=content
            post.save()
            return HttpResponseRedirect(page)

You should also return HttpResponses for the GET requests, and in case the post.user is not the same as the request.user.


Note: It is often better to use get_object_or_404(…) [Django-doc], then to use .get(…) [Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using .get(…) will result in a HTTP 500 Server Error.


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

about 4 years ago · Juan Pablo Isaza 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