For my project I have created in my project a new model called displacement, which will be related to the animal model by means of a variable type manytomanyfield
:
class desplazamiento(models.Model):
nombre=models.CharField(max_length=15)
descripcion=models.CharField(max_length=150)
foto=models.ImageField(null=True)
def __str__(self):
return self.nombre
class animal(models.Model):
ncomun=models.CharField(max_length=50)
ncientifico=models.CharField(max_length=50)
foto=models.ImageField()
categoria=models.ForeignKey(categoria,null=True)
alimentacion=models.ForeignKey(alimentacion,null=True)
desplazamiento=models.ManyToManyField(desplazamiento)
def __str__(self):
return self.ncomun
The next thing is that the form to make a new animal fits the new variable:
class nue_animal(forms.ModelForm):
class Meta:
model = animal
fields = ('ncomun', 'ncientifico', 'foto', 'categoria', 'alimentacion', 'desplazamiento')
Code views.py :
def nuevo_animal(request):
if request.method == "POST":
form = nue_animal(request.POST, request.FILES)
if form.is_valid():
com = form.cleaned_data['ncomun']
cie = form.cleaned_data['ncientifico']
fot = form.cleaned_data['foto']
cat = form.cleaned_data['categoria']
ali = form.cleaned_data['alimentacion']
des = form.cleaned_data['desplazamiento']
an = animal(ncomun=com, ncientifico=cie, foto=fot, categoria=cat, alimentacion=ali, desplazamiento=des)
an.save()
return HttpResponseRedirect('/')
else:
form=nue_animal()
return render(request,'bestias.html',{'forma':form})
So I can add the variable to the form, but when I give insertar
, I get this:
needs to have a value for field "animal" before this many-to-many relationship can be used.
PS: The Jabali
is the name ( ncomun
) of the new animal. On the contrary, if I insert the animal through the administrator, everything goes well.