- choice 選項問題
例如在 model 中定義的是choices = ((1, 'xx'), (2, 'sdf'), (3, 'zzz'))
那么在模板中顯示xx,sdf,zzz怎么顯示呢?不能直接.<field>,這樣會直接顯示1 2 3 這些值,那么可以使用 get_字段_display 來顯示。 - form 中字段驗證問題
def clean(self):
password = self.cleaned_data.get('password ')
re_password = self.cleaned_data.get('re_password ')
if re_password and re_password != password:
self.add_error('re_password', ValidationError("兩次密碼不一致"))
else:
return self.clean_data
注意:全局驗證的時候需要返回
self.cleaned_data,局部例如def clean_username時候需要返回字段的名稱。
- 關(guān)于時間分組問題
當(dāng)需要對時間進(jìn)行分組時
ret = models.xxx.objects.all.extra(
select={“x”: “date_format(create_time, '%%Y-%%m')”}
).values('c').annotate(x=Count('id')).values('c', 'x')
- 關(guān)于文本輸入框中 xss 攻擊問題
做字符串截取的時候,需要利用到bs4模塊
from bs4 import BeautifulSoup as bs
html = bs(content, 'lxml')
desc = html.text[0:150]
過濾非法標(biāo)簽
for tag in html.find_all():
if tag.name in ['script', 'link']:
# 刪除此標(biāo)簽
tag.decompose()
# 或者可以使用 replace_with() 替代
- form select 選擇問題
# 靜態(tài)字段
user_type=fields.ChoiceField(
choices=[(1,"普通用戶"),(2,"超級用戶")],
widget=widgets.Select,
)
# 數(shù)據(jù)庫中取字段,但是數(shù)據(jù)庫更改后不會同步
user_type=fields.ChoiceField(
choices=models.UserType.objects.all().values_list("id","name"),#要返回元組列表
widget=widgets.Select,
)
# 同步數(shù)據(jù)庫,重新寫 __init__ 方法
在 form 中
user_type=fields.ChoiceField(
choices=models.UserType.objects.all().values_list("id","name"),
widget=widgets.Select,
)
def __init__(self,*args,**kwargs):
super(UserInfoForm,self).__init__(*args,**kwargs)
self.fields["user_type"].choices=models.UserType.objects.all().values_list("id","name")
- 過期 session
Django 對于過期的 session 并不會自動清除,所以需要手動清除,可以設(shè)置一個定時任務(wù)。
命令:python manage.py clearsessions