我正在制作Django应用程序。我正在使用Django Rest Framework.models.py
class Info(models.Model):
username = custom_fields.NotEmptyCharField(max_length=100, unique=True)
email = models.EmailField()
password = custom_fields.NotEmptyCharField(max_length=100)
serializers.py是
class InfoSerializer(serializers.ModelSerializer):
created_time = serializers.DateTimeField(required=False)
updated_time = serializers.DateTimeField(required=False)
views.py是
class InfoViews(viewsets.ModelViewSet):
queryset = Info.objects.all()
serializer_class = InfoSerializer
def create(self, validated_data):
user = get_user_model(**validated_data)
user.set_password(validated_data['password'])
user.save()
urls.py是
urlpatterns = [
path('users/', views.InfoViews.as_view({
'get': 'list',
'post': 'create'
})),
]
当我发布新用户数据时,
user = get_user_model(**validated_data)
TypeError:**之后的get_user_model()参数必须是映射,而不是 发生请求错误
我搜索了create() argument after ** must be a mapping, not unicode,所以我发现也许有必要的东西不在serializer.py中但我真的无法理解如何解决这个问题。我的代码出了什么问题?我应该如何解决这个问题?
完全追溯
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch
response = handler(request, *args, **kwargs)
File "/opt/project/app/views.py", line 22, in create
user = User(**validated_data)
TypeError: ModelBase object argument after ** must be a mapping, not Request
答案 0 :(得分:1)
在创建用户之前调用get_user_model
方法获取User类:
User = get_user_model()
user = User(**validated_data)