Как на сайте отобразить значения models.ManyToManyField?
я новенький в python/django, прошу оказать помощь. Пытаюсь отобразить значения связи models.ManyToManyField, но не получается. Если через админ панель добавить или отредактировать, то потом на сайте все отображается корректно, но мне нужно через кнопки на сайте добавить новую запись или отредактировать существующую(через модальное окно в моем случае). Для уточнения, данные добавляются, но в таблице после добавления не отображается поле ManyToManyField.
models.py
class DicAuditories(models.Model):
title = models.CharField(max_length=100)
vmestimost = models.IntegerField(models.SET_NULL, null=True, blank=True)
kafedra = models.ForeignKey(DicDepartments, models.SET_NULL, null=True, blank=True)
typeLessons = models.ManyToManyField(DicTypeLessons, null=True, blank=True, related_name='typeLessons')
def __str__(self):
return self.title
views.py
@login_required
def dicauditories(request):
dicauds = DicAuditories.objects.all()
typelessonsAud = DicTypeLessons.objects.all()
form = AudForm(request.POST)
if request.method == 'GET':
return render(request, 'tao/dicauditories.html', {'dicauds': dicauds,
'form': AudForm(),
'typelessonsAud': typelessonsAud
})
else:
try:
if form.is_valid():
newgroup = form.save(commit=False)
newgroup.save()
# newgroup.typeLessons.add(newgroup.object.get())
return redirect('dicauditories')
except TypeError:
return render(request, 'tao/dicauditories.html', {'dicauds': dicauds,
'form': AudForm(),
'error': 'Ошибка',
})
@login_required
def auditoriesedit(request, id):
dicauds = DicAuditories.objects.all()
audsedit = DicAuditories.objects.get(id=id)
type = DicTypeLessons.objects.all()
type2 = get_object_or_404(DicTypeLessons, id=id)
audsedit.typeLessons.add(DicTypeLessons.objects.get(type2))
# audsedit.typeLessons.create(DicTypeLessons.objects.get(id=3))
form = AudForm(request.POST or None, instance=audsedit)
if request.method == 'GET':
return render(request, 'tao/dicauditories.html', {'dicauds': dicauds,
'form': AudForm(),
})
else:
try:
if form.is_valid():
audsedit = form.save(commit=False)
audsedit.save()
return redirect('dicauditories')
except TypeError:
return render(request, 'tao/dicauditories.html', {'dicauds': dicauds,
'error': 'Ошибка',
'form': AudForm(),
})
return render(request, 'tao/dicauditories.html', {'dicauds': dicauds, })
html
<div class="mb-md">
<button type="button" id="addToTable2" class="btn btn-primary" data-toggle="modal"
data-target="#groupModal">Добавить <i class="fa fa-plus"></i></button>
</div>
<!-- Modal -->
<div class="modal fade" id="groupModal" tabindex="-1" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Создание аудитории</h5>
<button type="button" class="btn-close" data-dismiss="modal"
aria-label="Close"></button>
</div>
<div class="modal-body">
<form method="POST">
{% csrf_token %}
<div class="mb-3">
<!-- <label for="recipient-name" class="col-form-label"></label>-->
{{ form.as_p }}
<!-- <input type="text" class="form-control" id="recipient-name">-->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Отмена
</button>
<button type="submit" class="btn btn-primary">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
</div>
forms.py
class AudForm(ModelForm):
class Meta:
model = DicAuditories
fields = ['title', 'vmestimost', 'typeLessons', 'kafedra']
labels = {'title': ('Наименование'), 'vmestimost': ('Вместимость'),
'typeLessons': ('Типы занятий'), 'kafedra': ('Кафедра'),}