Reputation: 1
I am quite new to Django and am currently building an app to display a calendar using Django. I've been following the tutorial here but I can't make the previous and next month button to work. When I go to http://127.0.0.1:8000/calendar I can see this month's calendar, but when I press previous / next month nothing happens, only the url changes to http://127.0.0.1:8000/calendar/?month=[this_year]-[this_month+/-1] Here is my View Class:
class CalendarView(generic.ListView):
model = Event
template_name = 'calendar.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
d_obj = get_date(self.request.GET.get('day', None))
cal = Calendar(d_obj.year, d_obj.month)
html_cal = cal.formatmonth(withyear=True)
context['calendar'] = mark_safe(html_cal)
d_obj = get_date(self.request.GET.get('month', None))
context['prev_month'] = prev_month(d_obj)
context['next_month'] = next_month(d_obj)
return context
def get_date(req_day):
if req_day:
year, month = (int(x) for x in req_day.split('-'))
return datetime(year, month, day=1)
return datetime.today()
def prev_month(d_obj):
first = d_obj.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_obj):
days_in_month = calendar.monthrange(d_obj.year, d_obj.month)[1]
last = d_obj.replace(day=days_in_month)
next_month = last + timedelta(days=1)
month = 'month=' + str(next_month.year) + '-' + str(next_month.month)
return month
I'm using Django 2.2 so I did a few changes to the urls:
urlpatterns = [
path('calendar/', views.CalendarView.as_view(), name='calendar')
]
And this is the body part of the calendar.html file:
<div class="clearfix">
<a class="btn btn-info left" href="{% url 'calendar' %}?{{ prev_month }}"> Previous Month
</a>
<a class="btn btn-info right" href="{% url 'calendar' %}?{{ next_month }}"> Next Month
</a>
</div>
{{ calendar }}
Is there something that I'm doing wrong around here?
Upvotes: 0
Views: 791
Reputation: 11
I know this is a bit late but for anyone else stuck on this problem here is the issue in the code above:
class CalendarView(generic.ListView):
model = Event
template_name = 'calendar.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
**d_obj = get_date(self.request.GET.get('month', None))**
cal = Calendar(d_obj.year, d_obj.month)
html_cal = cal.formatmonth(withyear=True)
context['calendar'] = mark_safe(html_cal)
context['prev_month'] = prev_month(d_obj)
context['next_month'] = next_month(d_obj)
return context
Upvotes: 1