我正在尝试在Django项目中使用twitter bootstrap设置错误样式。现在,我有一个简单的表单,该表单询问一个人的电子邮件地址,让他们按下一个按钮,然后将其提交到数据库。它还具有验证检查功能,以查看电子邮件在数据库中是否唯一。如果不是唯一的,则会引发错误消息“此电子邮件已被注册”。但是,如果出现错误,则对于重复的电子邮件,它将在输入字段旁边显示一个丑陋的项目符号列表,并显示文本This email is already registered
。我正在尝试将其设置为在输入文本下方带有黄色i
图标的小对话框显示的样式,例如在输入中不包含@
符号(即不包含)的情况下一封电邮。当电子邮件中未包含有效域时(例如,没有附加.com
。
我认为问题在于表单html的设置方式,或者视图如何处理表单错误。也许是因为表单字段是EmailField,所以is_valid
指示器无效,因此显示了Twitter引导警报。
如何获取它以每次显示警报?下面是我的代码:
属于index.html的一部分
<form class="form-inline" method="post">
<div class="input-group input-group-newsletter">
<div class="form-group">
{% csrf_token %}
{{ form }}
</div>
<div class="form-group">
<div class="input-group-append">
<button class="btn btn-secondary" type="submit">Button Text</button>
</div>
</div>
</div>
</form>
views.py
from django.shortcuts import render, HttpResponse
from django.views.generic import TemplateView
from appname.forms import AppForm
class AppView(TemplateView):
template_name = 'apps/index.html'
def get(self, request):
form = AppForm()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = AppForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
form.save()
form = AppForm()
args = {'form': form, 'email': email, 'signedup': True}
else:
args = {'form': form, 'signedup': False}
return render(request, self.template_name, args)
forms.py
from django import forms
from .models import AppModel
class AppForm(forms.ModelForm):
email = forms.EmailField(required=True,
label='',
widget=forms.EmailInput(attrs={'class': 'form-control',
'placeholder': 'Enter email...',
'name': 'email',
'aria-label': 'Enter email...',
'aria-describedby': 'basic-addon'}))
class Meta:
model = AppModel
fields = ('email',)
def clean_email(self, *args, **kwargs):
email = self.cleaned_data.get("email")
if AppModel.objects.filter(email__iexact=email).exists():
raise forms.ValidationError("This email is already registered.")
return email
答案 0 :(得分:-1)
您可能想尝试Django消息框架。这个站点显示了它是如何完成的。我自己尝试了一下,并且工作正常,尽管我没有尝试将图标放入其中。
https://simpleisbetterthancomplex.com/tips/2016/09/06/django-tip-14-messages-framework.html
根据以下评论进行更新:
这是我的项目中的片段
在 settings.py
中from django.contrib.messages import constants as messages
...
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
messages.html 模板,该模板可以包含在您希望收到通知的任何模板中
{% if messages %}
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible " role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message }}
</div>
{% endfor %}
{% endif %}
log-in.html 模板
<body>
{% include 'trip_monitor/messages.html' %}
<div class="login-form">
<form method="post">
{% csrf_token %}
<h2 class="text-center">Materials Management</h2>
<p align="center">Please <strong>log in</strong> to continue.</p>
<div class="form-group">
<input name="username" type="text" class="form-control" placeholder="Username" required="required" autofocus>
</div>
<div class="form-group">
<input name="password" type="password" class="form-control" placeholder="Password" required="required" id="password">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Log in</button>
</div>
</form>
</div>
</body>
views.py
from django.contrib import messages
def login(request):
if request.method == 'POST':
_username = request.POST['username']
_password = request.POST['password']
user = authenticate(request, username=_username, password=_password)
if user is not None:
auth_login(request, user)
return redirect('/trip/')
else:
messages.error(request, 'Username or Password is incorrect!') # this will be shown as pop-up message
return render(request, 'trip_monitor/login.html')
elif request.method == 'GET':
if request.user.is_authenticated:
return redirect('/trip/')
else:
return render(request, 'trip_monitor/login.html')