如何在模态窗口中显示django表单?

时间:2017-09-30 23:01:35

标签: django

我看到了这个post,但它没有帮助我

在模态窗口中,不显示表单。

查看:

class CreateOrder(FormView):
    template_name = 'toner/add_order.html'

    form_class = OrderForm
    success_url = '/toner/'

    def form_valid(self, form):
        form.save()
        return super(CreateOrder, self).form_valid(form)

add_order.html:

<div id="order" class="modal fade" role="dialog">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-body">
            <div class="container txt-box">
                <form action="{% url 'add_order' %}" role="form" method="post">
                    {% csrf_token %}
                    {{ form.media }}
                    {{ form.address }}
                    {{ form.room }}
                    {{ form.count }}
                    <button class="btn btn-success" type="submit">
                        Done
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

main_page.html:

{% extends 'toner/base.html' %}

{% block main_page %}

....

<div>
    <button class="btn btn-primary" data-toggle="modal" data-
    target="#order">
        Order
    </button>
    {% include "toner/add_order.html" %}
</div>
{% endblock %}

网址:

url(r'add_order/$', CreateOrder.as_view(), name='add_order'),

如果我直接转到url(/ add_order),它就可以了。我可以看到表格。但是从main_page.html,模态窗口是空的。也许有人为自己解决了这样的任务?

更新

from django.views.generic import ListView, FormView
from .models import Printer, Order
from .forms import OrderForm


class MainPageView(ListView):
    template_name = 'toner/main_page.html'

    model = Printer

    def get_context_data(self, **kwargs):
        context = super(MainPageView, self).get_context_data(**kwargs)
        context['printer'] = Printer.objects.all()
        context['order'] = Order.objects.all()
        return context


class CreateOrder(FormView):
    template_name = 'toner/add_order.html'

    form_class = OrderForm
    success_url = '/toner/'

    def form_valid(self, form):
        form.save()
        return super(CreateOrder, self).form_valid(form)

1 个答案:

答案 0 :(得分:4)

它不起作用,因为您没有在视图中传递表单。您必须使用main_page.html

的视图

因为您正在调用main_page.html视图而不是CreateOrder视图,这是Django可以呈现您的表单的原因。如果您发布主视图,我可以帮助您。

我不确定基于类的视图,但应该是这样的:

class MainPageView(ListView, FormView):
    template_name = 'toner/main_page.html'

    model = Printer

    form_class = OrderForm
    success_url = '/toner/'

    def form_valid(self, form):
        form.save()
        return super(MainPageView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(MainPageView, self).get_context_data(**kwargs)
        context['printer'] = Printer.objects.all()
        context['order'] = Order.objects.all()
        return context