我在我的應用程序中使用了django + jquery自動填充小部件。我自定義了我的一個表格的管理員表單,以在輸入文本框中獲得自動完成。 它的工作不同的是,當我救下發生異常形式:Django/jquery問題 - 無法指定「u'Agua」「:」Venta.producto「必須是」Producto「實例
ValueError at /admin/Stock/venta/add/
Cannot assign "u'Agua'": "Venta.producto" must be a "Producto" instance.
Request Method: POST
Request URL: http://127.0.0.1:8080/admin/Stock/venta/add/
Exception Type: ValueError
Exception Value:
Cannot assign "u'Agua'": "Venta.producto" must be a "Producto" instance.
Exception Location: /usr/lib/pymodules/python2.6/django/db/models/fields/related.py in __set__, line 273
Python Executable: /usr/bin/python
Python Version: 2.6.5
...
看來,這不是我的轉換文本自動完成的在PRODUCTO對象。我看到了POST,它發送了所選Producto的數字鍵(即:2)。當我禁用所有自動填充的東西時,帖子是完全一樣的,但它的工作原理。因此,某些admin.py或models.py源代碼是錯誤的。然後有一件事情正在將它轉換爲對象而不是另一個。
以下爲models.py部分:
class Producto(models.Model):
detalle = models.CharField('Detalle', max_length=200)
importe = models.FloatField('Importe')
def __unicode__(self):
return self.detalle
class Empleado(models.Model):
nombre = models.CharField('Nombre', max_length=100)
def __unicode__(self):
return self.nombre
class Venta(models.Model):
importe = models.FloatField('Importe')
producto = models.ForeignKey(Producto)
responsable = models.ForeignKey(Empleado)
mesa = models.IntegerField()
以下爲admin.py部分:
class VentaAdminForm(forms.ModelForm):
importe = forms.DecimalField()
producto = forms.CharField()
responsable = forms.CharField()
mesa = forms.IntegerField()
class Meta:
model = Venta
fields = ['producto', 'importe', 'responsable', 'mesa']
class VentaAdmin(admin.ModelAdmin):
form = VentaAdminForm
admin.site.register(Venta, VentaAdmin)
views.py
@login_required
def search(request):
results = []
if request.method != "GET":
return HttpResponse()
term = q = None
if request.GET.has_key(u'q'):
q = request.GET[u'q']
if request.GET.has_key(u'term'):
term = request.GET[u'term']
if not q or not term:
return HttpResponse()
if q == 'producto':
model_results = Producto.objects.filter(detalle__contains=term)
for x in model_results:
results.append({'label': x.detalle,'value': x.detalle, 'id': x.id })
elif q == 'responsable':
model_results = Empleado.objects.filter(nombre__contains=term)
for x in model_results:
results.append({'label': x.nombre,'value': x.nombre, 'id': x.id })
else:
raise Exception("Unknown query_object")
json = simplejson.dumps(results)
return HttpResponse(json, mimetype='application/json')
JavaScript部分:
<script>
$(function() {
$("#id_producto").autocomplete({
source: "/search/?q=producto",
});
$("#id_responsable").autocomplete({
source: "/search/?q=responsable",
});
});
</script>
當寫入,即:阿瓜,在自動完成的文本框,它發送一個GET和響應如下。
http://127.0.0.1:8080/search/?q=producto &項=阿瓜
[{"id": 3, "value": "Agua", "label": "Agua"}]
版本
django 1.1.1
jquery 1.5.1
jquery-ui 1.8.13
Rails?它是_Python_而不是_Ruby_。無論如何,它不起作用,如果數字(主鍵)在_value_中,它出現在組合框下拉列表中(1..2..3..4位於另一個下方),但是當你選擇一個時,文本,即_Agua_出現在文本框中。然後,_value_用於組合框中的選項,並且該標籤用於選擇,但是如果我將其修改爲回覆_「value」:「Agua」,「label」:2,...「_,在Dropbox中出現阿瓜,但是當我選擇一個,在選擇文本框中出現numbre(主鍵)。 – Tavo