简体   繁体   English

Django-autocomplete-light如何从html获取数据?

[英]Django-autocomplete-light how to get data from html?

I can't get how to fetch data from HTML-element that contains data generated by django-autocomplete-light. 我不知道如何从HTML元素中获取数据,其中包含由django-autocomplete-light生成的数据。 Here is a code of the form: 这是形式的代码:

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)

And autocomplete_light_registry.py: 和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,
},)

As you see I've changed the django-autocomplete app. 如您所见,我已经更改了django-autocomplete应用程序。 In the base.py I found a variable choice_html_format = '<span data-value="%s" name="choice">%s</span>' Attribute name was added by me to get data like that: 在base.py中,我发现了一个变量choice_html_format = '<span data-value="%s" name="choice">%s</span>' 。我添加了属性name以获取类似的数据:

tags = request.POST.get('name')

But this doesn't work. 但这是行不通的。 I'm getting an error like "NoneType in not callable" Next thing I've tried is change choice_html from base.py : 我收到类似"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)))

It is original function, I've changed choice_value(choice) to choice_label(choice) . 这是原始功能,我已经将choice_value(choice)更改为choice_label(choice) And got an error "invalid literal for int() with base 10: <tag_name_here>" . 并得到一个错误"invalid literal for int() with base 10: <tag_name_here>" Looks like data-value attribute is only for int() type (but I can't get where I can change it, maybe in js-function, I don't know). 看起来data-value属性仅适用于int()类型(但是我不知道可以在哪里更改它,也许在js函数中,我不知道)。

And the last, I'm trying to get the pk of each tag, and then get the name via manager. 最后,我试图获取每个标签的pk,然后通过管理器获取名称。 But I'm getting error Cannot resolve keyword '4' into field. Choices are: id, items, name 但是我遇到错误Cannot resolve keyword '4' into field. Choices are: id, items, name Cannot resolve keyword '4' into field. Choices are: id, items, name . Cannot resolve keyword '4' into field. Choices are: id, items, name

I absolutely sure that there is an easy way to perform the task I need. 我绝对确定,有一种简单的方法可以执行我需要的任务。

autocomplete-light has a template called widget.html that is rendered in the template: 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 %}
...

as you can see, this <select> element contains all selected choices for the autocomplete widget. 如您所见,此<select>元素包含自动完成小部件的所有选定选项。

Its name (we are going to identify it by its name attribute later in the view) is simply the autocomplete's name ('tags'). 它的名称(我们将在后面的视图中通过其name属性来标识它)只是自动完成的名称(“标签”)。

So now you need to make sure your autocomplete field in the template is wrapped in <form> tags so the values get submitted (if you haven't already). 因此,现在您需要确保模板中的自动完成字段包装在<form>标记中,以便提交值(如果尚未提交)。

The next step is to retrieve the data in the view: 下一步是在视图中检索数据:

request.POST.getlist('tags')

That's it. 而已。 You now have a list of primary keys of the selected values: 现在,您具有所选值的主键列表:

>>> print(str(request.POST.getlist('tags'))
['1', '3', '4', '7', ...]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 javascript 获取、更改或清除 django-autocomplete-light 字段值 - How to get, change or clear a django-autocomplete-light field value with javascript 如何以内联形式使用“ django-autocomplete-light” - How to use “django-autocomplete-light” in inline form django-autocomplete-light提供JavaScript错误 - django-autocomplete-light giving javascript errors Django:django-autocomplete-light无法正常工作 - Django: django-autocomplete-light does not work properly 如何通过javascript取消选择django-autocomplete-light小部件的所有选项? - How to deselect all choices of the django-autocomplete-light widget via javascript? 在django-autocomplete-light中以编程方式选择第一个建议 - Programmatically select the first suggestion in django-autocomplete-light Django-Autocomplete-Light Widget在Django-Rest-Framework中导致较长的加载时间 - Django-Autocomplete-Light Widget causing long loading times in Django-Rest-Framework Django-autocomplete-light - 启动时浏览器中的“未找到结果” - 在管理员中进行一次搜索后 - 再次在浏览器中找到结果 - Django-autocomplete-light - "No results found" in browser on startup - after doing one search in admin - results are found in browser again 如何将 HTML 表格中的数据导入 DJango - How to get data from a HTML table into DJango 如何使用 jQuery 在 Django Autocomplete Light 小部件上捕获更改事件 - How to capture on change event on Django Autocomplete Light widget using jQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM