我的问题是: Viaje类与Destino保持N:1的关系。我想为新的Viaje输入数据但是出现以下错误:
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
形式:
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)
模型:
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
最终结果应该允许表单选择目的地,但我无法做到这一点。
答案 0 :(得分:1)
由于destino
模型中的Viaje
是引用Destino
实例的ForeignKey,因此您应在ModelChoiceField
中使用ModelForm
而不是简单CharField
1}}:
class formularioViaje(forms.Form):
destino = forms.ModelChoiceField(
queryset=Destino.objects.all(),
required=True,
)