django - 将uuid传递给reverse()来构造url

标签 django django-urls

我有一个网址:

url(r'^profile_detail/(?P<uuid>%s)/$' % uuid, ProfileDetailView.as_view(), name="profile_detail_view")

我需要将用户重定向到该 View ,但我不知道如何在不对其进行硬编码的情况下构造 URL,这是我不想做的。

我想到了这样的事情:

reverse('profile_detail_view' 'profile.uuid')

我尝试了一些变体,但没有得到正确的结果。我还尝试了一些带有 args 和 kwargs 的东西,但没有任何结果。

我该怎么做?

最佳答案

urls.py
urls.py您只需定义匹配时调用给定 View 的模式。匹配的内容将作为命名参数传递给 View ,例如

url(
    r'^profile_detail/(?P<uuid>[\d\-]+)/$', 
    ProfileDetailView.as_view(), 
    name="profile_detail_view"
)

此模式将匹配数字 ( 0-9 ) 和连字符 ( - )(根据 uuid 您可以在分组和长度方面加强正则表达式)。

查看
然后,您的 View 有责任查找此 uuid 的用户。属于(或者如果未找到用户则引发错误),例如

class ProfileDetailView(View):
    def get(self, request, uuid):
        try:
            user = User.objects.get(uuid=uuid)
        except User.DoesNotExist:
            raise Http404  # or whatever else is appropriate

        # ...

倒车
通过将所有必要的内容传递给 reverse 来反转 View 。功能。 key 在kwargs需要匹配 url 模式中的命名正则表达式 (?P<uuid>[\d\-]+)

reverse('profile_detail_view', kwargs={'uuid': profile.uuid})

关于django - 将uuid传递给reverse()来构造url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29830348/

相关文章:

django - 反向未找到 : Sending Request Context in from templates

python - 在 Django 中使用信号创建 feed

django - 替换默认的表单的ManyToMany小部件

python - Urls.py 无法将 #(pound) 字符传递给 Django 中的 View ,

django admin - 覆盖单项模型的更改 ListView

python - urlpattern 的正则表达式

mysql - Django Admin 中的 PointField 使用 GeoDjango (DjangoUnicodeDecodeError)

django - 使用通用 View 的不区分大小写的查询

django - Tastypie:我想得到像 "/places/{PLACE_ID}/comments"这样的项目,但是怎么做?

python - NoReverseMatch : Reverse for 'complete' with arguments '(1,)' not found. 尝试了 1 个模式:['complete/<todo_id>' ]