英文:
What is a good way to filter a model and display that as a table in Django?
问题
I have been struggling on finding a simple method for displaying a filtered model on a Django webpage. I am using DataTables for my tables.
Here is some code for my view that filters a value and creates a serialized JSON. I am not sure of another method to do this, but intuitively it made sense to transform the filtered model and send it over to the webpage in the 'context' parameter.
def site(request, site_name):
filtered = Participant.objects.filter(site_name=site_name).all()
serialized = json.loads(serialize('json', filtered))
return render(request, 'site.html', context={'site': site_name, 'filtered': serialized})
Here's my JavaScript:
$(document).ready(function() {
$('#my-table').DataTable( {
data: JSON.parse(filteredData),
lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "All"]],
pageLength: 50,
responsive: true,
processing: true,
serverSide: false,
bSearchable: true,
columns: [
{"data": "some_data"},
],
} );
} );
And here's where I pass in the filteredData variable in my HTML:
<script>
filteredData = "{{filtered}}"
</script>
This does not work as I am not really sure how DataTables handles JSON files. I presume that the solution is simple, but I am quite new to Django. Thank you!
英文:
I have been struggling on finding a simple method for displaying a filtered model on a Django webpage. I am using DataTables for my tables.
Here is some code for my view that filters a value and creates a serialized json. I am not sure of another method to do this, but intuitively it made sense to transform the filtered model and send it over to the webpage in the 'context' parameter.
def site(request, site_name):
filtered = Participant.objects.filter(site_name=site_name).all()
serialized = json.loads(serialize('json', filtered))
return render(request, 'site.html', context={'site': site_name, 'filtered': serialized})
Here's my javascript:
$(document).ready(function() {
$('#my-table').DataTable( {
data: JSON.parse(filteredData),
lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "All"]],
pageLength: 50,
responsive: true,
processing: true,
serverSide: false,
bSearchable: true,
columns: [
{"data": "some_data"},
],
} );
} );
And here's where I pass the in the filteredData variable in my HTML:
<script>
filteredData = "{{filtered}}"
</script>
This does not work as I am not really sure how DataTables handles JSON files. I presume that the solution is simple, but I am quite new to Django. Thank you!
答案1
得分: 1
I was able to solve it! The serialized JSON that is generated from serializing a filtered model is not the correct format. I had to change my booleans to strings before I passed the JSON string to my site. I could have also changed the booleans to lowercase (e.g., False -> false) since JavaScript syntax is uncapitalized unlike Python.
def site(request, site_name):
site_pguids = Participant.objects.filter(site_name=site_name).all()
serialized = str(json.loads(serialize('json', site_pguids)))
serialized = serialized.replace("False", "'False'")
serialized = serialized.replace("True", "'True'")
return render(request, 'site.html', context={'site': site_name, 'filtered': serialized})
Then, in my JavaScript, I simply replaced the single quotes with double quotes and it worked.
data: JSON.parse(filteredData.replace(/'/g, '"')),
英文:
I was able to solve it! The serialized JSON that is generated from serializing a filtered model is not the correct format. I had to change my booleans to strings before I passed the JSON string to my site. I could have also changed the booleans to lowercase (e.g., False -> false) since JavaScript syntax is uncapitalized unlike Python.
def site(request, site_name):
site_pguids = Participant.objects.filter(site_name=site_name).all()
serialized = str(json.loads(serialize('json', site_pguids)))
serialized = serialized.replace("False", "'False'")
serialized = serialized.replace("True", "'True'")
return render(request, 'site.html', context={'site': site_name, 'filtered': serialized})
Then, in my JavaScript I simply replaced the single quotes with double quotes and it worked.
data: JSON.parse(filteredData.replace(/'/g, '"')),
答案2
得分: 0
以下是翻译好的部分:
JSON 数据
您的 JSON 字符串如下(基于另一个回答中的注释):
[{
"model": "participants.participant",
"pk": 5533,
"fields": {
"pGUID": "somedata",
"site_name": "somedata",
"fb_email": "somedata",
"is_authorized": false
}
}]
请注意使用的是双引号而不是单引号。请注意使用 false
而不是 False
。
JavaScript 部分
如果您将其写成字符串,您需要得到以下 JavaScript:
var filteredData = '[{"model": "participants.participant","pk": 5533,"fields": {"pGUID": "somedata","site_name": "somedata","fb_email": "somedata","is_authorized": false}}]';
请注意整个字符串都用单引号括起来,以不干扰 JSON 本身内部的双引号。
因此,您需要确保您的 JavaScript 占位符如下:
filteredData = '{{filtered}}';
我无法评论您在 Django 应用程序中创建 {{filtered}}
字符串的最佳方法。抱歉,我不使用 Django。
演示
但是,一旦您将该字符串正确传递到您的网页,然后您可以按如下方式使用它。在以下演示中,我只是硬编码了字符串,而不是使用 {{filtered}}
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
/*
what the json should look like:
[{
"model": "participants.participant",
"pk": 5533,
"fields": {
"pGUID": "somedata",
"site_name": "somedata",
"fb_email": "somedata",
"is_authorized": false
}
}]
// your JSON as a string, provided by Django:
var filteredData = '[{"model": "participants.participant","pk": 5533,"fields": {"pGUID": "somedata","site_name": "somedata","fb_email": "somedata","is_authorized": false}}]';
$(document).ready(function() {
$('#my-table').DataTable({
data: JSON.parse(filteredData),
lengthMenu: [
[25, 50, 100, -1],
[25, 50, 100, "All"]
],
pageLength: 50,
responsive: true,
processing: true,
serverSide: false,
searchable: true,
columns: [{
data: "model",
title: "Model"
},
{
data: "fields.pGUID",
title: "GUID"
},
{
data: "fields.is_authorized",
title: "Authorized?"
}
],
});
});
<!-- language: lang-html -->
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="my-table" class="display dataTable cell-border" style="width:100%;">
</table>
</div>
</body>
</html>
<!-- end snippet -->
在上面的代码中,您可以看到如何引用 JSON 中的不同字段:
data: "model"
data: "fields.pGUID"
data: "fields.is_authorized"
...等等。
我还添加了 title
选项,以为您的表格添加一些标题。
另一种方法
我更喜欢的方法是在 Django 中有一个端点,该端点提供正确的 JSON(而不是字符串)并直接使用Ajax 数据源将其提供给 DataTable。
但是,考虑到您的起点,这可能需要更多的工作。
您的方法当然没有问题 - 这是个人偏好的问题。因此,也许先让您当前的方法运行起来,然后再决定是否要尝试不同的方法。
英文:
Given your starting point, the least amount of work for you is probably as follows:
The JSON Data
Your JSON string is as follows (based on a comment in another answer):
"[{'model': 'participants.participant', 'pk': 5533, 'fields': {'pGUID': 'somedata', 'site_name': 'somedata', 'fb_email': 'somedata', 'is_authorized': False}}]"
But that is not a string containing valid JSON.
Valid JSON would be this:
[{
"model": "participants.participant",
"pk": 5533,
"fields": {
"pGUID": "somedata",
"site_name": "somedata",
"fb_email": "somedata",
"is_authorized": false
}
}]
Note the use of double-quotes - not single quotes. Note the use of false
not False
.
The JavaScript
If you write this as a string, you need to end up with the following JavaScript:
var filteredData = '[{"model": "participants.participant","pk": 5533,"fields": {"pGUID": "somedata","site_name": "somedata","fb_email": "somedata","is_authorized": false}}]'
Note that the entire string is enclosed in single quotes, so as to not interfere with the double-quotes inside the JSON itself.
You therefore need to ensure your JavaScript placeholder is this:
filteredData = '{{filtered}}';
I can't comment on the best way for you to create that {{filtered}}
string in your Django app. Sorry, I don't use Django.
A Demo
But once you have that string correctly passed to your web page, then you can use it as follows. In the following demo, I have just hard coded the string, instead of using {{filtered}}
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
/*
what the json should look like:
[{
"model": "participants.participant",
"pk": 5533,
"fields": {
"pGUID": "somedata",
"site_name": "somedata",
"fb_email": "somedata",
"is_authorized": false
}
}]
*/
// your JSON as a string, provided by Django:
var filteredData = '[{"model": "participants.participant","pk": 5533,"fields": {"pGUID": "somedata","site_name": "somedata","fb_email": "somedata","is_authorized": false}}]';
$(document).ready(function() {
$('#my-table').DataTable({
data: JSON.parse(filteredData),
lengthMenu: [
[25, 50, 100, -1],
[25, 50, 100, "All"]
],
pageLength: 50,
responsive: true,
processing: true,
serverSide: false,
searchable: true,
columns: [{
data: "model",
title: "Model"
},
{
data: "fields.pGUID",
title: "GUID"
},
{
data: "fields.is_authorized",
title: "Authorized?"
}
],
});
});
<!-- language: lang-html -->
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="my-table" class="display dataTable cell-border" style="width:100%">
</table>
</div>
</body>
</html>
<!-- end snippet -->
In the above code, you can see how to refer to the different fields in your JSON:
data: "model"
data: "fields.pGUID"
data: "fields.is_authorized"
...and so on.
I added the title
options as well, to give your table some headers.
An Alternative
I would prefer the approach where you have a Django endpoint which serves the correct JSON (as JSON, not as a string) and provides that directly to the DataTable using an Ajax data source.
But that is probably more work, given your starting point.
There is certainly nothing wrong with your approach - it's a matter of preference. So, maybe get your current approach working first, and then decide if you want to try a different approach, after that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论