添加admin应用
注册模型至admin
为模型字段添加自定义验证
提交代码到远程仓库的feature-catalog分支
------------------
实现
新建forms.py 用于验证模型的字段验证
from django import forms
from .models import Product
class ProductAdminForm(forms.ModelForm):
class Meta:
model = Product
exclude = []
# 验证属性price
def clean_price(self):
if self.cleaned_data['price'] <= 0:
raise forms.ValidationError('价格必须大于0.')
return self.cleaned_data['price']
注册模型 注意使用了装饰器
from django.contrib import admin
from .models import *
from .forms import ProductAdminForm
# Register your models here.
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm
list_display = ['name', 'price', 'old_price', 'created_at', 'updated_at']
list_display_links = ['name']
list_per_page = 30
ordering = ['-created_at']
search_fields = ['name', 'description', 'meta_keywords', 'meta_description']
exclude = ['created_at', 'updated_at']
prepopulated_fields = {'slug': ('name',)}
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'created_at', 'updated_at']
list_display_links = ['name']
list_per_page = 30
ordering = ['name']
search_fields = ['name', 'description', 'meta_keywords', 'meta_description']
exclude = ['created_at', 'updated_at']
prepopulated_fields = {'slug': ('name',)}#自动用name填充slug字段,但仅限英文时可用
git 操作
在代码目录下
git add .
查看状态
git status
确认
git commit -m 'register model to admin and check field'
git push origin featrue-catalog
origin 代表远程仓库