SepticReVo SepticReVo - 1 year ago 59
Python Question

Multiple Models on a Single View/Template in Django

Trying to incorporate 2 models into my "season" view/template on my django site. Currently, I get the following as a ValueError "The view webapp.views.season didn't return an HttpResponse object. It returned None instead." Not sure what I am doing wrong, but hoping someone can take a look.

from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView
from .models import Player, Season

def home(request):
seasons = Season.objects.order_by('sid')
return render(request, 'webapp/home.html', {'seasons': seasons})

def player(request, pk):
player = get_object_or_404(Player, pk=pk)
return render(request, 'webapp/player.html', {'player': player})

def season(ListView, pk):
model = Season
template_name = 'webapp/season.html'

def get_context_data(self, **kwargs):
context = super(season, self).get_context_data(**kwargs)
context['players'] = Player.objects.all()
return context

def seasons(request):
seasons = Season.objects.order_by('sid')
return render(request, 'webapp/seasons.html', {'seasons': seasons})

from django.conf.urls import url
from . import views

urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^player/(?P<pk>\d+)/$', views.player, name='player'),
url(r'^season/(?P<pk>\d+)/$', views.season, name='season'),
url(r'^seasons/$', views.seasons, name='seasons'),

It should be noted that I originally had a TypeError that said "season() got an unexpected keyword argument 'pk'" before I added the pk to the season argument. Any help is greatly appreciated! Thanks!

Answer Source

The views:home, player and seasons are Function Based Views, this is the old Django Views style. On the other hand, ListView is a Class Based View, a newer way to write views in Django. You are mixing both kind of views and that's a bad idea. No idea what your season view should do, but try something like:

def season(request, pk):
    season = get_object_or_404(Season, pk=pk) 
    return render(
        {'season': season, 'players': Player.objects.all()}