开发者

Django/Jquery problem - Cannot assign "u'Agua'": "Venta.producto" must be a "Producto" instance

开发者 https://www.devze.com 2023-03-18 21:09 出处:网络
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.

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 VentaAdmin开发者_如何转开发Form(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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消