[英]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.