问题描述
我是django的新手,我为我的项目写了一个邮寄表格,想使用自动完成功能在Line邮寄表格中的Node字段中选择外键。 我已经成功地应用了django-autocomplete-light返回外键(node_name),但是当我发布它时该表单无效。我猜外键是一个node_id的数字,但是自动完成返回了文本( node_name)。 如何使用django-autocomplete-light应用程序修复它? 谢谢。
models.py:
class Node(models.Model):
node_name = models.CharField(max_length=255)
def __unicode__(self):
return self.node_name
class Line(models.Model):
node = models.ForeignKey(Node,on_delete=models.PROTECT)
line_code = models.CharField(max_length=100)
def __unicode__(self):
return self.line_code
forms.py:
from django import forms
import autocomplete_light
from .models import Line,Node
class LineForm(forms.ModelForm):
class Meta:
model = Line
autocomplete_fields = ('node')
widgets = {
'node': autocomplete_light.TextWidget('NodeAutocomplete'),
}
class NodeForm(forms.ModelForm):
class Meta:
model = Node
autocomplete_light_registry.py:
import autocomplete_light.shortcuts as al
from models import Node,Line
al.register(Node,
search_fields=['node_name'],
attrs={
'data-autocomplete-minimum-characters': 1,
},
widget_attrs={
'data-widget-maximum-values': 4,
'class': 'modern-style',
},
)
1楼
我已经解决了我的问题。autocomplete_light_registry.py中有问题。现在,我已对其进行了更改。
import autocomplete_light.shortcuts as al
from models import Node,Line
# This will generate a LineAutocomplete class
al.register(Line,
# Just like in ModelAdmin.search_fields
search_fields=['node'],
attrs={
# This will set the input placeholder attribute:
'placeholder': '',
# This will set the yourlabs.Autocomplete.minimumCharacters
# options, the naming conversion is handled by jQuery
'data-autocomplete-minimum-characters': 1,
},
# This will set the data-widget-maximum-values attribute on the
# widget container element, and will be set to
# yourlabs.Widget.maximumValues (jQuery handles the naming
# conversion).
widget_attrs={
'data-widget-maximum-values': 4,
# Enable modern-style widget !
'class': 'modern-style',
},
)
al.register(Node,
# Just like in ModelAdmin.search_fields
search_fields=['node_name'],
attrs={
# This will set the input placeholder attribute:
'placeholder': '',
# This will set the yourlabs.Autocomplete.minimumCharacters
# options, the naming conversion is handled by jQuery
'data-autocomplete-minimum-characters': 1,
},
# This will set the data-widget-maximum-values attribute on the
# widget container element, and will be set to
# yourlabs.Widget.maximumValues (jQuery handles the naming
# conversion).
widget_attrs={
'data-widget-maximum-values': 4,
# Enable modern-style widget !
'class': 'modern-style',
},
)