How to use context with class in CreateView in django?

前端 未结 3 1834
天涯浪人
天涯浪人 2021-01-03 10:04

How to use context with class in CreateView in django?

Before i have:

#views.py
from django.views.generic import CreateView
from cars.models import *         


        
3条回答
  •  生来不讨喜
    2021-01-03 10:15

    You have to use get_context_data

    class CreateCar(CreateView):
        info_sended = False
        template_name = 'create_car.html'
        model = Car
        success_url = 'create_car' #urls name
    
        def form_valid(self, form):
            self.info_sended = True
            return super(CreateCar, self).form_valid(form)
    
        def get_context_data(self, **kwargs):
            ctx = super(CreateCar, self).get_context_data(**kwargs)
            ctx['info_sended'] = self.info_sended
            return ctx
    

    If you see the django source CreateView inherits from BaseCreateView this one inherits from ModelFormMixin in turn this one inherits from FormMixin and this one inherits from ContextMixin and the only method this one defines is get_context_data. Hope this helps you.

    PD: This may be a bit confusing for better understanding of inheritance in Python feel free of read this article about MRO.

提交回复
热议问题