3

I have this function,

def event (request):
    all_events = Quiz.objects.filter(owner_id=request.user.pk, status="Assigned")
    get_event_types = Quiz.objects.filter(owner_id=request.user.pk, status="Assigned")
    context = {"events": all_events, "get_event_types": get_event_types, }
    print("context is", context)
    return render(request, 'classroom/teachers/calendar.html', context)

and it runs fine if I pass the template as 'calendar.html'. It is supposed to draw a calendar, and also pass the context called events, which is then processed by a JavaScript function to populate the days with some data values.

This is my correct working calendar.html:

{% extends 'base.html' %}
{% load fullcalendar_tags %}

{% block content %}

{% for i in events %}
    {{ i }}
{% endfor %}


    {% calendar %}
    <script>

        $(document).ready(function () {

            var currentView = '',
                d = new Date(),
                today = d.getDay(),
                dow = 1;
            $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next',
                    center: 'title',
                    right: 'month,agendaWeek'
                },
                defaultDate: d,
                events: [
                    {% for i in events %}
                        {
                            title: "{{ i.weight}} Kg",
                            start: '{{ i.scheduled_date|date:"Y-m-d" }}',
                            end: '{{ i.scheduled_date|date:"Y-m-d" }}',

                        },
                    {% endfor %}],
                navLinks: true,
                firstDay: 1, //Monday
                viewRender: function (view) {
                    if (view && view.name !== currentView) {
                        if (view.name === 'agendaWeek') {
                            dow = today;
                        } else {
                            dow = 1;
                        }
                        setTimeout(function () {
                            $("#calendar").fullCalendar('option', 'firstDay', dow);
                        }, 10);
                    }
                    if (view) {
                        currentView = view.name;
                    }
                }
            });

        });

    </script>
{% endblock %}

This is rendering the context event just fine. But, when I try to pass this to another view, the {% calendar %} part is working just fine, but the context is not being sent at all. I have printed it a bunch of times, and for whatever reason it is not passing anything in the 'events' context.

I found a way to call the event function, from another view(not very sure if the best method available, but it seemed simple to execute).

def json_example1 (request):
    distinct_origin = Quiz.objects.filter(owner_id=request.user.pk).order_by().values_list('origin',
                                                                                           flat=True).distinct()
    distinct_o_list = list(distinct_origin)
    distinct_dest = Quiz.objects.filter(owner_id=request.user.pk).order_by().values_list('destination',
                                                                                         flat=True).distinct()
    distinct_d_list = list(distinct_dest)
    markers_list = list(set(distinct_o_list) | set(distinct_d_list))

    # print("markers", markers_list)

    gmaps = googlemaps.Client(key='AIzaSyArNLCXScd7tH0mwlDDPqXoVNgTT6emblI')
    latitude = list()
    longitude = list()
    for i in markers_list:
        geocode_result = gmaps.geocode(i)

        lat = geocode_result[0]["geometry"]["location"]["lat"]
        lon = geocode_result[0]["geometry"]["location"]["lng"]
        longitude.append(lat)
        latitude.append(lon)

    # print("lat", latitude)
    data = pd.DataFrame({'lat': latitude, 'lon': longitude, 'name': markers_list})
    m = folium.Map(location=[21, 78], tiles="OpenStreetMap", zoom_start=4.75)
    for i in range(0, len(data)):
        folium.Marker([data.iloc[i]['lon'], data.iloc[i]['lat']], popup=data.iloc[i]['name']).add_to(m)

    html_string = m._repr_html_()
    context = {'map2': html_string}

    # print("context is", context)

    def load_calendar (request):
        return event(request)

    load_calendar(request)  //Here I am loading the function

    return render(request, 'classroom/teachers/graph_tot_trucks.html', context)

Any clues ??

Rohit Kumar
  • 684
  • 2
  • 17
  • 39
  • @DanielRoseman Well, maybe because it is working?? I just add the code ``{% calendar %}`` in my other html file, and then load the view of that file, which contains the nested ``load_calendar`` function, and it renders the calendar just fine on that other html template. Maybe if you saw it working you'd believe it ? – Rohit Kumar Jul 08 '19 at 14:51
  • Er, what? You asked a question because this is not working. So what are you asking? – Daniel Roseman Jul 08 '19 at 15:03
  • Like it says in the question title, the calendar is working fine, but context data is not being sent. "Events" in this case... – Rohit Kumar Jul 08 '19 at 15:11
  • Yes. Which was what I was talking about, why did you think I meant anything else? Displaying the calendar does not depend on the nested function, only the events do. And there is no way that the code you have written could pass any events from that function to the context. – Daniel Roseman Jul 08 '19 at 15:15
  • 1
    Thanks! This was the constructive feedback I was looking for. I realised it is not possible, but I was able to do this by using an iframe, and it works perfectly fine, along with the context data. Your question "Why would you expect this to work ?" gave me the wrong idea, as I am a fellow coder asking for help in the coding community. This is what SO is for right @DanielRoseman ? – Rohit Kumar Jul 09 '19 at 05:07

1 Answers1

0

I was able to do this perfectly with an iframe. All context data is being passed just fine too. Weird, I never found any clue about this on SO or Google.

Rohit Kumar
  • 684
  • 2
  • 17
  • 39