Django-未应用于URL的模型对象的slug字段



我正在观看一个YouTube教程,该教程显示了如何在该对象的详细视图的URL中使用模型对象的ID,并试图将相同的概念应用于Slug字段通过用" slug"替换所有" ID"(我的模型slug字段的名称)。但是,这恰好引起了一个错误 -

noreversematch at/dashboard/for``活动'' 找不到参数'('',)'和关键字参数'{}'。1个模式 尝试:['(?i)仪表板/竞选/(?p/slug [ - w d] ) )/$']

views.py:

def campaign_detail(request, campaignprofile_slug):
    if request.user.is_authenticated:
        campaignprofile = get_object_or_404(CampaignProfile, slug=campaignprofile_slug)
        return render(request, 'campaign-detail.html', {'campaignprofile': campaignprofile, 'slug': slug})
    else:
        return redirect('/users/login/next?=')

urls.py:

url(r'^campaigns/(?P<slug>[-wd]+)/$', views.campaign_detail, name='campaign-detail')

models.py for我要显示的模型对象:

class CampaignProfile(models.Model):
    user = models.ForeignKey(UserModel, related_name='campaignprofile', on_delete=models.CASCADE, null=True)
    campaign_title = models.CharField(max_length=50, verbose_name='Title')
    slug = models.SlugField(unique=True, blank=True, null=True)

html模板a href标签:

<a href='{% url "campaign-detail" slug %}'></a>

对于此问题的任何潜在解决方案都会很棒。谢谢。

两件事:

1)您正在模板中的URL中传递的slug似乎是一个空字符串,并且您的urls.py中的代码无法处理导致错误的con字符串。

2)修复1后,您需要在urls.py的正则 slug变量中以与视图函数中的第二个参数相同的名称,以防止其他错误。

<</p>

看起来您在返回的上下文中使用了错误的变量名称;

return render(request, 'campaign-detail.html', {'campaignprofile': campaignprofile, 'slug': slug})

'slug': slug重命名为'slug': campaignprofile_slug

最新更新