Search code examples
djangoformsdjango-1.7

Django 1.7 ERROR: Cannot assign "u'Cordoba'": "Viaje.destino" must be a "Destino" instance


my problem is this: The Viaje class maintains a relationship N: 1 with Destino. I want to enter data for a new Viaje but got the following error:

Django Version: 1.7
 Exception Type:    ValueError
 Exception Value:   
 Cannot assign "u'Cordoba'": "Viaje.destino" must be a "Destino"   instance.
 Exception Location:    /usr/local/lib/python2.7/dist-packages/Django-1.7- py2.7.egg/django/db/models/fields/related.py in __set__, line 597> Python Executable:    /usr/bin/python> Python Version:    2.7.6
Python Path: ['/home/juanma/Escritorio/exPWfebrero/Django/AgenciaViajes',
'/usr/local/lib/python2.7/dist-packages/Django-1.7-py2.7.egg',
'/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PILcompat',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
 '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode']
 Server time:   Tue, 2 Feb 2016 04:54:43 -0600

forms:

from django import forms
from viajes.models import Destino, Viaje



DESPLAZAMIENTOS = (
    ('autobus', 'autobus'),
    ('tren', 'tren'),
    ('avion', 'avion'),
    ('coche', 'coche')
    )


class formularioViaje(forms.Form):
    destino = forms.CharField(required=True)
    dias = forms.IntegerField(required=True)
    coste = forms.IntegerField(required=True)
    desplazamiento = forms.ChoiceField(choices=DESPLAZAMIENTOS)

models:

from django.db import models
from django.contrib.auth.models import User



class Destino(models.Model):
    lugar = models.CharField(max_length=100)
    descripcion = models.TextField()
    distancia = models.IntegerField()

    def __unicode__(self):
            return self.lugar

class Viaje(models.Model):
    destino = models.ForeignKey(Destino)
    dias = models.IntegerField()
    coste = models.IntegerField()
    desplazamiento = models.CharField(max_length=100)

    def __unicode__(self):
        return self.destino

The end result should allow the form to choose a destination , but I can not achieve this.


Solution

  • Since destino in Viaje model is a ForeignKey referring to a Destino instance you should use a ModelChoiceField in your ModelForm instead of a simple CharField:

    class formularioViaje(forms.Form):
        destino = forms.ModelChoiceField(
            queryset=Destino.objects.all(),
            required=True,
        )