[Python] How can I redirect to the same page after submitting a form using Django and display...

Discussão em 'Python' iniciado por Stack, Setembro 7, 2025.

  1. Stack

    Stack Membro Participativo

    This is my class based view function

    Whenever the use finishes to enter the required data and click the submit button. I want the page to reload so user can see the data they have submitted.

    I don't want to redirect the user to another page. But the app behaves differently.

    I'm trying to see how I can manage to make this work please

    class homeView(View):
    def get(self, request):
    data = recipemeal.objects.all().order_by("-id")

    context ={
    "recipes":data,
    "form":RecipeForm()
    }
    return render(request, "index.html", context)

    def post(self, request):
    form = RecipeForm(request.POST)
    data = recipemeal.objects.all().order_by("-id")

    if form.is_valid():
    form.save(commit=True)
    return HttpResponseRedirect(reverse("home"))

    else:
    context = {
    "recipes": data,
    "form": RecipeForm()
    }
    return render(request, "index.html", context)


    *************************************************************************
    urlpatterns = [
    path("", views.homeView.as_view(), name="home"),
    ]

    *********************************************************************
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    </head>
    <body>
    <h2>Hi there, my name is Wilkenson</h2>
    <section>
    <div class="container">
    <div>
    <form method="POST">
    {% csrf_token %}
    {{ form }}
    <button class="btn" type="submit">Add Data</button>
    </form>
    </div>
    <div>
    <form action="/" method="POST">
    {% csrf_token %}
    <button class=" button generate-pdf">Generate Plan</button>
    </form>
    </div>

    {% if recipes %}
    <table>
    <tr>
    <th>Recipe No.</th>
    <th>Day-Time</th>
    <th>Recipe Name</th>
    <th>Description</th>
    <th>Action</th>
    </tr>
    {% for item in recipes %}
    <tr>
    <td>{{item.id}}</td>
    <td>{{item.date}}</td>
    <td>{{item.title}}</td>
    <td>{{item.content}}</td>
    <td><a href="">Update</a>/<a href="">Delete</a></td>
    </tr>
    {% endfor %}
    </table>
    {% endif %}
    </div>
    </section>
    </body>
    </html>

    Continue reading...

Compartilhe esta Página