I want to add a link to a calendar, so every single day will have a link to the day page, as you can see from the urls.py every link is already generate dynamically.
When in html you show the HTMLCalendar {{ cal | safe }} you can see the days, but how can i add a link to every single day? I've been trying a for loop with no success for the last two days. Happy to buy a box of beer to anybody who will help me
from django.urls import path
from dayplanner import views
app_name = 'dayplanner'
urlpatterns = [
#Day Planner Home Page
path('', views.dayplanner, name='dayplanner'),
path('<int:year>/<str:month>/<int:day>', views.dayplanner, name='dayplanner'),
]{% extends 'core/base.html' %}
{% block content %}
<div style="max-width: 500px; margin-left: 20%;">
{{ cal | safe }}
</div>
{% endblock %}from django.shortcuts import render
import calendar
from calendar import HTMLCalendar
from datetime import datetime
from datetime import datetime as date
def dayplanner(request, year=datetime.now().year, month=datetime.now().strftime('%B'), day=datetime.now().strftime('%A')):
# Capitalize the title
month = month.title()
# Shows the month number
month_number = list(calendar.month_name).index(month)
# This is the Calendar object
cal = HTMLCalendar().formatmonth(year, month_number)
# Generate links to each day in the calendar
day_links = ''
for day_number in range(1, calendar.monthrange(year, month_number)[1] + 1):
day_links += f'<a href="/{year}/{month}/{day_number}/">{day_number}</a> '
# Shows the current date
now = datetime.now()
return render(request, 'home.html', {
"cal":cal,
})
You can modify the HTML generated by the HTMLCalendar to include the links to each day. Here's an example of how you can modify your dayplanner view function to include the links:
pythondef dayplanner(request, year=datetime.now().year, month=datetime.now().strftime('%B'), day=datetime.now().strftime('%A')):
# Capitalize the title
month = month.title()
# Shows the month number
month_number = list(calendar.month_name).index(month)
# This is the Calendar object
cal = HTMLCalendar().formatmonth(year, month_number)
# Generate links to each day in the calendar
day_links = ''
for day_number in range(1, calendar.monthrange(year, month_number)[1] + 1):
link = f'<a href="{year}/{month.lower()}/{day_number}/">{day_number}</a> '
day_links += cal.replace(str(day_number), link, 1)
return render(request, 'home.html', {
"cal": day_links,
})
This code will generate the links for each day and replace the day number with the link in the HTML generated by the HTMLCalendar. You can then output the modified HTML in your template with {{ cal | safe }}. Note that the replace method used here replaces only the first occurrence of the day number in the HTML, so it won't affect any other instances of the same number in the calendar (e.g. the day name header).
Comments
Post a Comment