Django if field = blank, set field = 1?
Can I use conditional statements in my either my models.py or admin.py file to do the following?:
if field (trying to be saved) == blank, set field = 1.
Thanks for the help. Please ask me to c开发者_如何转开发larify if need be.
You would want to override the save method on your model.
def save(self, *args, **kwargs):
# this is your model "trying" to be saved, before the "real"
# save is called by super below
if self.field == 'blank':
self.field = 1
super(MyModel, self).save(*args, **kwargs)
http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods
If you wanted to do it in your admin.py (so admin specific behavior, not global model behavior), you would want to override save_model
on your ModelAdmin
# code mostly from docs
class ArticleAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if obj.field == 'blank':
obj.field = 1
obj.save()
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model
精彩评论