I have the following problem I have two models one Themes and another Videos have a relationship much to many already that a video can deal with different topics, the problem is that when saving a video I do not give any error and I am saved but without the themes chosen with a CheckboxSelectMultiple, besides that the topics field does not validate me and I am declaring it required in the form, the strangest thing is that using the Django admin if all the fields including the Many-to-Many are stored
Model.py
class Tema(models.Model):
nombre = models.CharField(max_length=100)
color = models.CharField(max_length=7, default='#007bff')
def __str__(self):
return self.nombre
def get_html_badge(self):
name = escape(self.nombre)
color = escape(self.color)
html = '<span class="badge badge-primary" style="background-color: %s">%s</span>' % (color, name)
return mark_safe(html)
class Video(models.Model):
nombre = models.CharField(max_length=100)
dueño = models.ForeignKey(User, on_delete=models.CASCADE, related_name='videos')
docfile = models.FileField(upload_to='video/%Y/%m/%d')
descripcion = models.CharField(max_length=500)
tema = models.ManyToManyField(Tema, related_name='video_tema',blank=False)
def __str__(self):
return '%s ' % (self.nombre)
View.py
class VideoCreateView(CreateView):
model = Video
form_class = VideoAdd
template_name = 'Lab/video_add_form.html'
def form_valid(self, form):
video = form.save(commit=False)
video.dueño = self.request.user
video.save()
messages.info(self.request, 'El video fue añadido satisfactoriamente')
return redirect('add_video')
forms.py
class VideoAdd(forms.ModelForm):
tema = forms.ModelMultipleChoiceField(
queryset=Tema.objects.all(),
widget=forms.CheckboxSelectMultiple(),
required=True,
)
class Meta:
model = Video
fields = ('docfile', "nombre", 'descripcion','tema')