A.Raouf
A.Raouf

Reputation: 2320

How to redirect to different pages with one view

Now I have 6 buttons, Everyone will redirect to a page containing courses, this method is for one button,

Views.py

def categories_pages(request):
    if request.user.is_authenticated():
        courses = Course.objects.filter(
            published_date__lte=timezone.now(),
            categories__name__icontains="IT"
        ).order_by('published_date')
        context = {
            "courses": courses
        }
        return render(request, 'categories/categories-page.html', context)

template

{% for instances in courses %}
        <div class="col-sm-6 col-md-4">
        <div class="thumbnail">
          <img src="{{ instances.img }}" alt="{{ instances.name }}">
          <div class="caption">
            <h3>{{ instances.name }}</h3>
            <p>{{ instances.description }}</p>
            <p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
          </div>
        </div>
    {% endfor %}

This button for IT courses , what about Business, Languages, etc.. and it worked well but do I have to make different view for every button and all have same syntax or is there another way to make it in the same view ? Thanks

Upvotes: 0

Views: 72

Answers (1)

Shang Wang
Shang Wang

Reputation: 25559

You need to define your url to have the category as a named parameter, so your view would take that extra parameter and query for the course:

url:

url(r'^categories/(?P<course_name>\w+)/$', views.categories_pages)

views.py

def categories_pages(request, course_name):
    if request.user.is_authenticated():
        courses = Course.objects.filter(
            published_date__lte=timezone.now(),
            categories__name__icontains=course_name
        ).order_by('published_date')
        context = {
            "courses": courses
        }
        return render(request, 'categories/categories-page.html', context)

Upvotes: 1

Related Questions