是的,我知道有很多次问过类似的问题,但很抱歉,没有一个答案对我有帮助,或者我错过了一些重要的问题。
我希望在客户发布的数据格式为时进行注册:
{
"email": "asouausdhnsabnsmsd.s@s.com",
"first_name": "s",
"last_name": "d",
"password": "f"
}
和服务器返回:
{
"results": {
"email": "asouausdhnsabnsmsd.s@s.com",
"first_name": "s",
"last_name": "d"
}
}
当我发布数据时,我得到了:
在/ api / register处配置不正确无法解析URL 使用视图名称“customuser-detail”的超链接关系。你可以 未能在您的API中包含相关模型,或者不正确 在此字段上配置了
lookup_field
属性。
所以我有serializers.py之类的:
class RegisterUserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = CustomUser
fields = ('url', 'email', 'first_name', 'last_name', 'password')
write_only_fields = ('password',)
def create(self, validated_data):
user = CustomUser.objects.create(**validated_data)
try:
user.set_password(user.password)
user.save()
return user
except KeyError:
return user
class RegisterUserRetrieveSerializer(serializers.Serializer):
results = RegisterUserSerializer(source='*')
然后在views.py中的api viewsets:
class RegisterUserViewSet(mixins.CreateModelMixin,
viewsets.GenericViewSet):
permission_classes = (AllowAny,)
parser_classes = (parsers.JSONParser,)
serializer_class = serializers.RegisterUserSerializer
model = CustomUser
def create(self, request):
serializer = serializers.RegisterUserSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
user = serializer.save()
serializer = serializers.RegisterUserRetrieveSerializer(user, context={'request': request})
results = serializer.data
return Response(results, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
和urls.py:
router = routers.DefaultRouter()
router_without_trailing_slashes = routers.DefaultRouter(trailing_slash=False)
router.register(r'register', RegisterUserViewSet, base_name='customuser')
router_without_trailing_slashes.register(r'register', RegisterUserViewSet, base_name='customuser')
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^templates/', include('core.main.urls'), name='templates'),
url(r'^api/', include(router_without_trailing_slashes.urls)),
url(r'^api/', include(router.urls)),
]
新用户正确保存到db,因此我认为错误与RegisterUserRetrieveSerializer以某种方式连接。 有什么想法吗?
答案 0 :(得分:1)
看起来问题是您在序列化程序中包含url
字段,但DRF无法生成该URL,因为序列化程序没有详细信息视图。
有两种选择:
url
字段