Search code examples
javascripthtmldjangobackend

Is there any better way to do like history.back() in django backend?


In Django, I have "form view(GET)" and "action view(POST)"

If there is a validation error or any other error in action view,
I want browser to go back to the previous form page with the input data wrote by the user remains.

I tried:
At first, I used return redirect(request.META.get('HTTP_REFERER')).
This code goes back to the previous page well, but all the input fields became empty.

And now I am using return HttpResponse("<script>history.back();</script>") this code.
This works very well. but It looks weird sending javascript response.

What I expected was like return redirect.back()(with like HTTP 301 or 30X status code)

I was wondering if there is any better way or a proper way like officially provided by Django.


Solution

  • I want browser to go back to the previous form page with the input data wrote by the user remains.

    To achieve above goal, you should create a form on django

    forms.py

    from django import forms
    
    
    class UserForm(forms.Form):
        your_name = forms.CharField(label="Your name", max_length=100)
        your_surname = forms.CharField(label="Your surname", max_length=100)
    

    views.py

    from django.http import HttpResponseRedirect
    from django.shortcuts import render
    
    from .forms import UserForm
    
    def get_user_form(request):
     # if this is a POST request we need to process the form data
        if request.method == "POST":
            # create a form instance and populate it with data from the request:
            form = UserForm(request.POST)
            # check whether it's valid:
            if form.is_valid():
                # process the data in form.cleaned_data as required
                # ...
                # redirect to a new URL:
                return HttpResponseRedirect("/thanks/")
    
        # if a GET (or any other method) we'll create a blank form
        else:
            form = UserForm()
    
        return render(request, "userform.html", {"form": form})
    

    userform.html

    <form action="/user-form" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit">
    </form>
    

    Notice:

    if form.is_valid():
       # rest of the code...
    

    If this check fails, i.e. user-submitted info is invalid, form will be returned to the user with the (invalid) data submitted by the user .

    There is return render(request, "name.html", {"form": form}) line an the end.

    If the request is Get, i.e user is just requesting the form page, form will be empty.

    But if the request is Post and user-submitted data is invalid, prepopulated form is returned.

    You can learn more about django forms here