0

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})
4
  • Giving data from your DB to your frontend can be achieved in many ways. You can add context variables in your views or you can fetch them via Rest framework and Ajax. If you want the path in your music_upload.html you could music_paths=Music .objects.all() and then add music_paths to 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 Commented Feb 17, 2021 at 15:32
  • will {{music_paths}} work in the Javascript code of the music player ? Commented Feb 17, 2021 at 15:36
  • The best thing in the beginning is just trying stuff out and googling. If you use {{music_paths}} in your js it will likely throw an error. You can google this error and then will find something like this stackoverflow.com/questions/24647307/… you will try it out and search for the next solution. Please don't hope for "here is everything you need solutions" if you want to make it in programming a little "hands on mentality" won't hurt Commented Feb 17, 2021 at 15:41
  • One Trick must be to put {{music_paths}} value into a global variable in the html page inside a <script></script> and then access it from your js code Commented Feb 17, 2021 at 17:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.