找不到与参数'('1534691562.8842607',)'为'snippet_detail'反向匹配的NoReverseMatch

时间:2018-08-19 15:44:18

标签: django django-models django-forms django-views url-pattern

我正在尝试在Django应用程序中创建一个代码段。

创建代码段时出现以下错误

NoReverseMatch at / 
Reverse for 'snippet_detail' with arguments '('1534693093.896782',)' not found. 1 pattern(s) tried: ['(?P<snippet_slug>[\\d]+)$']

我无法找出问题所在。网址格式和视图中的所有内容看起来都不错。但是错误仍然存​​在。

django_project / urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('djangobin.urls'))
]

djangobin / urls.py

urlpatterns=[
    url(r'^$', views.index, name='index'),
    url('^(?P<snippet_slug>[\d]+)/$', views.snippet_detail, name='snippet_detail'),
]

djangobin / views.py

def index(request):
    if request.method=='POST':
        f=SnippetForm(request.POST)
        if f.is_valid():
            snippet=f.save(request)
            return redirect(reverse('djangobin:snippet_detail', args=[snippet.slug]))
    else:
        f=SnippetForm()
    return render(request, 'djangobin/index.html',{'form':f})

def snippet_detail(request, snippet_slug):
    snippet = get_object_or_404(Snippet, slug=snippet_slug)
    snippet.hits += 1
    snippet.save()
    return render(request, 'djangobin/snippet_detail.html', {'snippet': snippet})

这是代码段模型:

class Snippet(models.Model):
    title=models.CharField(max_length=100, blank=True)
    original_code=models.TextField()
    highlighted_code=models.TextField(help_text='Contains syntax highlighted code - Read only')
    expiration=models.CharField(max_length=10, choices=Pref.expiration_choices)
    exposure=models.CharField(max_length=10, choices=Pref.exposure_choices)
    hits=models.IntegerField(default=0, help_text='Read only field. Will be updated after every visit to snippet.')
    slug=models.SlugField(help_text='Read only field. Will be filled automatically.')
    created_on=models.DateTimeField(auto_now_add=True)

    language=models.ForeignKey(Language, on_delete=models.CASCADE)
    user=models.ForeignKey(User, on_delete=models.CASCADE)
    tags=models.ManyToManyField('Tag', blank=True)

    def highlight(self):
        formatter=HtmlFormatter(linenos=True)
        return highlight(self.original_code, self.language.get_lexer(), formatter)

    def __str__(self):
        # return self.language
        return (self.title if self.title else "Untitled")+" - "+self.language.name

    def get_absolute_url(self):
        return reverse('djangobin:snippet_detail', args=[self.slug])

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug=str(time.time()).replace(",","")
        self.highlighted_code=self.highlight()
        if not self.title:
            self.title="Untitled"
        super(Snippet, self).save(*args, **kwargs)

    class Meta:
        ordering=['-created_on']

1 个答案:

答案 0 :(得分:0)

您的网址格式仅接受数字,但您的子句中包含点。

您可以添加一个点:

url('^(?P<snippet_slug>[\d.]+)/$', 

尽管我不确定为什么您会使用时间戳记。