[英]Django Error Styling with Twitter Bootstrap
我正在嘗試在Django項目中使用twitter bootstrap設置樣式錯誤。 現在,我有一個簡單的表單,該表單詢問一個人的電子郵件地址,讓他們按下一個按鈕,然后將其提交到數據庫。 它還具有驗證檢查功能,以查看電子郵件在數據庫中是否唯一。 如果不是唯一的,則會引發錯誤消息“此電子郵件已被注冊”。 但是,如果出現錯誤,對於重復的電子郵件,它將在輸入字段旁邊顯示一個丑陋的項目符號列表,其文本為“ This email is already registered
。 我正在嘗試將其樣式設置為在輸入文本下帶有黃色i
圖標的小對話框,就像輸入不包含@
符號(即不是電子郵件)時一樣。 當電子郵件中未包含有效域時(例如未附加.com
,也會出現難看的要點。
我認為問題在於表單html的設置方式,或者視圖如何處理表單錯誤。 可能是因為表單字段是EmailField,所以is_valid
指示符無效,因此顯示了twitter bootstrap警報。
如何獲得每次顯示警報的信息? 下面是我的代碼:
構成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)
表格
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
您可能想嘗試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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.