Django/Jquery 问题 - 无法分配“u”Agua“”:“Venta.producto”必须是“Producto”实例

发布于 2024-11-19 07:52:30 字数 3449 浏览 1 评论 0原文

我在我的应用程序中使用 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,它正在发送所选 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>

当写入时,即: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

I'm using django+jquery autocomplete widget in my application. I customized the admin form of one of my tables to get autocomplete in the input textbox.
It's working except that when I save the form the following exception occurs:

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
...

It seems that it's not converting my autocompleted text in a Producto object. I saw the POST and it's sending the numerical key (i.e: 2) of the Producto selected. When I disabled all the autocomplete stuff, the post is exactly the same but it works. So something of admin.py or models.py sourcecode is wrong. Then something is doing that in a case it's converting it to an object and not in the other one.

The following is the models.py part:

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()

The following is the admin.py part:

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')

The javascript part:

<script>
$(function() {
        $( "#id_producto" ).autocomplete({
                source: "/search/?q=producto",
        });
        $( "#id_responsable" ).autocomplete({
                source: "/search/?q=responsable",
        });
});
</script>

When a write, i.e.: agua, in the autocomplete textbox, it send a GET and the response is the following.

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

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

versions

django 1.1.1
jquery 1.5.1
jquery-ui 1.8.13

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雨后彩虹 2024-11-26 07:52:30

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

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

并查看它是否有效

It looks like "Agua" is the value thats being passed in back to your controller whereas Rails is expecting you to pass "3". Can you try changing your backend to send

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

and see if it works

喜你已久 2024-11-26 07:52:30
producto = models.ForeignKey(Producto)

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

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

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

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

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

producto = models.ForeignKey(Producto)

In your Venta model definition, you defined producto as a foreignkey, that means, when you save the form, django expects to get the id of the related object (in this situation, id of the related producto record) not the label of the record.

Django uses a combo box for such foreignkeys, with an html output like:

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

If you sdisplay that field as a raw_id_field (documentation), django will display id of the object, and write the unicode value near the field.

So you have to pass the id of the relatred object, not the name or unicode string. I dont use autocomplete widget, but there must be a proper way to do it correctly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文