1👍
This is how saving with commit=False
works, as mentioned in the documentation:
Another side effect of using commit=False is seen when your model has a many-to-many relation with another model. If your model has a many-to-many relation and you specify commit=False when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn’t possible to save many-to-many data for an instance until the instance exists in the database.
To work around this problem, every time you save a form using commit=False, Django adds a save_m2m() method to your ModelForm subclass. After you’ve manually saved the instance produced by the form, you can invoke save_m2m() to save the many-to-many form data.
The solution is to call form.save_m2m()
, which is a method that is added to your form instance when the form’s save
method is called with commit=False
.
def form_valid(self, form):
self.object = form.save(commit=False)
if self.request.user.is_authenticated():
self.object.trainee = Trainee.objects.get(username=self.request.user)
self.object.save()
form.save_m2m()
return super(LearningObjectiveView, self).form_valid(form)
0👍
The code here seems a bit incorrect, few updates that could help you trace the issue are:
- In your CreateModel view define: form_class = LearningObjectiveForm, model = LearningObjective
- Use form as mentioned here https://docs.djangoproject.com/en/1.7/topics/forms/#rendering-fields-manually in your template
- Again remove super call from the form_valid method of CreateModel View as this will call form.save() again(might create a duplicate object here)
- I am not sure if I see the relevance of RetrieveLearningObjective View.