在JavaScript中使用django变量
我的模型:在JavaScript中使用django变量,javascript,django,Javascript,Django,我的模型: class Category(models.Model): category_name=models.CharField(max_length = 100) def __str__(self): return self.Category_name class Song(models.Model): category= models.ForeignKey(Category, on_delete=models.CASCADE
class Category(models.Model):
category_name=models.CharField(max_length = 100)
def __str__(self):
return self.Category_name
class Song(models.Model):
category= models.ForeignKey(Category, on_delete=models.CASCADE)
pass
{%load static%}
函数printSong(x){
var all={x.song_set.all};
document.getElementById(“main”);
var theme=[{%for song in all%}{{song.song_name}}{%endfor%}];
main.innerHTML=它们;
}
NSM
欢迎{{user.username}
{所有类别中歌曲的百分比%}
{%endfor%}
演奏
您的歌曲
{user.song\u set.all%中歌曲的百分比}
{%endfor%}
如果可以通过json显示歌曲,那么可以使用Ajax。有点像这样(我在看到您的代码之前将其放在一起,因此模型名称等不同,但作为示例):
从这里您可以访问作为json对象的歌曲列表 显示您的模型、当前模板和当前JavaScript代码,并描述哪些不起作用。问题是什么?如何在JavaScript中包含django变量
function getSongs(category) {
$.ajax({
url : "songs/", // links to a django view to get the songs
type : "POST",
data : { id }, // you could take the category id from the template eg {{ category.id }}
dataType : 'json',
success : function(songs) {
// an example of getting song titles
for (i = 0; i < songs.length; i++) {
song = songs[i]
title = song.title
// do something with the title here
}
}
})
}
from django.http import JsonResponse
from models import Category
def songs(request):
if request.method == 'POST':
category_id = request.POST.get('id')
category = Category.objects.get(id=category_id)
songs = category.songs.all()
jsonSongs = []
for song in songs:
jsonSong = {}
jsonSong["title"] = song.title
// title used here just to show how you might access aspects of the song model
jsonSongs.append(jsonSong)
return JsonResponse(songs, safe=False)