имеется форма для сознания объекта модели. В этой форме есть поле по выбору некоторого оборудования (equipment он же в модели ForeignKey). Я пытаюсь использовать в этом поле Checkbox, но каждый раз при попытке сохранить внесенные изменения ничего не происходит. Форма просто сбрасывается. Так-же если не использовать виджет Checkbox, а вместо него простой Select, то все работает. Как решить данную проблему?
models.py
class Events(models.Model):
applicant = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Заявитель', blank=False)
purpose_of_use = models.CharField(max_length=500, verbose_name='Цель заседания', blank=False)
comment = models.CharField(max_length=500, verbose_name='Комментарий', blank=True)
equipment = models.ForeignKey('Equipments', on_delete=models.CASCADE, verbose_name='Оборудование')
lecture_hall = models.ForeignKey('LectureHalls', on_delete=models.CASCADE, verbose_name='Аудитория', blank=False)
condition = models.ForeignKey('Conditions', verbose_name='Состояние', on_delete=models.CASCADE, blank=False)
holding_date_start = models.DateTimeField(verbose_name='Дата и время начала заседания')
holding_date_end = models.DateTimeField(verbose_name='Дата и время окончания заседания')
creation_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания заявки')
enable = models.BooleanField(default=True, verbose_name='Активно')
history = HistoricalRecords()
def __str__(self):
return f"{self.purpose_of_use}"
class Meta:
ordering = ['pk']
verbose_name = 'Заседания'
verbose_name_plural = 'Заседания'
class Equipments(models.Model):
service = models.CharField(max_length=200, verbose_name='Оборудование', blank=False)
id_lecture_halls = models.ForeignKey('LectureHalls', on_delete=models.CASCADE, verbose_name='Для аудитории',
blank=False)
history = HistoricalRecords()
def __str__(self):
return f"{self.service}"
class Meta:
ordering = ['pk']
verbose_name = 'Оборудование'
verbose_name_plural = 'Оборудование'
class LectureHalls(models.Model):
hall_holding = models.CharField(max_length=100, verbose_name='Аудитория', blank=False)
history = HistoricalRecords()
def __str__(self):
return f"{self.hall_holding}"
class Meta:
ordering = ['pk']
verbose_name = 'Аудитории'
verbose_name_plural = 'Аудитории'
class Conditions(models.Model):
condition_holding = models.CharField(max_length=100, verbose_name='Состояние', blank=False)
history = HistoricalRecords()
def __str__(self):
return f"{self.condition_holding}"
class Meta:
ordering = ['pk']
verbose_name = 'Состояния'
verbose_name_plural = 'Состояния'
forms.py
class EventsForm(forms.ModelForm):
equipment = ModelChoiceField(queryset=Equipments.objects.all(), widget=forms.CheckboxSelectMultiple())
class Meta:
model = Events
fields = ['applicant', 'purpose_of_use', 'comment', 'equipment', 'lecture_hall', 'condition',
'holding_date_start', 'holding_date_end']
widgets = {
'applicant': forms.Select(attrs={'class': 'form-select',
'style': 'width: 300px;'}),
'purpose_of_use': forms.Textarea(attrs={'class': 'form-control',
'style': 'resize: none; width: 500px;',
'rows': '5'}),
'comment': forms.Textarea(attrs={'class': 'form-control',
'style': 'resize: none; width: 500px;',
'rows': '5'}),
'lecture_hall': forms.Select(attrs={'class': 'form-select',
'style': 'width: 300px;'}),
'condition': forms.Select(attrs={'class': 'form-select',
'style': 'width: 300px;'}),
'holding_date_start': forms.DateTimeInput(attrs={'class': 'form-control',
'style': 'width: 300px;'}),
'holding_date_end': forms.DateTimeInput(attrs={'class': 'form-control',
'style': 'width: 300px;'}),
}
views.py
def index(request):
all_events = Events.objects.all()
events = Events.objects.all()
get_event_purpose = Events.objects.only('purpose_of_use')
if request.GET:
event_arr = []
if request.GET.get('purpose_of_use') == "all":
all_events = Events.objects.all()
else:
all_events = Events.objects.filter(purpose_of_use__icotains=request.GET.get('purpose_of_use'))
for i in all_events:
event_sub_arr = {}
# event_sub_arr['title'] = i.event_name
start_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strptime("%Y-%m-%d %H:%M")
end_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strptime("%Y-%m-%d %H:%M")
event_sub_arr['start', 'title'] = start_date
event_sub_arr['end'] = end_date
event_arr.append(event_sub_arr)
return HttpResponse(dumps(event_arr))
# Create object model
if request.method == 'POST':
form = EventsForm(request.POST)
if form.is_valid():
form.save()
# Send E-mail
data = {
'applicant': form.cleaned_data['applicant'],
'purpose_of_use': form.cleaned_data['purpose_of_use'],
'comment': form.cleaned_data['comment'],
'equipment': form.cleaned_data['equipment'],
'lecture_hall': form.cleaned_data['lecture_hall'],
'condition': form.cleaned_data['condition'],
'holding_date_start': form.cleaned_data['holding_date_start'],
'holding_date_end': form.cleaned_data['holding_date_end'],
}
html_body = render_to_string('sendMail/sendMail.html', data)
msg = EmailMultiAlternatives(subject='Заявки от "Календарь ТУСУР"', to=['va.99.dim@tusur.ru'])
msg.attach_alternative(html_body, 'text/html')
msg.send()
# # # # # # # # # # # #
form = EventsForm()
# # # # # # # # # # #
context = {
'ev': events,
'form': form,
'get_event_purpose': get_event_purpose,
'events': all_events,
}
return render(request, 'home/home.html', context)
home.html
<div class="mx-4">
<div class="row">
<div class="col">
<div class="card" style="position: absolute; left: 0; width: 75%;">
<div class="card-body" id='calendar'></div>
</div>
</div>
<br>
<div class="mx-3">
<div class="col">
<div class="card" style="position: absolute; right: 0; width: 23%;">
<div class="card-body">
<h3>Создание заявки</h3>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Создать</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>