我正在嘗試將表單提交給我的視圖:在 Trending.html 中:{% extends 'djangobin/base.html' %}{% load static %}{% load humanize %}{% block title %} Trending {{ lang.name }} Snippets - {{ block.super }}{% endblock %}{% block main %} <h5><i class="fas fa-chart-line"></i> Trending {{ lang.name }} Snippets</h5> <hr> <table class="table"> <thead> <tr> <th>Title</th> <th>Date</th> <th>Hits</th> <th>Language</th> <th>User</th> </tr> </thead> <tbody> {% for snippet in snippets %} <tr> <td><i class="fas fa-globe"></i> <a href="{{ snippet.get_absolute_url }}">{{ snippet.title }}</a> </td> <td title="{{ snippet.created_on }}">{{ snippet.created_on|naturaltime }}</td> <td>{{ snippet.hits }}</td> <td><a href="{% url 'trending_snippets' snippet.language.slug %}">{{ snippet.language }}</a></td> {% if not snippet.user.profile.private %} <td><a href="{{ snippet.user.profile.get_absolute_url }}">{{ snippet.user.username|title }}</a></td> {% else %} <td>-</td> {% endif %} </tr> {% empty %} <tr class="text-center"> <td colspan="4">There are no snippets.</td> </tr> {% endfor %} </tbody> </table>{% endblock %}在views.py中:from django.shortcuts import HttpResponse, render, redirect, get_object_or_404, reversefrom .forms import SnippetFormfrom .models import Language, Snippetdef trending_snippets(request, language_slug=''): lang = None snippets = Snippet.objects if language_slug: snippets = snippets.filter(language__slug=language_slug) lang = get_object_or_404(Language, slug=language_slug) snippets = snippets.all() return render(request, 'djangobin/trending.html', {'snippets': snippets, 'lang': lang})
2 回答

江戶川亂折騰
TA貢獻1851條經驗 獲得超5個贊
要匹配c-sharp
包含連字符的 ,您需要更改[\w]
為[-\w]
。
url('^trending/(?P<language_slug>[-\w]+)/$', views.trending_snippets, name='trending_snippets'),

慕沐林林
TA貢獻2016條經驗 獲得超9個贊
由于它是您要匹配的 slug 字段,因此您可以使用Django 提供的內置 slug 路徑轉換器通過使用path
而不是url
.
改變:
url('^trending/(?P<language_slug>[\w]+)/$', views.trending_snippets, name='trending_snippets'),
至:
path('trending/<slug:language_slug>)/', views.trending_snippets, name='trending_snippets'),
請注意,它slug:
匹配連字符、下劃線以及 ASCII 字母和數字。
url()
只是一個別名,re_path()
將來可能會被棄用,因此您應該相應地更改您的代碼。
添加回答
舉報
0/150
提交
取消