我正在使用Django Forms来创建一个新对象,但是我遇到了问题。一切都OK,但是当我提交表单时,会引发错误:
“ / rutinas / nueva_rutina的AttributeError
'DiaForm'对象没有属性'ejercicios'“
我尝试了许多在这里阅读的可能解决方案,但是它们没有用。我认为问题出在M2M关系上,但也可能是一次处理两种形式。这是我的文件
models.py
class Ejercicio(models.Model):
id = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=30, default='')
descripcion = models.TextField(default='')
gif = models.ImageField(default='')
def __str__(self):
return self.nombre
class Rutina(models.Model):
id = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=30, default='')
def __str__(self):
return self.nombre
class Dia(models.Model):
ejercicios = models.ManyToManyField(Ejercicio)
rutina = models.ForeignKey(Rutina, on_delete=models.CASCADE)
forms.py
class RutinaForm(forms.ModelForm):
class Meta:
model = Rutina
fields = '__all__'
labels = {
'nombre': _('Nombre')
}
class DiaForm(forms.ModelForm):
ejercicios = forms.ModelMultipleChoiceField(queryset=Ejercicio.objects.all())
class Meta:
model = Dia
fields = ['ejercicios']
labels = {
'ejercicios': _('Ejercicios')
}
views.py
def nueva_rutina_view(request):
if request.method == "POST":
form = RutinaForm(request.POST)
dia_form_1 = DiaForm(request.POST)
dia_form_2 = DiaForm(request.POST)
dia_form_3 = DiaForm(request.POST)
if form.is_valid() and dia_form_1.is_valid() and dia_form_2.is_valid() and dia_form_3.is_valid():
rutina = form.save(commit=False)
dia1 = dia_form_1.save(commit=False)
dia2 = dia_form_2.save(commit=False)
dia3 = dia_form_3.save(commit=False)
rutina.save()
dia1.rutina = rutina
dia2.rutina = rutina
dia3.rutina = rutina
dia1.ejercicios = dia_form_1.ejercicios
dia2.ejercicios = dia_form_2.ejercicios
dia3.ejercicios = dia_form_3.ejercicios
dia1.save()
dia2.save()
dia3.save()
return redirect(historial_rutinas_view)
else:
form = RutinaForm()
dia_form_1 = DiaForm()
dia_form_2 = DiaForm()
dia_form_3 = DiaForm()
return render(request, 'rutinas/nueva-rutina.html', {'form': form, 'dia_form_1': dia_form_1, 'dia_form_2': dia_form_2, 'dia_form_3': dia_form_3})