【发布时间】:2015-08-23 21:36:51
【问题描述】:
我无法从包含 django-autocomplete-light 生成的数据的 HTML 元素中获取数据。 这是表单的代码:
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" 的错误
我尝试的下一件事是将choice_html 从base.py 更改为:
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。
我绝对确信有一种简单的方法可以完成我需要的任务。
【问题讨论】:
标签: javascript jquery python django django-autocomplete-light