首页 文章

Python:NoReverseMatch错误:反向'detail',参数为'(UUID)',未找到关键字参数_652159 . 尝试了1种模式:django中的['']

提问于
浏览
0

我创建了一个模型'Post',其中我使用UUID而不是Django内置的自动生成ID . 在'Post'模型中,我定义了一个def get_absolute_url,以便我可以将它保存在我的模板中 . 当我试图获得交易页面时,它会引发错误:NoReverseMatch at / deal / Reverse for'defite'with arguments'(UUID('086d177f-9071-4548-b5db-1d329078853e'),)'和关键字参数'{}' 未找到 . 尝试了1种模式:['deal /(?P \ d)/ $'] . 我很感激帮助我解决这个问题 .

这是我的代码:

Models.py:

class Post(models.Model):
    post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    from1 = models.CharField(max_length=20)

    def __str__(self):
        return self.post_id

    def get_absolute_url(self):
        return reverse("detail", args=(self.post_id))

urls.py:

url(r'^deal/$', views.deal, name='deal'),
url(r'^deal/(?P<post_id>\d+)/$', views.post_detail, name='detail'),

Views.py:

def deal(request):
    queryset_list = Post.objects.active() #.order_by("-timestamp")
    if request.user.is_staff or request.user.is_superuser:
        queryset_list = Post.objects.all()
    context = {
        "object_list": queryset_list, 
        "post_id": "List",
    }
    return render(request, 'before_login/deal.html', context)

def post_detail(request, post_id=None):  
    instance = get_object_or_404(Post, post_id=post_id)
    if instance.date > timezone.now().date():
        if not request.user.is_staff or not request.user.is_superuser:
            raise Http404
    share_string = quote_plus(instance.Material_Type)
    context = {
        "from1": instance.from1,
        "instance": instance,
        "share_string": share_string
    }
    return render(request, "loggedin_load/post_detail.html", context)

deal.html:

{% for obj in object_list %}
    <tr>
      <td scope="row">{{obj.post_id}}</td>
      <td> <a href='{{ obj.get_absolute_url }}'>{{ obj.from1 }}</a>
</td> <td>{{obj.user}}</td> </tr> {% endfor %}

2 回答

  • 4

    您的UUID包含字母和连字符,但您的正则表达式仅匹配数字( \d+ ) . 您需要更改正则表达式以捕获字母和连字符:

    url(r'^deal/(?P<post_id>[\w-]+)/$', views.post_detail, name='detail'),
    
  • 0

    对于UUID,这是正则表达式

    url(r'^deal/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', views.post_detail, name='detail'),

相关问题