gpt4 book ai didi

python - Django-Rest-Framework 关系和超链接 API 问题

转载 作者:太空狗 更新时间:2023-10-29 17:23:39 25 4
gpt4 key购买 nike

我正在试用 django-rest-framework。一切都很顺利,直到我进入教程的关系和超链接 API 部分。在稍微弄乱它之后我现在得到的错误是:

ImproperlyConfigured at /api/users/ "^\.(?P<format>[a-z0-9]+)\.(?P<format>[a-z0-9]+)$" is not a valid regular expression: redefinition of group name u'format' as group2; was group 1

我尝试对此进行一些研究,但似乎找不到任何东西,而且我越弄越乱

这是我的代码:

模块.py

class Home(models.Model):
user = models.ForeignKey(User)
#address ect

序列化器.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
username = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='home-detail')

class Meta:
model = User
fields = ('url', 'username', 'home')


class HomeSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
highlight = serializers.HyperlinkedIdentityField(view_name='home-highlight', read_only=True, format='html')

class Meta:
model = Home
fields = ('url', 'owner', 'postcode')

API.py

@api_view(('GET',))
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'homes': reverse('home-list', request=request, format=format)
})


class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer


class UserDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer


class HomeList(generics.ListCreateAPIView):
queryset = Home.objects.all()
serializer_class = HomeSerializer


class HomeDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Home.objects.all()
serializer_class = HomeSerializer


class HomeHighlight(generics.GenericAPIView):
queryset = Home.objects.all()
renderer_classes = (renderers.StaticHTMLRenderer,)

def get(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)

网址.py

urlpatterns = format_suffix_patterns([
url(r'^$', api.api_root),

url(r'^users/$',
api.UserList.as_view(),
name='user-list'),
url(r'^users/(?P<pk>[0-9]+)/$',
api.UserDetail.as_view(),
name='user-detail'),
url(r'^home/$',
api.HomeList.as_view(),
name='home-list'),
url(r'^home/(?P<pk>[0-9]+)/$',
api.HomeDetail.as_view(),
name='home-detail'),
url(r'^home/(?P<pk>[0-9]+)/highlight/$',
api.HomeHighlight.as_view(),
name='home-highlight')
])

urlpatterns += [
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
]

urlpatterns = format_suffix_patterns(urlpatterns)

最佳答案

你调用了 format_suffix_patterns 两次,所以 Django 不知道如何解析 URL,因为有两个 format 组。

您不需要第一次调用,因为第二次调用会为您处理(并允许 TokenAuthentication 仍然具有后缀)。

关于python - Django-Rest-Framework 关系和超链接 API 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27368024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com