简体   繁体   中英

calling a Django view function from django HTML template

I'm trying to call the last function in this code (def get_level_msg():)

   class ProductDetailView(ProductView):
model = EnrollableTemplate

@functional.cached_property
def location(self):
    return get_object_or_404(
        Location.actives, slug=self.kwargs['location_slug'])

def get_object(self):
    return get_object_or_404(
        EnrollableTemplate, slug=self.kwargs['product_slug'])

def get_template_names(self):
    if self.get_object().category.language:
        return 'pdp_language.html'
    return 'immersion_pdp.html'

def get_faqs(self):
    object = self.get_object()
    if object.is_workshop:
        return c.faqs['workshop']
    elif object.category.language:
        return c.faqs['language']
    else:
        return c.faqs['immersion']

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    template = kwargs[self.context_object_name]

    # only display upcoming classes that have open seats available
    courses = (template.enrollable_set
               .upcoming()
               .select_related('template', 'venue__location')
               .filter(venue__location=self.location)
               .order_by('start_date'))

    loc_filter = self.request.GET.get('neighborhood')
    context['language'] = language = template.category.language

    if not self.object.is_workshop:
        sessions = [enrollable.session_count for enrollable
                    in self.object.enrollable_set.upcoming()]
        if sessions:
            context['max_sessions'] = max(sessions)

    neighborhoods = (Venue.objects.filter(location=self.location)
                                  .filter(enrollable__in=courses)
                                  .distinct()
                                  .values_list('neighborhood', flat=True))
    if loc_filter:
        courses = courses.filter(course__venue__neighborhood=loc_filter)
        context['filtered'] = True

    location_filters = [('?neighborhood={}'.format(n), n) for
                        n in neighborhoods.iterator()]
    path = urlparse(self.request.get_full_path()).path
    location_filters.insert(0, ('{}#filter'.format(path), "all"))
    context['filters'] = [('Location', location_filters)]

    if language:
        context['featured_teachers'] = self.get_featured_teachers(
            self.location, language)
    else:
        try:
            context['featured_teachers'] = [courses[0].teacher]
        except IndexError:
            context['featured_teachers'] = None

    context['expectations'] = template.expectation_set.all()
    context['faqs'] = self.get_faqs()
    context['courses'] = courses
    context['template_id'] = template.id
    # import ipdb; ipdb.set_trace()
    if courses.exists():
        course = courses[0]
        days_per_week = sum(1 for x in course.schedule if x is True)
        if days_per_week == 1:
            days_per_week = 'once'
        elif days_per_week == 2:
            days_per_week = 'twice'
        else:
            days_per_week = 'every day'
        context['days_per_week'] = days_per_week


    weeks = (course.start_date - course.end_date).days
    context['weeks_per_course'] = abs(int(weeks / 7))
    context['has_book'] = course.template.books.count() > 0
    context['first_start_date'] = course.start_date
    context['hello'] = template.level
    level_message1 = "Beginner Course"
    level_message2 = "Intermediate Course"
    level_message3 = "Advanced Course"
    level_message4 = "Beginner Intensive"

    # context['get_level_msg'] = 
    def get_level_msg():
        if template.level == 1:
            return level_message1
        elif template.level == 2:
            return level_message1
        elif template.level == 3:
            return level_message1
        elif template.level == 4:
            return level_message2
        elif template.level == 5:
            return level_message2
        elif template.level > 5:
            return level_message3
        else:
            return level_message4

into this HTML template

    <h4 class="t2">{{ weeks_per_course }} WEEK {{ ProductDetailView.get_level_msg }}<!-- BEGINNER INTENSIVE --></h4>

using examples i've found on the web, where it said I should first use the model, in this case its ProductDetailView. I'm 3 days into django and still don't understand how to do this! Can someone help me reach a conclusion? Thanks!

I don't understand why you want a function here at all, or why you want it to be called from the template. This value depends only on another value within get_context_data ; you should just use a basic if statement within that method.

...
level_message1 = "Beginner Course"
level_message2 = "Intermediate Course"
level_message3 = "Advanced Course"
level_message4 = "Beginner Intensive"

if template.level == 1:
    lvl = level_message1
elif template.level == 2:
    lvl = level_message1
elif template.level == 3:
    lvl = level_message1
elif template.level == 4:
    lvl = level_message2
elif template.level == 5:
    lvl = level_message2
elif template.level > 5:
    lvl = level_message3
else:
    lvl = level_message4

context['get_level_msg'] = lvl

Now you can refer to {{ get_level_msg }} directly in your template, just as you do with any other value.

(I doubt that template is actually what you expect, or even present at all, though; I suspect you should be using self.object .)

I realized I wasn't approaching this problem correctly, here's what i did to fix it:

t_level = template.level

    if t_level == 1:
            t_level = level_message1
    elif t_level == 2:
            t_level =  level_message1
    elif template.level == 3:
            t_level = level_message1
    elif template.level == 4:
            t_level = level_message2
    elif template.level == 5:
            t_level = level_message2
    elif template.level == 6:
            t_level = level_message3
    elif template.level == 7:
            t_level = level_message3
    else:
            t_level = level_message4
    context['t_level'] = t_level

I was making this a function when in fact, that wasn't necessary so i rewrote it so i would be able to call it into my template with context

<h4 class="t2">{{ weeks_per_course }} WEEK {{ t_level }}</h4>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM