我'模仿'模型team_name
的{{1}}字段,以便空格在网址中显示得更漂亮。但是当我尝试切换你传递给URL的pk变量时,我得到一个slug的NoReverseMatch。它适用于Team
。
模型
team_name
观看次数+模板网址(这不起作用)
class Team(models.Model):
team_name = models.CharField(max_length=25, unique=True)
team_name_slug = models.SlugField(max_length=25, unique=True)
此作品
def team_public_profile(request, pk):
team = get_object_or_404(Team, team_name_slug=pk)
... other code
---
<form action="{% url 'team_public_profile' pk=team_name_slug %}">
答案 0 :(得分:1)
首先,您需要使用团队模型team_name_slug
方法使用django.utils.text.slugify
填充save()
,如:
from django.utils.text import slugify
class Team(models.Model):
...
def save(self, *args, **kwargs):
if self.team_name:
self.team_name_slug = slugify(self.team)
super(Team, self).save(*args, **kwargs)
您的网址应如下所示:
url(r'^teams/(?P<team_name_slug>[\w-]+)/$', views.team_public_profile, name='team_public_profile')
您的视图+模板:
def team_public_profile(request, team_name_slug):
team = get_object_or_404(Team, team_name_slug=team_name_slug)
... other code
<form action="{% url 'team_public_profile' team_name_slug=team_name_slug %}">