如何改进Django表单错误?

时间:2022-10-24 10:30:12

If I have a django form, where I want it to provide a bootstrap error input (<input type="text" id="inputError">) to show an error instead of the bullet-list {{ form.title.error }}, how would I go about doing this? Right now I have:

如果我有一个django表单,我希望它提供引导错误输入(),以显示错误,而不是项目列表{form.title。error},我该怎么做呢?现在我有:

  {% if UF.title.errors %}                   
        {{ UF.title }}
        {{ UF.title.errors.as_text }}
  {% else %}
        {{ UF.title }}
  {% endif %}

but instead of having UF.title in the first error, I would rather have UF.title but with the ERROR> how would I go about doing this?

而不是UF。在第一个错误中,我宁愿有UF。标题,但有错误>我该怎么做呢?

2 个解决方案

#1


1  

You should use django-bootstrap3. It does exactly what you want.

您应该使用django-bootstrap3。它做的正是你想要的。

{% load bootstrap3 %}

{# Display a form #}

<form action="/url/to/submit/" method="post" class="form">
    {% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
        <button type="submit" class="btn btn-primary">
            {% bootstrap_icon "star" %} Submit
        </button>
    {% endbuttons %}
</form>

#2


0  

Here's what I do for my code:

下面是我为我的代码所做的:

<div class="form-group {% if form.username.errors %}has-error{% endif %}">
  {{ form.username }}
  {% if form.username.errors %}
  <span class="help-block">{{ form.username.errors.0 }}</span>
  {% endif %}
</div>

And my forms.py looks like:

和我的形式。py看起来像:

from django import forms

class LoginForm(forms.Form):
    username = forms.CharField(label='Username', max_length=32, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'form-control'}))

#1


1  

You should use django-bootstrap3. It does exactly what you want.

您应该使用django-bootstrap3。它做的正是你想要的。

{% load bootstrap3 %}

{# Display a form #}

<form action="/url/to/submit/" method="post" class="form">
    {% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
        <button type="submit" class="btn btn-primary">
            {% bootstrap_icon "star" %} Submit
        </button>
    {% endbuttons %}
</form>

#2


0  

Here's what I do for my code:

下面是我为我的代码所做的:

<div class="form-group {% if form.username.errors %}has-error{% endif %}">
  {{ form.username }}
  {% if form.username.errors %}
  <span class="help-block">{{ form.username.errors.0 }}</span>
  {% endif %}
</div>

And my forms.py looks like:

和我的形式。py看起来像:

from django import forms

class LoginForm(forms.Form):
    username = forms.CharField(label='Username', max_length=32, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'form-control'}))