gpt4 book ai didi

django - 如何限制 django ModelAdmin.autocomplete_fields 中自动完成搜索结果的外键对象?

转载 作者:行者123 更新时间:2023-12-02 07:24:08 26 4
gpt4 key购买 nike

关注此answer ,我能够过滤外键选项来选择:

enter image description here

但是当我将 spm 标记为 autocomplete_field:autocomplete_fields = ['spm'] 时,spm 字段从选择字段变为自动完成搜索字段: enter image description here

但外键选择不再受“formfield_for_foreignkey”中配置的限制。

即使我在 formfield_for_foreignkey 方法中附加小部件,spm 自动完成选项也会受到限制:

@admin.register(CustomModel)
class CustomModelAdmin(admin.ModelAdmin):

#autocomplete_fields = ['spm']
search_fields = ['name']

def get_form(self, request, obj=None, **kwargs):
request.current_object = obj
return super(CustomModelAdmin, self).get_form(request, obj, **kwargs)

def formfield_for_foreignkey(self, db_field, request, **kwargs):

if db_field.name == 'spm':
instance = request.current_object
if instance.brand and instance.memory_size:
filtered_qs=StandardProductWithMemorySize.objects.filter(
product__brand=instance.brand,
memory_size=instance.memory_size
)
kwargs['queryset'] = filtered_qs
db = kwargs.get('using')
kwargs['widget'] = AutocompleteSelect(db_field.remote_field, self.admin_site)
return super(
CustomModelAdmin, self
).formfield_for_foreignkey(db_field, request, **kwargs)

最佳答案

不使用 autocomplete_fields = ['spm'],而是重写 change_form.html 模板并使用 JavaScript 使 HTML 选择元素可搜索(具有自动完成功能)我:

enter image description here

change_form.html的内容:

{% extends 'admin/change_form.html' %}

{% block admin_change_form_document_ready %}
{{ block.super }}
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<script type="text/javascript">
$("#id_spm").select2({});
</script>

{% endblock %}

select2 函数操作的 HTML 选择元素:

<select name="spm" required="" id="id_spm" >
<option value="" selected="">---------</option>
<option value="67688">apple iphone 7</option>
<option value="69093">apple iphone 7 plus</option>
<option value="71453">apple ipad pro</option>
<option value="71076">apple ipad pro 9.7</option>
<option value="34840">apple ipad pro 10.5</option>
<option value="72303">apple iphone 8 plus</option>
<option value="72301">apple iphone 8</option>
<option value="72307">apple iphone x</option>
<option value="71243">apple ipad pro 12.9</option>
</select>

关于django - 如何限制 django ModelAdmin.autocomplete_fields 中自动完成搜索结果的外键对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48606101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com