我有选择字段。我想要这样的views.py; 我该怎么办?
if gametype == 1:
template='xxx.html'
if gametype == 2:
template='xxx1.html'
views.py
def game_detail(request,tournamentslug,slug,gameslug):
game=get_object_or_404(Model,tournament__slug=tournamentslug,slug=slug,game__slug=gameslug)
context={
'game':game,
}
return render(request,'esports/lolgame.html',context)
models.py
class Model(models.Model):
type_tvt = 1
type_pvp = 2
type_royale=3
types = (
(type_tvt, 'T'),
(type_pvp, 'P'),
(type_royale,'R'),
)
gametype=models.SmallIntegerField(choices=types)
答案 0 :(得分:1)
假设您有一个基于类的详细信息视图(出于完整性考虑,该模型被命名为Game
,而不是示例中的Model
),
class GameView(generic.DetailView):
model = Game
def get_template_names(self):
if self.object.gametype == Game.type_tvt:
return ['xxx.html']
elif self.object.gametype == Game.type_pvp:
return ['xxx2.html']
elif self.object.gametype == Game.type_royale:
return ['xxx3.html']
raise ValueError('invalid game type')
可以解决问题–或简化使用字典的方法,
class GameView(generic.DetailView):
model = Game
template_names = {
Game.type_tvt: 'xxx.html',
Game.type_pvp: 'xxx2.html',
Game.type_royale: 'xxx3.html',
}
def get_template_names(self):
return [self.template_names[self.object.gametype]] # may raise KeyError
编辑:对于基于功能的视图,如在已编辑的问题中一样,
template_names = {
Model.type_tvt: "xxx.html",
Model.type_pvp: "xxx2.html",
Model.type_royale: "xxx3.html",
}
def game_detail(request, tournamentslug, slug, gameslug):
game = get_object_or_404(
Model,
tournament__slug=tournamentslug,
slug=slug,
game__slug=gameslug,
)
context = {"game": game}
template_name = template_names[game.gametype]
return render(request, template_name, context)