我无法从包含 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>'
Attributename
来获取这样的数据:
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,然后通过 manager 获取名称。但我得到错误Cannot resolve keyword '4' into field. Choices are: id, items, name
。
我绝对确信有一种简单的方法可以执行我需要的任务。