我使用的是django-selectable,無法從模板中保存代表類別id的「id」('autocomplete_1')。django-selectable - 從模板中保存數據的問題
models.py
class Category(models.Model):
cat_no = models.IntegerField(null=True, blank=True)
cat_txt = models.CharField(max_length=45)
def __unicode__(self):
return self.cat_txt
class Cattest(models.Model):
category = models.ForeignKey(Category)
info = models.CharField(max_length=35, blank=True)
lookups.py
class CategoryLookup(ModelLookup):
model = Category
search_fields = ('cat_txt__icontains',)
forms.py
class CategoryForm(forms.Form):
autocomplete = forms.CharField(
label='Type the name of a category (AutoCompleteWidget)',
widget=selectable.AutoCompleteWidget(CategoryLookup),
required=False,
)
autocompleteselect = selectable.AutoCompleteSelectField(
lookup_class=CategoryLookup,
label='Select a category (AutoCompleteField)',
required=False,
)
class CattestForm(forms.Form):
#model = cattest
#fields = ('category', 'info')
autocomplete = forms.CharField(
label='Type the name of a category (AutoCompleteSelectWidget)',
widget=selectable.AutoCompleteSelectWidget(CategoryLookup),
required=False,
)
info = forms.CharField(max_length=35, label="Information")
views.py
def cattest(request):
if request.method == 'POST':
form = CattestForm(request.POST)
if form.is_valid():
cattest = Cattest.objects.create(
category=form.cleaned_data['autocomplete_1'],
info=form.cleaned_data['info'],
)
# Always redirect after a POST
return http.HttpResponseRedirect('/bsmain/login_customer')
else:
if request.GET:
form = CattestForm(initial=request.GET)
else:
form = CattestForm()
return render_to_response('bsmain/form.html', {'form': form}, context_instance=RequestContext(request))
回溯:
KeyError異常在/ bsmain/cattest/
'autocomplete_1'
請求方法:POST 請求URL:http://127.0.0.1:8000/bsmain/cattest/ Django的版本:1.3.1 異常類型:KeyError異常 異常值:
'autocomplete_1'
異常位置:/ home /票據/工作區/ boatsite /../ boatsite/bsmain /在cattest views.py 64行 Python的可執行文件:在/ usr/bin中/ Python的 Python版本:2.6.5
索取信息
得不到GET數據 POST變量值
info u'44# Bruce'
csrfmiddlewaretoken u'9ffe49bd68be04087521e71e86a5bec0'
autocomplete_1 u'10'
autocomplete_0 u'Anchors'
馬克 - 我試過了。我收到一個錯誤:ValueError at/bsmain/cattest/ 無法分配「u」'「:」Cattest.category「必須是」類別「實例。 – BillB1951 2012-03-02 03:28:22
..如果我使用form.cleaned_data ['category']我得到KeyError at/bsmain/cattest/ 'category'我認爲django-selectable是一個很棒的應用程序,我希望我能儘快爲它工作。 – BillB1951 2012-03-02 03:41:17
有幾個問題與您當前的表單有關。 'autocomplete'不是必需的,但類別要填充。它也不會返回正確的類型作爲您的第一條評論。我已經使用ModelForm添加了一個示例。 – 2012-03-02 04:14:34