django:如何使用 django 在 url 标记中添加 slug 作为参数

django: how to add slug as arguments in url tag using django

我想像这样使用 django 在 url 中添加 slug <a href="{% url 'base:tutorial-page' p.slug p.slug2 %}" </a> 我真的不知道如何在 url 中传递双 slug 例如:我想访问html 页面,然后转到与 html.

相关的 教程 页面

得到-started.html

{% for p in prglangcat %}>
      {{ p.title }}
      <a href="{% url 'base:tutorial-page' p.slug p.slug %}"  </a>
{% endfor %}

强文本

def gettingStarted(request):
    prglangcat = ProgrammingLanguagesCategory.objects.all()
    context = {
        'prglangcat': prglangcat
    }
    return render(request, 'base/getting-started.html', context)

def programmingLanguageTutorial(request, prg_slug):
    prglangcat = ProgrammingLanguagesCategory.objects.get(slug=prglangcat_slug)
    prglangtut = ProgrammingLanguageTutorial.objects.get(slug=prg_slug, prglangcat=prglangcat)
    context = {

        'prglangtut': prglangtut
    }
    return render(request, 'base/tutorial-page.html', context)

models.py

class ProgrammingLanguagesCategory(models.Model):
    title = models.CharField(max_length=100)
    icon = models.ImageField(upload_to='programming-category', default="default.jpg")
    description = models.TextField(default="Learn ...")
    slug = models.SlugField(max_length=100, unique=True)

    def get_absolute_url(self):
        return reverse('programming-languages-category', args=[self.slug])

    def __str__(self):
        return self.title

class ProgrammingLanguageTutorial(models.Model):
    prglangcat = models.ForeignKey(ProgrammingLanguagesCategory, on_delete=models.CASCADE, null=True)
    slug = models.SlugField(max_length=10000, unique=True, null=True)
    title = models.CharField(max_length=10000)
    description = models.TextField(null=True)
    image = models.ImageField(upload_to='Tutorial Image', default="default.jpg", null=True)
    code_snippet = models.CharField(max_length=1000000000, null=True, blank=True)
    video_url = models.URLField(null=True)
    views = models.IntegerField(default=0)

    def __str__(self):
        return self.title

urls.py

app_name = 'base'

urlpatterns = [
        path('', views.index, name="index"),
        path('getting-started/', views.gettingStarted, name="getting-started"),
        path('getting-started/<slug:prglangcat_slug>/<slug:prg_slug>', views.programmingLanguageTutorial, name="tutorial-page"),
]

回溯

NoReverseMatch at /getting-started/
Reverse for 'tutorial-page' with no arguments not found. 1 pattern(s) tried: ['getting\-started/(?P<prglangcat_slug>[-a-zA-Z0-9_]+)/(?P<prg_slug>[-a-zA-Z0-9_]+)$']

您没有传递第二个参数:

def programmingLanguageTutorial(request, prg_slug):

你可以使用like关键字参数,它的接受方式相同,更明确的是哪个参数是哪个。

这样做:

<a href="{% url 'base:tutorial-page' prg_slug=p.slug prglangcat_slug=p.slug2 %}"  </a>