How to use context with class in CreateView in django?

前端 未结 3 1832
天涯浪人
天涯浪人 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:28

    Since your are creating a new instance of a Car, there is no context for get_context_data because there is no object yet. I didn't test using Mixin to get the context from another class as suggested above, but that seems reasonable. However, if I can assume you want to use the basic CreateView, UpdateView and DeleteView, then I solved this by assuming I will have no context for CreateView. Then in my template I used an if to make the decision, such as:

    {% csrf_token %} {{ form.as_p }}

    In DeleteView I include:

    context['buttonword'] = 'Delete'
    

    In UpdateView I include:

    context['buttonword'] = 'Update'
    

    As I said, I do not set buttonword in CreateView. Hence, when the template logic is done, if buttonword is assigned, the word in it shows up in the button, otherwise Save shows up on the button.

提交回复
热议问题