Reputation: 95
I have the following model:
class Survey(models.Model):
is_published = models.BooleanField()
which is set to "False" as the default.
I am using modelForm to add this into a form. When I call the save() method on the form, I want to change "False" to "True" and save this to the db. How do I do that?
I've read through https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/ and it doesn't explain how this would work.
Upvotes: 1
Views: 5715
Reputation: 345
Under your model you can define the save method:
def save(self, *args, **kwargs):
...
self.is_published = True
...
super(Survey, self).save(*args, **kwargs)
However the implication of this is that everytime you save the instance of your model the field will be changed!
if you want to change it only when the instance is created you can add this check:
if not self.pk:
self.is_published = True
Upvotes: 1
Reputation: 599590
You do this in the view.
if form.is_valid()
obj = form.save(commit=False)
obj.is_published = True
obj.save()
return redirect('wherever')
Upvotes: 6