重定向到具有自己唯一模板的模型的最佳方法是什么?

时间:2018-06-27 20:50:25

标签: python html django

我有一个由团队模型代表的独立团队组成的联赛。我要做的是在联赛首页(base.html)上列出球队,并让每个球队成为各自页面的链接,该页面由扩展base.html的不同模板表示。实现此目标的最佳策略是什么?如果我一个接一个地编写每个团队链接,就可以使它工作,但是如果尝试在base.html模板中使用for循环,就会遇到麻烦。在我保存模板并以某种方式重定向到该属性的模型中是否可以具有模板属性?

 # Team
 class Team(models.Model):
team_choices = TEAM_CHOICES
name = models.CharField(max_length=50, null=True, blank=True, choices=team_choices)
players = models.ManyToManyField('accounts.User', related_name='players', blank=True)
season = models.ManyToManyField('Season', related_name='team_seasons', blank=True)
city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True)
neighborhood = models.CharField(max_length=100, null=True, blank=True)
sponsor = models.CharField(max_length=100, null=True, blank=True)
about = models.TextField(null=True, blank=True)
credits = models.TextField(null=True, blank=True)
url = models.CharField(max_length=50, null=True, blank=True)
photo = models.ImageField(null=True, blank=True, upload_to='images')
video = models.FileField(null=True, blank=True, upload_to='videos')
date_created = models.DateField(auto_now_add=True)

class Meta:
    ordering = ['name', 'neighborhood', 'sponsor', 'about', 'credits']

def create(self):
    self.created_date = timezone.now()
    self.save()

def __str__(self):
    return self.name

def __getitem__(self,index):
    return self.name[index]

def __setitem__(self,index,value):
    self.name[index] = value

这些是我正在使用的相关视图:

 class League(generic.ListView):
     model = Team
     template_name = 'league.html'

     def get_queryset(self):
         t = Team.objects.filter()
         return t

 def team1(request):
    team = Team.objects.get(name='team1')
    return render(request, 'team/team1.html', {'team':team,})
    print (team.name)

 class team_redirect(View):
    template_name = 'home/base.html'
    def get(self, request):
        return HttpResponsePermanentRedirect(reverse('Get_team', args=(team.name,)))

 class Get_team(LoginRequiredMixin, DetailView):
     Model = Team

     def get_object(self, *args, **kwargs):
         team = get_object_or_404(Team, name=self.kwargs['name'])
         return team

我想让模板中的链接重定向到特定团队的主页和模板,但这是我遇到麻烦的地方。难以将正确的参数传递给网址。

 #Urls
    url(r'^league$', views.League.as_view(), name='league'),

           # Team Redirect
           url(r'^team_redirect$', views.team_redirect.as_view(), name='team_redirect'),

           # Get Team
           url(r'^team/(?P<team_name>\d+)/view$', views.Get_team.as_view(), name='get_team'),

0 个答案:

没有答案