Django:当表单处于模态

时间:2015-06-18 14:43:43

标签: django twitter-bootstrap bootstrap-modal

我正在尝试创建一个能够在数据库中添加和显示某些信息的Django Web应用程序(下面看到的代理模型)我在twitter bootstrap模式中有一个表单。当我输入有效数据并提交时,一切都按预期工作,模态重定向到视图页面。但是,当我输入无效信息时,不会重新显示显示验证错误的模态,而是重定向到空白页面。我有视图打印出验证错误,一切都在那里,它只是没有在页面上显示。当我从模板中删除模态类(因此它显示在页面而不是模式中)时,将显示错误信息。如何让它显示在模态中?

查看:

class AgentAddView(CreateView):
    model = Agent
    template_name = "agent_form.html"
    success_url = '/ui/all_agents'
    form_class = NewAgentForm

    def form_valid(self, form):
        form.save()
        print('hererererer')
        return redirect('/ui/all_agents')

    def form_invalid(self, form):
        return self.render_to_response(self.get_context_data())

形式:

class NewAgentForm(forms.ModelForm):
    class Meta:
        model = Agent
        fields = ['hostname', 'ip_address', 'domain', 'username', 'password', 'password', 'encrypted']

    hostname = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Hostname'}))
    ip_address = forms.GenericIPAddressField(required=True, widget=forms.TextInput(
    attrs={'placeholder': 'IP Address'}), label="IP Address")
    domain = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Domain'}))
    username = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Username'}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}), required=False)
    confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}), required=False)
    is_encrypted = forms.BooleanField(required=False)

模板:

{% extends 'base_page.html' %}
{% block content %}
<div class="modal fade" id="add-agent-modal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h3>Add Agent</h3>
            </div>
            <form method="post" action="{% url 'add_agent' %}">
                <div class="modal-body">
                    {% csrf_token %}
                    {{ form.as_p }}
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success" >Add</button>
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                </div>
            </form>
        </div>
    </div>
</div>

{% endblock %}

1 个答案:

答案 0 :(得分:2)

您需要编写一些javascript来感知表单是否已提交并且发现无效,如果是,则显示模态。

您可以根据错误状态在模板中设置javascript全局变量:

<script>
    document.formHasErrors = {% if form.errors %}true{% else %}false{% endif %};
</script>

然后你可以use javascript to tell the modal to open

<script>
    $( document ).ready(function() {
       if (document.formHasErrors) {
           $('#add-agent-modal').modal('toggle');
       }
    });
</script>

它不是特别漂亮,但它应该是有效的。