#python #django #forms #checkbox #model
#python #django #формы #флажок #Модель
Вопрос:
Я новичок в django, и я пытаюсь заставить свой календарь отображать сам флажок, а не значение True / False. Однако я могу получить данные для сохранения из формы
models.py
class Event(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField(max_length=350)
start_time = models.DateTimeField()
#end_time = models.DateTimeField()
event_checked = models.BooleanField()
@property
def get_html_url(self):
url = reverse('cal:event_edit', args=(self.id, ))
return f'<a href="{url}"> <label> {self.title} {self.event_checked}<label></a>'
def __str__(self):
return '{} - {} by {}'.format(self.title, self.description, self.user)
forms.py
class EventForm(forms.ModelForm):
event_checked = forms.BooleanField()
class Meta:
model = Event
# datetime-local is a HTML5 input type, format to make date time show on fields
widgets = {
'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
}
fields = ('title', 'description', 'start_time')
def __init__(self, *args, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
# input_formats parses HTML5 datetime-local input to datetime field
self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',)
views.py
def event(request, event_id=None):
instance = Event()
if event_id:
instance = get_object_or_404(Event, pk=event_id)
else:
instance = Event()
form = EventForm(request.POST or None, instance=instance)
if request.POST and form.is_valid():
event = Event.objects.create(**form.cleaned_data, user=request.user)
print(event.title)
return HttpResponseRedirect(reverse('cal:calendar'))
return render(request, 'cal/event.html', {'form': form})
Ответ №1:
Я не знаю, было ли это вашей целью:
class EventForm(forms.ModelForm):
event_checked = forms.BooleanField()
class Meta:
model = Event
# datetime-local is a HTML5 input type, format to make date time show on fields
widgets = {
'event_checked' forms.CheckboxInput(), # <-- added this
'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
}
fields = ('title', 'description', 'start_time')
def __init__(self, *args, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
# input_formats parses HTML5 datetime-local input to datetime field
self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',)