0

我使用django-selectable插件。从文档

在从基于模型的查找扩展的查找的情况下,新创建的项目尚未保存到数据库中,保存应由表单处理

模型:

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,表单无法使用此视图保存。如何使用此插件保存表单?

提前致谢

4

1 回答 1

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)
于 2013-10-29T22:19:36.630 回答