Modelform with reverse foreignkey

18 views
Skip to first unread message

Kiran

unread,
Sep 27, 2016, 7:27:43 AM9/27/16
to Django users

I am trying to create a ModelForm for movie Model from which it must be possible to select a number of theatre for each movie.Since theatre is reverse foreignkey i think ModelForm doesn't automatically  saves theatre values to the database.i tried to override the save method and ended up with the error.


Exception Type:ValueError
Exception Value:
save() prohibited to prevent data loss due to unsaved related object 'movie'.

Anyone please help me to solve this and thanks in advance.

class movieAdminForm(forms.ModelForm):

theatre = forms.ModelMultipleChoiceField(queryset=theatre.objects.all(),
widget=forms.widgets.CheckboxSelectMultiple())


class Meta:
model = movie
fields = ('image', 'image2', 'title', 'language', 'director', 'cast', 'y_tube_url',
'synopsis', 'like', 'music', 'cast',
'duration', 'genre', 'date', 'rating', 'writer','theatre')


def save(self,*args,**kwargs):
super(movieAdminForm,self).save(*args,**kwargs)
self.instance.theatre.clear()
for i in self.cleaned_data['theatre']:
self.instance.theatre.add(i)
Reply all
Reply to author
Forward
0 new messages