![](/img/trans.png)
[英]how to populate a CreateView field based on count of model instances in Django
[英]How to set model field automatically in CreateView? (Django)
class PetAddView(CreateView):
model = Pet
fields = ['name','animal_type','breed','color','age','height','price','city','sex','photo']
template_name = 'pets/pet-add.html'
這是我的創建視圖。
我的目標是為視圖提供在數據庫中創建記錄的功能。 Bu 我不需要我的用戶指定 slug 而是我需要從指定的“名稱”值自動設置它。
我可以嗎?
是的,你可以在form_valid
方法中做任何事情。 訣竅是
def form_valid( self, form):
instance = form.save( commit = False)
# define the slug and any other programmatically generated fields
instance.slug = whatever
instance.save()
return HttpResponseRedirect( self.get_success_url())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.