How can I extract data from my django model and put it into a javascript variable. I have a music player that uses javascript, within the JS code there is a variable 'trackUrl' which is a list of the track paths. How can i use my music model to extract the track and place into this JS code ? I've been trying to find a solution but was only advised to use Django REST framework, is there another method I could use. Could you please explain in detail as I'm still learning Django. Thanks
This is the music player : https://codepen.io/himalayasingh/pen/QZKqOX
models.py
class Music(models.Model):
track = models.FileField(upload_to='path/to/audio')
title = models.TextField(max_length=50)
artwork = models.ImageField(upload_to='path/to/img', blank=True)
artist = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
views.py
@login_required
def music_upload(request):
if request.method == "POST":
form = MusicForm(request.POST, request.FILES)
if form.is_valid():
user = request.user
song = form.save(commit=False)
song.artist = user
song.save()
messages.success(request, f'Track Uploaded')
return redirect('my_profile')
else:
form = MusicForm()
return render(request, 'feed/music_upload.html', {'form':form})
music_paths=Music .objects.all()and then addmusic_pathsto your context like you did with({'form':form, 'music_paths': music_paths}in your template you can now call {{music_paths}}. or use a for loop to get each one individually