在Django

时间:2019-01-11 15:13:42

标签: python django python-3.x django-models slug

我有一个Django项目,该项目围绕创建锦标赛并将特定对象嵌套在其中。例如,每个锦标赛都有多个委员会。当某人创建比赛时,我允许他们创建带有SlugField的链接。我的代码(到目前为止)如下:

models.py

from django.db import models
from django.utils.text import slugify

class Tournament(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, unique=True)

    def _get_unique_slug(self):
        '''
        In this method a unique slug is created
        '''
        slug = slugify(self.name)
        unique_slug = slug
        num = 1
        while Tournament.objects.filter(slug=unique_slug).exists():
            unique_slug = '{}-{}'.format(slug, num)
            num += 1
        return unique_slug

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = self._get_unique_slug()
        super().save(*args, **kwargs)

class Committee(models.Model):
    name = models.CharField(max_length=100)
    belongsTo = models.ForeignKey(Tournament, blank=True, null=True)
    slug = models.SlugField(max_length=50, unique=True)

    def _get_unique_slug(self):
        '''
        In this method a unique slug is created
        '''
        slug = slugify(self.name)
        unique_slug = slug
        num = 1
        while Committee.objects.filter(slug=unique_slug).exists():
            unique_slug = '{}-{}'.format(slug, num)
            num += 1
        return unique_slug

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = self._get_unique_slug()
        super().save(*args, **kwargs)

views.py

from django.shortcuts import render, get_object_or_404
from .models import Tournament, Committee

def tournament_detail_view(request, slug):
    tournament = get_object_or_404(Tournament, slug=slug)    
    return render(request, 'tournament/detail.html', {'tournament': tournament})

def committee_detail_view(request, slug): 
    committee = get_object_or_404(Committee, slug=slug)    
    return render(request, 'committee/detail.html', {'committee': committee})

urls.py

from . import views
from django.urls import path

app_name = 'tournament'
urlpatterns = [
    path('<slug:slug>/', views.tournament_detail_view),
]

我的问题与urls.py有关。如果用户创建了名为“ Zavala”的锦标赛,则他们当前可以访问example.com/zavala上的网站。但是,如果他们在上述比赛下创建了一个名为“ Cayde”的委员会,则他们无法访问位于example.com/zavala/cayde的委员会。问题是这两个子URL都是段子,而且我不确定Django是否可以使用此子URL。有没有一种方法可以创建允许用户去委员会的路径?我想过要创建一个函数来测试锦标赛是否存在,但不确定到底是怎么回事。有小费吗?我需要的是一个可行的解决方案。

1 个答案:

答案 0 :(得分:1)

我不确定你为什么认为不能有两个two。您可以:

urlpatterns = [
    path('<slug:slug>/', views.tournament_detail_view),
    path('<slug:tournament_slug>/<slug:committee_slug>/', views. committee_detail_view),
]

现在您的Committee_detail_view变为:

def committee_detail_view(request, tournament_slug, committee_slug): 
    committee = get_object_or_404(Committee, slug=committee_slug, belongsTo__slug=tournament_slug)    
    return render(request, 'committee/detail.html', {'committee': committee})