Django - TemplateView and POST

Viewed 16002

I have a page generated by a TemplateView and containing a POST form. How can I use this form with a TemplateView.

There is an example similar of my code :

class ProjetMixin(object) :

    ...

    def get_context_data(self, **kwargs) :
        ...
        return context


class AView(ProjetMixin, TemplateView):
    template_name = 'path-to-the-page.html'

    offre = None

    def get_context_data(self, **kwargs) :

        context = super(AView, self).get_context_data(**kwargs)

        try :   
            self.offre = self.projet.offredeprojet
        except OffreDeProjet.DoesNotExist :
            self.offre = None   

        if self.request.user.is_authenticated() :               
                print(" method = ",self.request.method) //display "GET"
                if self.request.method == "POST" :
                    print("post")

        context['offre'] = self.offre

        return context

So it's normal that the only method is GET but how can I use POST ?

I have this error when I submit the form :

Method Not Allowed (POST): /projets/pseudoaz/recrutement
[2017/07/01 11:50:57] HTTP POST /projets/pseudoaz/recrutement 405 [0.06, 127.0.0.1:57560]

Thank you

2 Answers

Django has long been updated to support the extension of it's views. The following code illustrates how to use django's generic Templateview with a post method. Alternatively, one could use View, Formview or function-based-view depending on how complex the logic gets, this just expresses the TemplateView with post implementation.

from django.views.generic import TemplateView


class TemplateViewWithPost(TemplateView):
    template_name = 'path-to-the-page.html'
    
    def get_context_data(self, **kwargs):
        kwargs = super(TemplateViewWithPost, self).get_context_data(**kwargs)
        # Your code here
        kwargs['foo'] = "bar"
        return kwargs

    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        # Your code here
        # Here request.POST is the same as self.request.POST
        # You can also access all possible self variables
        # like changing the template name for instance
        bar = self.request.POST.get('foo', None)
        if bar: self.template_name = 'path-to-new-template.html'
        previous_foo = context['foo']
        context['new_variable'] = 'new_variable' + ' updated'
        
        return self.render_to_response(context)
Related