根据用户输入从django模型中选择对象



我有一个大约有800个对象的大型django模型,我想创建一个视图,用户可以在其中选择一定数量的对象传递到另一个视图进行进一步处理。模型中有这么多对象,这使得列出所有对象变得非常不现实,因为用户必须滚动浏览800个对象。

为了解决这个问题,我想在视图的顶部放置一个按需键入搜索栏,这样用户就可以键入对象的名称并通过单击来选择它们。当对象被选择时,它们应该作为标签出现在搜索栏下,用户可以通过点击";x〃;每个旁边。

当用户做出了所有必要的选择后,他们应该能够单击按钮并跳到下一个视图,在那里可以访问这些选定的对象。

我使用的模型可以简化为:

class Song():
song_name = models.CharField(max_length=256)
song_author = models.CharField(max_length=256, blank=True)
song_content = models.TextField()
def __str__(self):
return self.song_name

class Meta:
ordering = ['song_order']
song_order = models.PositiveIntegerField(editable=False, db_index=True)

到目前为止,我已经能够通过模型进行搜索。

mytemplate.html

<!DOCTYPE html>
{% load static %}
<html style="height: 100%;" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="preload" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons" as="style" onload="this.rel='stylesheet'">
<link rel="preload" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" as="style" onload="this.rel='stylesheet'">
<link rel="stylesheet" href="{% static 'css/main.css' %}">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
</head>
<body>

{% block body_block %}
<div class="container" style="padding-bottom:40px;margin-top: 35px;">   
<div class="form-group">
<label for="searchInput" class="bmd-label-floating">Search</label>
<input type="text" class="form-control" id="searchInput" oninput="filter()">
</div>
<ul class="list-group bmd-list-group-sm">
{% for song in songs %}
<div
class="list-group-item"
data-title="{{song.song_name}}"
data-author="{{song.song_author}}"
data-lyrics="{{song.song_content}}">
<h4>
{{song.song_name}}
{% if song.song_author %}
({{ song.song_author }})
{% endif %}
</h4>
</div>
{% endfor %}
</ul>
</div>
<script>
$('#searchInput').focus();
function short(s) {
let punctuationRegEx = /[.,/#!$%^&*;:{}=-_`~()]/g;
return s.replace(punctuationRegEx, '')
.toLowerCase()
.normalize("NFD")
.replace(/[u0300-u036f]/g, "");
}
function filter() {
let f = short($('#searchInput').val());
$('.list-group-item').each(function (index) {
if (short($(this).data('title') + "").includes(f) ||
short($(this).data('author') + "").includes(f)
) {
$(this).show();
} else {
$(this).hide();
}
});
}
</script>
{% endblock %}

</body>
</html>

视图.py

class SongListView(ListView):
context_object_name = 'songs'
model = Song
template_name = "songapp/mytemplate.html"

关于如何进行选择有什么想法吗?

我已经创建了一个带有随键入搜索的零件库存程序
这是ajax调用搜索和数据库的完整示例
您可以修改它以显示X搜索下的结果。

https://github.com/edcodes/Django-Parts-Inventory

最新更新