gpt4 book ai didi

python - Django:如何添加复选框?

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:54 26 4
gpt4 key购买 nike

我正在尝试在日历中的事件旁边添加一个复选框。我还希望它保存为用户保留的任何内容(选中/未选中)。

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})

class CalendarView(generic.ListView):
model = Event
template_name = 'cal/calendar.html'

def get_queryset(self):
qs = Event.objects.filter(user=self.request.user.id)
return qs

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
d = get_date(self.request.GET.get('month', None))
cal = Calendar(d.year, d.month)
cal.user = self.request.user
html_cal = cal.formatmonth(withyear=True)
context['calendar'] = mark_safe(html_cal)
context['prev_month'] = prev_month(d)
context['next_month'] = next_month(d)
return context

模型.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()

@property
def get_html_url(self):
url = reverse('cal:event_edit', args=(self.id,))
return f'<a href="{url}"> {self.title} </a>'

def __str__(self):
return '{} - {} by {}'.format(self.title, self.description, self.user)

Heres what my calendar looks like with an event added

enter image description here

最佳答案

您的事件模型中需要一个多对多字段,例如:

class Event(models.Model):
...
attending = models.ManyToManyField('User', blank=True)

https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_many/

您需要添加一个复选框:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox

如果用户选中该复选框,您可以发出发布请求来更新数据库。

如果用户选中该框,您只需更新/保存到数据库。

关于python - Django:如何添加复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55553182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com