R
R
rusyska550112021-09-14 01:54:56
Django
rusyska55011, 2021-09-14 01:54:56

How to correctly render the page after a post request in the Django3 View class?

views.py:

from django.shortcuts import render, redirect
from django.views import View

from .models import HeaderTextDesc, Contacts, Portfolio
from Services.models import Services
from Applications.forms import ApplicationsForm


class MainView(View):
    def post(self, req):
        form = ApplicationsForm(req.POST)
        if form.is_valid():
            form.save()
            return redirect('/')

    def get(self, req):
        headerTextDesc, contacts = HeaderTextDesc.objects.all()[0], Contacts.objects.all()[0]
        services_objects = Services.objects.all()
        potrfolio_objects = Portfolio.objects.all()
        form = ApplicationsForm()

        context = {
            'title': headerTextDesc.title,
            'desc': headerTextDesc.description,
            'tel_number': contacts.tel_number,
            'vk_link': contacts.vk_link,
            'telegram_link': contacts.telegram_link,
            'whatsApp_link': contacts.whatsApp_link,

            'services_objects': services_objects,
            'portfolio_objects': potrfolio_objects,

            'form': form
        }

        return render(req, 'MainTEST.html', context)

After a form post request, I would like to render the page in the same way as the get() function, BUT pass a new key to the context variable containing the response from the server how the form was submitted and display it on the page. Is it really necessary to copy all the code contained in get() into the post() method and return the render? Or is there a humane way instead of duplication?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
javedimka, 2021-09-14
@javedimka

Or is there a humane way instead of duplication?

Yup, use FormView.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question