[英]How to get, change or clear a django-autocomplete-light field value with javascript
[英]Django-autocomplete-light how to get data from html?
我不知道如何从HTML元素中获取数据,其中包含由django-autocomplete-light生成的数据。 这是形式的代码:
class ThreadForm(forms.Form):
topic = forms.CharField(label="Topic", max_length=255)
body = forms.CharField(label="Body", widget=forms.Textarea(attrs={'rows': '12', 'cols':'100'}))
tags = autocomplete_light.fields.MultipleChoiceField(choices=(tuple((tag.name, tag.name) for tag in Tag.objects.all())),
label='Tags',
widget=autocomplete_light.widgets.MultipleChoiceWidget('TagAutocomplete',
attrs={'class':'form-control',
'placeholder':'Tag'}
)
)
def save(self, author, created):
topic = self.cleaned_data['topic']
body = self.cleaned_data['body']
tags = self.cleaned_data['tags']
th = Thread(author = author,
topic = topic,
body = body,
created = created,
)
rtags = []
for tag in tags:
sr = Tag.objects.get(tag)
rtags.append(sr.name)
th.save()
Tag.objects.update_tags(th, tags)
和autocomplete_light_registry.py:
from threads.models import Thread
import autocomplete_light
from tagging.models import Tag
class TagAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['^name']
autocomplete_light.register(Tag, TagAutocomplete, attrs={
'data-autocomplete-minimum-characters': 1,
},)
如您所见,我已经更改了django-autocomplete应用程序。 在base.py中,我发现了一个变量choice_html_format = '<span data-value="%s" name="choice">%s</span>'
。我添加了属性name
以获取类似的数据:
tags = request.POST.get('name')
但这是行不通的。 我收到类似"NoneType in not callable"
类的错误"NoneType in not callable"
我尝试尝试的choice_html
件事是从base.py
更改choice_html
:
def choice_html(self, choice):
"""
Format a choice using :py:attr:`choice_html_format`.
"""
return self.choice_html_format % (
escape(self.choice_value(choice)),
escape(self.choice_label(choice)))
这是原始功能,我已经将choice_value(choice)
更改为choice_label(choice)
。 并得到一个错误"invalid literal for int() with base 10: <tag_name_here>"
。 看起来data-value
属性仅适用于int()类型(但是我不知道可以在哪里更改它,也许在js函数中,我不知道)。
最后,我试图获取每个标签的pk,然后通过管理器获取名称。 但是我遇到错误Cannot resolve keyword '4' into field. Choices are: id, items, name
Cannot resolve keyword '4' into field. Choices are: id, items, name
。
我绝对确定,有一种简单的方法可以执行我需要的任务。
autocomplete-light具有在模板中呈现的名为widget.html
的模板:
...
{% block select %}
{# a hidden select, that contains the actual selected values #}
<select style="display:none" class="value-select" name="{{ name }}" id="{{ widget.html_id }}" multiple="multiple">
{% for value in values %}
<option value="{{ value|unlocalize }}" selected="selected">{{ value }}</option>
{% endfor %}
</select>
{% endblock %}
...
如您所见,此<select>
元素包含自动完成小部件的所有选定选项。
它的名称(我们将在后面的视图中通过其name属性来标识它)只是自动完成的名称(“标签”)。
因此,现在您需要确保模板中的自动完成字段包装在<form>
标记中,以便提交值(如果尚未提交)。
下一步是在视图中检索数据:
request.POST.getlist('tags')
而已。 现在,您具有所选值的主键列表:
>>> print(str(request.POST.getlist('tags'))
['1', '3', '4', '7', ...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.