Home > front end >  Redirect to same page after form submitted in views.py not working while using Django paginator
Redirect to same page after form submitted in views.py not working while using Django paginator

Time:03-29

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)))

CodePudding user response:

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].

CodePudding user response:

I was able to get it working using sessions:

<a id="page" >{{ 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']
  • Related