我无法从包含django生成的数据的HTML元素中获取数据--自动完成-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--自动完成应用程序。在base.py中,我发现我添加了一个变量choice_html_format = '<span data-value="%s" name="choice">%s</span>'属性name来获取这样的数据:
tags = request.POST.get('name')但这不管用。我得到了一个类似于"NoneType in not callable"的错误,接下来我尝试的是从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-function,我不知道)。
最后,我试图得到每个标签的pk,然后通过经理获得名称。但是我得到了错误Cannot resolve keyword '4' into field. Choices are: id, items, name。
我绝对相信有一个简单的方法来完成我需要的任务。
发布于 2015-08-24 05:42:57
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属性来标识它)只是自动完成的名称(‘tag’)。
因此,现在需要确保模板中的自动完成字段被包装在<form>标记中,以便提交值(如果您还没有提交)。
下一步是检索视图中的数据:
request.POST.getlist('tags')就这样。现在有了所选值的主键列表:
>>> print(str(request.POST.getlist('tags'))
['1', '3', '4', '7', ...]https://stackoverflow.com/questions/32171786
复制相似问题