我正在使用django-selectable插件。来自docs:
如果从基于模型的查找扩展查找,则新创建的项目尚未保存到数据库中,并且应该通过表单处理保存
型号:
class UserSettings(models.Model):
user = models.ForeignKey(UserProfile, related_name='own_user')
lookup_user = models.ManyToManyField(UserProfile, related_name='other_user')
category = models.ManyToManyField(NewsCategory)
tag = models.ManyToManyField(Tag)
形式:
class UserSettingsForm(forms.ModelForm):
category = TreeNodeChoiceField(
required=False,
queryset=NewsCategory.objects.filter(status=True, is_deleted =False), label=u"Kategori", widget=forms.SelectMultiple(attrs={'class':'uniformselect'})
)
class Meta:
model = UserSettings
exclude = ['user']
widgets = {
'lookup_user': selectable.AutoCompleteSelectMultipleWidget(lookup_class=UserLookUp,),
'tag': selectable.AutoCompleteSelectMultipleWidget(lookup_class=TagLookUp,),
}
查找
class UserLookUp(ModelLookup):
model = UserProfile
search_fields = ('first_name__icontains', )
filters = {'is_active': True, }
def get_item_value(self, item):
return item.get_full_name()
def get_item_label(self, item):
return u"(%s)" % (item.get_full_name())
registry.register(UserLookUp)
@login_required
class TagLookUp(ModelLookup):
model = Tag
search_fields = ('slug__icontains', )
def get_item_value(self, item):
return item.name
def get_item_label(self, item):
return u"(%s)" % (item.name)
registry.register(TagLookUp)
并查看:
def user_settings(request):
try:
set = UserSettings.objects.filter(blabla)[0]
except:
set = None
if request.method == 'POST':
form = UserSettingsForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.user = user
obj.save()
form.save_m2m()
return HttpResponseRedirect('/')
else:
form = UserSettingsForm(instance=set)
return render_to_response('main/settings.html', {'form':form,},
context_instance=RequestContext(request))
错误:
TypeError at /news/settings/
int() argument must be a string or a number, not 'list'
Request Method: POST
Request URL: http://localhost:8000/news/settings/
Django Version: 1.4
Exception Type: TypeError
Exception Value:
int() argument must be a string or a number, not 'list'
Exception Location: /Library/Python/2.7/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 537
使用django-selectable,表单无法保存此视图。如何使用此插件保存表单?
提前致谢
答案 0 :(得分:0)
我通过替换它解决了这个问题:
category = TreeNodeChoiceField(
required=False,
queryset=NewsCategory.objects.filter(status=True, is_deleted =False), label=u"Kategori", widget=forms.SelectMultiple(attrs={'class':'uniformselect'})
)
由此:
category = forms.ModelMultipleChoiceField(queryset=NewsCategory.objects.filter(parent__isnull=False, status=True, is_deleted=False)