如何在django中的CreateView中使用上下文?

时间:2014-01-02 06:22:03

标签: django django-views

如何在django中的CreateView中使用上下文?

在我之前:

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

def CreateCar(CreateView):
    info_sended = False
    if request.method == 'POST':
        form = FormCar(request.POST, request.FILES)
        if form.is_valid():
            info_sended = True
            form.save()
    else:
        form = FormCar()
    ctx = {'form': form, 'info_sended':info_sended}
    return render_to_response("create_car.html", ctx,
        context_instance=RequestContext(request))

现在,有了,并尝试:

class CreateCar(CreateView):
    info_sended = False
    template_name = 'create_car.html'
    model = Car
    success_url = 'create_car' #urls name

    def form_valid(self, form):
        info_sended = True
        ctx = {'form': form, 'info_sended':info_sended}
        return super(CreateCar, self).form_valid(form)

我的html页面是:

<!-- create_car.html -->
{% extends 'base.html' %}

{% block content %}

{% if info_sended %}
    <p>Data saved successfully</p>
    <p><a href="{% url 'list_cars' %}">Show List</a></p>
{% else %}
    <form class="form-horizontal" action="" method="post">
        {% csrf_token %}
        {% include "form.html" %}
        <div class="col-md-offset-1">
            <button class="btn btn-primary" type="submit">Add</button>
        </div>
    </form>
{% endif %}

{% endblock %}

3 个答案:

答案 0 :(得分:6)

您应该在班级视图中定义get_context_data()方法。将代码更新为

from django.shortcuts import render

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
        # Instead of return this HttpResponseRedirect, return an 
        #  new rendered page
        super(CreateCar, self).form_valid(form)
        return render(self.request, self.template_name,
                      self.get_context_data(form=form))


    def get_context_data(self, **kwargs):
        ctx = super(CreateCar, self).get_context_data(**kwargs)
        ctx['info_sended'] = self.info_sended
        return ctx

答案 1 :(得分:0)

您必须使用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

如果您看到django source CreateView继承自BaseCreateView,则此内容继承自ModelFormMixin,此内容继承自FormMixin,此内容继承自ContextMixin {3}},这个定义的唯一方法是get_context_data。 希望这会对你有所帮助。

PD:对于更好地理解Python中的继承而言,这可能有点令人困惑,请不要阅读关于MRO的article

答案 2 :(得分:0)

由于您正在创建Car的新实例,因此没有get_context_data的上下文,因为还没有对象。我没有使用Mixin来测试如上所述从另一个类获取上下文,但这似乎是合理的。但是,如果我可以假设你想要使用基本的CreateViewUpdateViewDeleteView,那么我通过假设我没有CreateView的上下文来解决这个问题。然后在我的模板中,我使用 if 来做出决定,例如:

<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value={% if not buttonword %}Save{% else %}{{ buttonword }}{% endif %}>
</form>

DeleteView我包括:

context['buttonword'] = 'Delete'

UpdateView我包括:

context['buttonword'] = 'Update'

正如我所说,我没有在buttonword中设置CreateView。因此,当模板逻辑完成时,如果分配了buttonword,则其中的单词显示在按钮中,否则保存显示在按钮上。