gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:18:18 24 4
gpt4 key购买 nike

我看到这个 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)

最佳答案

它不起作用,因为您没有在 View 中传递表单。你必须以 main_page.html 的观点.

因为您调用的是 main_page.html View 而不是 CreateOrder View ,这就是 Django 可以呈现您的表单的原因。如果你发布你的主要观点,我可以帮助你。

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

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

关于django - 如何在模态窗口中显示 django 表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46507805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com