[英]How to use Django's models in JavaScript
我在 Django 中有一个应用程序,数据库中有 2 个新闻。 我使用views.py 来在我的html 页面中显示这些新闻。
模型.py
class News(models.Model):
news_title = models.CharField(max_length=150)
news_body = models.TextField(max_length=1500)
视图.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。
脚本.js
var news = "{{ news_f_html }}";
但这不起作用。 我无法显示,例如:
console.log(news[1].news_title) //Note that I have 2 news in my db app
Static 文件(js、css)对页面的上下文一无所知。 您需要将此上下文显式传递给您的 js 代码。 render
function 返回一个HttpResponse ,默认为纯文本,仅适用于模板。 就是这样,Django 只将数据传递给news.html
模板(以及像这样{% include "template.html"%}
在其中调用的模板),但不是 ZA81259CEF8E959C3224DF1D456E 文件如果您想将数据传递给 js 文件,则让您的视图返回JsonResponse ,并让您的 js 代码通过 url 获取数据。 由于您刚刚在 Django 开始您的旅程,因此请尝试以类似方式进行操作:
在你的news.html
模板中写下这些行(这是你初始化变量的方式):
{# news.html #}
...
<script>
var news = {{ news_f_html }}; // note that this assignment without quotes - "{{ news_f_html }}" will be just string variable
</script>
...
在这些行之后,使用将处理您的上下文的代码导入您的 js 文件。 就是这样,js-code 从模板中获取了这些变量,并且已经可以使用它们了。
{# news.html #}
...
<script>
var news = {{ news_f_html|safe }}; // 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>
由于您已经在使用序列化程序(我认为这是 DRF ,请参阅更新),因此将来请查看Django Rest 框架视图以创建 API。
更新:
因此,您正在使用Django 的核心序列化程序。
在这种情况下,为了获得所需的结果,您需要更改视图,例如,如下所示:
def news(request):
news_f = News.objects.all().order_by('-news_id')
news_f_html = []
for instance in News.objects.all(): # it's not serialization, but extracting of the useful fields
news_f_html.append({'pk': instance.pk, 'title': instance.news_title, 'body': instance.news_body})
news_dic = {'news_f': news_f, 'ac_tab_n': 'ac_tab', 'news_f_html': news_f_html}
return render(request, 'news.html', news_dic)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.