fsimoes
fsimoes

Reputation: 79

Proper way to write 'request.POST.post' in class based views

I'm trying to use CBV. I'm new to it. I'm having problem requesting a POST data inside a form.

Here is my view:

    form_class = LocatarioForm
    template_name = 'contrato/locatario_form.html'


    def get_initial(self):
        return {
            'contrato': self.kwargs["pk"]
        }

    def post(self, request, pk):
        segundolocatario = request.POST['segundolocatario']
        return segundolocatario

    def get_success_url(request):
        # if request.POST.post('segundolocatario') == 'Sim'
        #     return reverse('contrato:locatario', kwargs={'pk': self.object.pk})
        return reverse('contrato:conjugec', kwargs={'pk': self.object.pk})

Here is the template:

                <form method="post">
                    {% csrf_token %}
                    {{form}}
                    
                    <label for="segundolocatario">Deseja cadastrar um segundo locatário para este contrato?</label>
                    <select name="segundolocatario" id="">
                        <option value="sim">Sim</option>
                        <option value="nao">Não</option>
                    </select>
                    <br><br>
                    <button type="submit">Próxima etapa</button>

                </form>

I need to request 'segundolocatario' to flow control my templates.

How can I do this in CBV? Thank you.

Upvotes: 0

Views: 390

Answers (1)

I don't think you have grasped the basics of class based views. Unless you are inheriting from View which is the base class for all generic views, you should not be overriding get and post methods (they are populated with some boilerplate depending on the class).

Assuming that you use FormView, you should use form_valid method. This method takes form as argument, from which you can get validated post data using form.cleaned_data.

I suggest you check Django documentation on how to override these methods. There is this great website that shows all internal properties and methods CBV's have, so you can understand them better.

Upvotes: 1

Related Questions