Monday, September 26, 2016

Modelform with reverse foreignkey


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)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/04b5656e-b994-4d5e-8288-0eb69ec7953f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment