Search code examples
djangodjango-formsdjango-generic-views

Django - Modify a generic detail view to manage a form and post data - Django


I'am new to django.

I want to reate a webpage, and display information about a specific object and have a form to send a message about this object.

At the beginning, i used a detail view to display the info about the object. Then a created a message form based on my Message Class

I used get_context_data to pass the form in the context for the template.

I would like to know if there is a way to manage the validation of the form in the same view or should i come back to a function view?

I've seen that FormMixin can help. Could you tell me if it's the right solution.

Thank you for your help

My view:

class LoanDetailView(DetailView):

    model = Loan

    def get_context_data (self, **kwargs):
        context = super(LoanDetailView, self).get_context_data(**kwargs)
        msg_form = MessageForm()
        context['msg_form'] = msg_form

        return context

In my template:

        <form method="POST"> 
            {%csrf_token%}
            <fieldset class="form-group">
                {{ msg_form | crispy  }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit"> Envoyer </button>
            </div>
      </form>

Solution

  • You could use this pattern

    class LoanDetailView(DetailView):
        def get_context_data(self, **kwargs):
            [...]
    
        def post(self, request, *args, **kwargs):
            form = MessageForm(request.POST)
            if form.is_valid():
                [...]  # logic similiar as in function based view