如何自定义Django验证消息的样式

tjjdgumg  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(116)

我有一个Django项目,它有一个联系我们的表单。我想改变样式的错误,如“此字段是必需的”从UL风格引导警报风格。请帮帮我...
我只能改变错误的信息,但我也想改变那些错误的风格。

sg2wtvxw

sg2wtvxw1#

好吧,我找到一个方法
在forms.py:

from django.forms.utils import ErrorList

class Bootstrap(ErrorList):
    def __str__(self):
        if not self: return ''
        return ''.join([f'<div class="alert alert-danger" role="alert">{error}</div>' for error in self])

在views.py中:

MyForm(request.POST, error_class=BootstrapErrorList)
im9ewurl

im9ewurl2#

你可以自定义django**ModelForm**的错误,风格如下.

form.py

class ProductForm(forms.ModelForm):
    class Meta:
        model = Products
        fields = '__all__'
        widgets = {
            'category':  forms.Select(attrs={'class': 'form-select'}),
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'price': forms.NumberInput(attrs={'class': 'form-control'}),
        }
        error_messages = {
            'category':{'required':'Select category'},
            'name':{'required':'Enter product name'},
            }

views.py

def HomePageView(request):
    form = ProductForm()
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            return redirect('/home/')
        
    context = {'form': form}
    return render(request, 'index.html', context)

html

<div class="container position-absolute top-0 end-0 mt-5">
  <div class="row ">
    <div class="col-lg-5 p-3 border">
      <form action="" method="POST" novalidate>
        {% csrf_token %}

        {% for i in form %}

        <div class="mb-3">
          <label class="form-label">{{i.label_tag}}</label>
          {{i}} <span class="text-danger">{{i.errors|striptags}}</span>
        </div>
        {% endfor %}
        <button class="btn btn-primary" type="submit">Submit</button>
      </form>
    </div>
  </div>
</div>

浏览器输出

相关问题