Reputation: 660
I have a CreateSong CBV in Django that allows me to create song objects to a model. My question is, in the form I created for the view, how do I make the album column to be auto-populated with albums the user-created only? I get errors calling "self" that way.
See my views below
class CreateSong(CreateView):
model = Song
fields = [album, song_title]
fields['album'].queryset = Album.objects.filter(owner=self.request.user)
Upvotes: 0
Views: 61
Reputation: 996
You do not have access to self.request.user
, because you are calling it at class level, thus when the class is being defined and not when the view is actually called. Instead you should override the get_form
method as in Davit's answer.
Upvotes: 0
Reputation: 3588
I think you should override get_form
. See the example below:
class CreateSong(CreateView):
model = Song
fields = [album, song_title]
def get_form(self):
form = super().get_form()
form.fields['album'].queryset = Album.objects.filter(owner=self.request.user)
return form
Upvotes: 1