我在Django中有一个应用程序,该数据库中存储了2条新闻。我正在使用views.py以便在我的html页面中显示这些新闻。
Models.py
class News(models.Model):
news_title = models.CharField(max_length=150)
news_body = models.TextField(max_length=1500)
Views.py
def news(request):
news_f = News.objects.all().order_by('-news_id')
news_f_html = serializers.serialize("json",News.objects.all())
news_dic= {'news_f':news_f,'ac_tab_n':'ac_tab', 'news_f_html':news_f_html}
return render(request, 'news.html',news_dic)
我想使用html标签显示新闻正文,但我不能,因为它是一个字符串。我一直在阅读,并且尝试对新闻进行序列化,以便在JavaScript中使用news_f_html。
scripts.js
var news = "{{ news_f_html }}";
但是这不起作用。我无法显示,例如:
console.log(news[1].news_title) //Note that I have 2 news in my db app
静态文件(js,css)对页面上下文一无所知。您需要将该上下文明确传递给您的js代码。render
函数返回render
,默认情况下为纯文本,并且仅适用于模板。就是这样,Django仅将数据传递给HttpResponse模板(以及像news.html
这样传递到其中调用的模板),但不是静态文件。如果要将数据传递到js文件,请让视图返回{% include "template.html"%}
,然后让js代码通过url提取数据。由于您刚刚开始使用Django,因此请尝试以类似方式进行操作:
在您的JsonResponse模板中写这些行(这是初始化变量的方式):
news.html
并且在这些行之后,使用将处理上下文的代码导入js文件。就是这样,js代码从模板中获取了这些变量,并且已经可以使用它们。
{# news.html #}
...
<script>
var news = {{ news_f_html }}; // note that this assignment without quotes - "{{ news_f_html }}" will be just string variable
</script>
...
由于您已经在使用序列化程序(我认为这是DRF,请参阅更新),因此将来请查看{# news.html #}
...
<script>
var news = {{ news_f_html }}; // note that this assignment without quotes - "{{ news_f_html }}" will be just string variable
</script>
...
<script src="{% static 'path/to/your/js/code.js' %}"></script>
以创建API。
更新:
所以您正在使用Django Rest Framework views。
在这种情况下,为了获得所需的结果,您需要更改视图,例如,如下所示:
Django's core serializers