我在我的应用程序中使用了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