0

From my views:

class SongCreate(CreateView):
    model = Song
    fields = ['album', 'name']

My functionality of adding a song (this) to an album is inside the details template of an album A. However, I want the input only be the name and not the album anymore since the song's album should automatically be "A." How do I make the code above behave such?

From my urls:

url(r'album/(?P<pk>[0-9]+)/song/add/$', views.SongCreate.as_view(), name='song-add') 
JM Lontoc
  • 211
  • 4
  • 15

1 Answers1

0

You can use the get_initial method:

class SongCreate(CreateView):
    model = Song
    fields = ['album', 'name']

    def get_initial(self):
        return {
            'album': Album.objects.get(id=self.kwargs.get('pk')),
        }

Or you can use the form_valid method:

class SongCreate(CreateView):
    model = Song
    fields = ['name']

    def form_valid(self, form):
        form.instance.album = Album.objects.get(id=self.kwargs.get('pk'))
        return super(SongCreate, self).form_valid(form)
Anton Shurashov
  • 1,820
  • 1
  • 26
  • 39