Reputation: 1
I want to save Department model forms with Model Direccion values, using foreign key in Department, but I have this error.
Models.py
class Direccion(models.Model):
calle = models.CharField(max_length=50)
numero = models.CharField(max_length=6)
#comuna = models.ForeignKey(Comuna, on_delete=models.CASCADE)
class Departamento(models.Model):
n_habitaciones = models.IntegerField(max_length=1)
n_banios = models.IntegerField(max_length=1)
n_depto = models.CharField(max_length=5)
descripcion = models.CharField(max_length=500)
precio = models.IntegerField(max_length=10)
img1 = models.ImageField(upload_to='Departamentos/')
img2 = models.ImageField(upload_to='Departamentos/')
img3 = models.ImageField(upload_to='Departamentos/')
img4 = models.ImageField(upload_to='Departamentos/')
img5 = models.ImageField(upload_to='Departamentos/')
direccion = models.ForeignKey(Direccion, on_delete=models.CASCADE)
Forms.py
class DeptosForms(forms.ModelForm):
descripcion = forms.CharField(max_length=1000, widget=forms.Textarea)
img1 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'}))
img2 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'}))
img3 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'}))
img4 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'}))
img5 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'}))
calle = forms.CharField(max_length=50)
numero = forms.CharField(max_length=6)
class Meta:
model = Departamento
fields = ('n_habitaciones', 'n_banios', 'n_depto', 'precio', 'descripcion', 'img1',
'img2', 'img3', 'img4', 'img5', 'calle', 'numero', )
Views.py
def AddDepto(request):
if request.method == 'POST':
form = DeptosForms(request.POST, request.FILES)
if form.is_valid():
depto = form.save()
depto.save()
messages.success(request, 'Departamnto registrado correctamente')
return redirect('show_deptos')
else:
form = DeptosForms()
return render(request, 'core/add_dptos.html', {'form': form})
Error: enter image description here
Upvotes: 0
Views: 48
Reputation: 325
Forms.py
class DeptosForms(forms.ModelForm):
class Meta:
model = Departamento
fields = ('n_habitaciones', 'n_banios', 'n_depto', 'precio', 'descripcion', 'img1',
'img2', 'img3', 'img4', 'img5', 'calle', 'numero', )
views.py
def AddDepto(request):
if request.method == 'POST':
form = DeptosForms(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, 'Departamnto registrado correctamente')
return redirect('show_deptos')
else:
form = DeptosForms()
return render(request, 'core/add_dptos.html', {'form': form})
Models.py
direccion=models.ForeignKey(Direccion, null=True, on_delete=models.CASCADE)
Upvotes: 1