My model has quite a few boolean fields. I've broken these up into 3 sets which I'm rendering as a MultipleChoiceField
w/ a modified CheckboxSelectMultiple
.
Now I need to save this data back to the DB. i.e., I need to split the data returned by a single widget into multiple boolean columns. I think this is appropriate for the save()
method, no?
Question is, how do I do I do it? Something like this?
def save(self, commit=True): # code here return super(MyForm, self).save(commit)
If so... how do I set the values?
self.fields['my_field'].value = 'my_flag' in self.cleaned_data['multi_choice']
Or something? Where's all the data stored?
You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form. https://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin.
save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically. Let us try to create an instance with “Gfg is the best website”.
Saving changes to objectsTo save changes to an object that's already in the database, use save() . This performs an UPDATE SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() .
- The Web Dev How to override the save method in the Python Django ModelForm? To override the save method in the Python Django ModelForm, we add the save method into our model form class.
Overriding the save method – Django Models. The save method is an inherited method from models.Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save () function is run.
Overwriting data can be done in a number of places in the Django project. It can be done in models.py, admin.py, or views.py. In this article, we show how to overwrite form data in the views.py file, which is probably the most dynamic place to do, because you have to access to every type of variable, including the request object.
Technically it is not recommended to override the save method to implement such functionalities because any error in save method lets to crash of whole database. So either if you are perfect at writing save method and error handling or don’t try save method and try to implement these functionalities either in forms, views, models, etc.
The place you want your data to be stored is your new model instance:
def save(self, commit=True): instance = super(MyForm, self).save(commit=False) instance.flag1 = 'flag1' in self.cleaned_data['multi_choice'] # etc if commit: instance.save() return instance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With