我有一个日历应用程序,该应用程序具有Event
,title
,description
,start_time
,end_time
字段的choices
类。我通过两个选择添加了choices
字段
c =[("1", "経理部"), ("2", "管理部")]
我还为此类向User
模型添加了一列
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)
我可以使用此代码访问该部门field
>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username='marcel4')
>>> d = u.employee.department
>>> print(d)
>>> 経理部
我只是想在日历应用程序中选择“ with理部”保存一个帖子(事件),并且只能使用将department
设置为“経理部”(相同的)的帐户才能看到该帖子。我应该改变吗? (例如if
左右
这是我的密码
日历中的模型
class Event(models.Model):
c =[("1", "経理部"), ("2", "管理部")]
title = models.CharField(max_length=100)
description = models.TextField()
start_time = models.DateTimeField(default='2019-06-18T16:00')
end_time = models.DateTimeField(default='2019-06-18T17:00')
choices = models.CharField(max_length=1, choices=c)
@property
def get_html_url(self):
url = reverse('cal:event_edit', args=(self.id,))
return f'<a href="{url}"> {self.title} </a>'
日历中的观看次数
class CalendarView(LoginRequiredMixin, generic.ListView):
model = Event
template_name = 'cal/calendar.html'
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)
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
def get_date(req_month):
if req_month:
year, month = (int(x) for x in req_month.split('-'))
return date(year, month, day=1)
return datetime.today()
def prev_month(d):
first = d.replace(day=1)
prev_month = first - timedelta(days=1)
month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month)
return month
def next_month(d):
days_in_month = calendar.monthrange(d.year, d.month)[1]
last = d.replace(day=days_in_month)
next_month = last + timedelta(days=1)
month = 'month=' + str(next_month.year) + '-' + str(next_month.month)
return month
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():
form.save()
return HttpResponseRedirect(reverse('cal:calendar'))
return render(request, 'cal/event.html', {'form': form})
日历中的实用程序
class Calendar(HTMLCalendar):
weekday = (u'月', u'火', u'水', u'木', u'金', u'<a style="color:#a4d2ff;">土</a>', u'<a style="color:#ff9999;">日</a>')
def __init__(self, year=None, month=None):
self.year = year
self.month = month
super(Calendar, self).__init__()
# formats a day as a td
# filter events by day
def formatday(self, day, events):
events_per_day = events.filter(start_time__day=day)
d = ''
for event in events_per_day:
d += f'<li> {event.get_html_url} </li>'
if day != 0:
return f"<td style='color:#4b4b4b;'><span class='date'>{day}</span><ul> {d} </ul></td>"
return '<td style="background-color:#bababa;";></td>'
# formats a week as a tr
def formatweek(self, theweek, events):
week = ''
for d, weekday in theweek:
week += self.formatday(d, events)
return f'<tr> {week} </tr>'
# formats a month as a table
# filter events by year and month
def formatmonth(self, withyear=True):
events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month)
cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n'
cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n'
if "January" in cal:
cal = cal.replace('January', '1月')
if "February" in cal:
cal = cal.replace('February', '2月')
if "March" in cal:
cal = cal.replace('March', '3月')
if "April" in cal:
cal = cal.replace('April', '4月')
if "May" in cal:
cal = cal.replace('May', '5月')
if "June" in cal:
cal = cal.replace('June', '6月')
if "July" in cal:
cal = cal.replace('July', '7月')
if "August" in cal:
cal = cal.replace('August', '8月')
if "September" in cal:
cal = cal.replace('September', '9月')
if "October" in cal:
cal = cal.replace('October', '10月')
if "November" in cal:
cal = cal.replace('November', '11月')
if "December" in cal:
cal = cal.replace('December', '12月')
cal += f'{self.formatweekheader()}\n'
for week in self.monthdays2calendar(self.year, self.month):
cal += f'{self.formatweek(week, events)}\n'
return cal
def formatweekday(self, theday):
return u'<th>%s</th>' % self.weekday[theday]
日历中的表格
class EventForm(ModelForm):
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'),
'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
}
fields = '__all__'
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',)
self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',)
self.fields['title'].label = "タイトル"
self.fields['description'].label = "内容"
self.fields['start_time'].label = "エベントの開始時間"
self.fields['end_time'].label = "エベントの終了時間"
self.fields['choices'].label = "Choise"
instance = getattr(self, 'instance', None)
if instance and instance.pk:
self.fields['title'].widget.attrs['readonly'] = True
self.fields['title'].label = "タイトル"
self.fields['description'].widget.attrs['readonly'] = True
self.fields['description'].label = "内容"
self.fields['start_time'].widget.attrs['readonly'] = True
self.fields['start_time'].label = "エベントの開始時間"
self.fields['end_time'].widget.attrs['readonly'] = True
self.fields['end_time'].label = "エベントの終了時間"