Reputation: 21
I created a model name song, and I made a form to upload song to the website. I was wondering how to save songs to a specific user, so I can query the database for all of the songs uploaded by a user
My models:
class Song(models.Model):
user=models.ForeignKey(User, null = True)
song_name = models.CharField(max_length = 100)
audio = models.FileField()
My View:
class SongCreate(CreateView):
model = Song
fields=['song_name','audio']
summary:
I can upload songs but i can't link them to a user
p.s I'm very new to django
Upvotes: 1
Views: 45
Reputation: 3326
You can use the form_valid
method of the CreateView
to assign the user to the song and then save it.
from django.shortcuts import redirect
from django.views.generic.edit import CreateView
class SongCreate(CreateView):
model = Song
fields=['song_name','audio']
def form_valid(self, form):
song = form.save(commit=False)
song.user = self.request.user
song.save()
return redirect(self.get_success_url())
Upvotes: 3