Django小知识备忘录
项目路由转发和模块路由配置
# 项目路由转发
# blog/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
# 新增代码, 配置app的url
path('article/', include('article.urls', namespace='article')),
# 这里的namespace对应模块urls.py中的app_name
]
# 模块路由配置
article/urls.py
from django.urls import path
from article import views
app_name = 'article'
urlpatterns = [
# article 的url路由配置.
path('list/', views.article_list, name='article_list'), # article 列表
]
表单验证器
class UserRegisterForm(forms.ModelForm):
password = forms.CharField()
password2 = forms.CharField()
class Meta:
model = User
fields = ('username', 'email')
def clean_password2(self):
data = self.cleaned_data
if data.get('password') == data.get('password2'):
return data.get('password')
else:
return forms.ValidationError('密码输入不一致, 请重试.')
- clean_xxx 用于验证数据参数, 类似flask的validate_xxx
- 覆盖的字段不用在Meta中写出