96
The form_valid()
method for CreateView
and UpdateView
saves the form, then redirects to the success url. It’s not possible to do return super()
, because you want to do stuff in between the object being saved and the redirect.
The first option is to not call super()
, and duplicate the two lines in your view. The advantage of this is that it’s very clear what is going on.
def form_valid(self, form):
self.object = form.save()
# do something with self.object
# remember the import: from django.http import HttpResponseRedirect
return HttpResponseRedirect(self.get_success_url())
The second option is to continue to call super()
, but don’t return the response until after you have updated the relationship. The advantage of this is that you are not duplicating the code in super()
, but the disadvantage is that it’s not as clear what’s going on, unless you are familiar with what super()
does.
def form_valid(self, form):
response = super(CourseCreate, self).form_valid(form)
# do something with self.object
return response
3
I would suggest to use Django’s Signal. That is an action that gets triggered when something happens to a Model, like save or update. This way your code stays clean (no business logic in the form-handling), and you are sure that it only gets triggered after save.
#views.py
from django.dispatch import receiver
...
@receiver(post_save, sender=Course)
def post_save_course_dosomething(sender,instance, **kwargs):
the_faculty = instance.faculty
#...etc
- [Django]-Django TemplateDoesNotExist?
- [Django]-Django migration strategy for renaming a model and relationship fields
- [Django]-Django models – how to filter number of ForeignKey objects
2
If you need to modify also the Course object when call save function use False and after change save the object
def form_valid(self, form):
self.object = form.save(False)
# make change at the object
self.object.save()
return HttpResponseRedirect(self.get_success_url())
- [Django]-Django returns 403 error when sending a POST request
- [Django]-Django: Populate user ID when saving a model
- [Django]-How do I get the class of a object within a Django template?
0
It is possible to do return super() as it is in the django doc:
https://docs.djangoproject.com/en/4.0/topics/class-based-views/generic-editing/
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
form.send_email()
return super().form_valid(form)
- [Django]-Using Django Rest Framework, how can I upload a file AND send a JSON payload?
- [Django]-How to change status of JsonResponse in Django
- [Django]-Django unit tests without a db