Search code examples
pythondjangoformshttp-redirect

Django - multiple pages using one form


There's a number of questions regarding one page and handling multiple forms but I seem to have the reverse issue. I have two pages that contain datatables showing filtered data from my model, but both are the same source data and every object (in both tables, on both pages) has the same "edit" button bringing the user to the same form allowing them to edit the object details. My problem is redirecting from the form to the original page. I have tried using HttpResponseRedirect but that doesn't seem to be working, it goes to my homepage everytime.

def edit_drawing(request, drawing_no):
    drawing = get_object_or_404(Drawings, pk=drawing_no)
    if request.method == "POST":
        form = DrawingForm(request.POST, instance=drawing)
        if form.is_valid():
            form.save()
            messages.success(request, f'Drawing {drawing.drawing_no} was successfully updated.')
            return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
    else:
        form = DrawingForm(instance=drawing)
    
    return render(request, 'edit_drawing.html', {'form': form, 'drawing': drawing})

I thought I could do something like this where my tag in the original html would tell the redirect where to go if I passed a variable:

<a href="{% url 'schedule:edit_drawing' drawing_no=your_drawing_no %}?next={{ request.path }}">Edit Drawing</a>

But when I try to use return redirect(next_url) in the view, next_url is undefined and doesn't work.

Does anyone have a best practice to handle something like this? I would like to try and avoid individual forms for each page that are performing the same function.


Solution

  • Not sure why but I could not get the HTTP_REFER to work like so many other people. I did find the solution though

    to the edit button on every page that uses the same form to edit an existing object on the model I modified the link like so:

    <a href="{% url 'schedule:edit_job' job.job_no %}?next={{ request.path|urlencode }}" class="btn btn-primary">Edit</a>
    

    Add the input line to my edit_form.html:

    <form method="POST">
        {% csrf_token %}
        {{ form }}
        <input type="hidden" name="next" value="{{ request.GET.next }}">
        <button type="submit">Save</button>
    </form>
    
    

    and the return in views.py:

    def edit_job(request, job_no):
                ...
                next_url = request.POST.get('next', '/')
                return HttpResponseRedirect(next_url)
    

    I tested this on several pages and whichever the 'edit' button was pressed is the one it returns to after submit.