【问题标题】:Django/Jquery problem - Cannot assign "u'Agua'": "Venta.producto" must be a "Producto" instanceDjango/Jquery 问题 - 无法分配“u'Agua”:“Venta.producto”必须是“Producto”实例
【发布时间】:2011-10-01 16:39:09
【问题描述】:

我在我的应用程序中使用 django+jquery 自动完成小部件。我自定义了一张表的管理表单,以在输入文本框中自动完成。 它的工作原理是当我保存表单时发生以下异常:

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,它正在发送所选产品的数字键(即: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>

当在自动完成文本框中写入时,即:agua,它发送一个 GET 并且响应如下。

http://127.0.0.1:8080/search/?q=producto&term=agua

[{"id": 3, "value": "Agua", "label": "Agua"}]

版本

django 1.1.1
jquery 1.5.1
jquery-ui 1.8.13

【问题讨论】:

    标签: jquery django django-models autocomplete foreign-keys


    【解决方案1】:
    producto = models.ForeignKey(Producto)
    

    在您的 Venta 模型定义中,您将 producto 定义为外键,这意味着,当您保存表单时,django 期望获取相关对象的 id(在这种情况下,相关的producto记录)而不是记录的标签。

    Django 为此类外键使用组合框,其 html 输出如下:

    <select name='producto'>
        <option value='3'>Agua</option>
        ...
    

    如果您将该字段显示为 raw_id_field (documentation),django 将显示该对象的 id,并在该字段附近写入 unicode 值。

    所以你必须传递相关对象的 id,而不是名称或 unicode 字符串。我不使用自动完成小部件,但必须有一个正确的方法来正确地做到这一点。

    【讨论】:

      【解决方案2】:

      看起来“Agua”是传回控制器的值,而 Rails 期望你传递“3”。你可以尝试改变你的后端发送

      [{"value": "3", "label": "Agua"}]
      

      看看有没有效果

      【讨论】:

      • 导轨?它是 Python 而不是 Ruby。无论如何,它不起作用,如果数字(主键)在 value 中,它会出现在组合框下拉列表中(1..2..3..4 低于其他),但是当您选择一个时,文本,即 Agua 会出现在文本框中。那么value就是combobox里面的选项,label是用来选择的,但是如果我修改为回复"value": "Agua", "label": 2,。 ..",在下拉框中出现Agua,但是当我选择一个时,在选择文本框中出现数字(主键)。
      猜你喜欢
      • 2015-01-05
      • 2013-12-18
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 2018-06-03
      • 1970-01-01
      相关资源
      最近更新 更多