tests.py
ジャンゴ休息フレームワーク: "「u'johnz" を割り当てることができません: "Message.authorは"
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase, APIClient, RequestsClient, APIRequestFactory
from rest_framework.authtoken.models import Token
from views import MessageListView
class CreateMessageTest(APITestCase):
def setUp(self):
self.client = APIRequestFactory()
self.user = User.objects.create_user(username='johnz', first_name='John', last_name='Doe', email='[email protected]', password='johnny', id=3)
self.user.save()
self.token = Token.objects.create(user=self.user)
self.data = {"body": "I am sad", "author": self.user}
def test_loggedin_user_can_create_message(self):
header = {'HTTP_AUTHORIZATION': 'Token {}'.format(self.token)}
user_obj = User.objects.get(pk=self.user.pk)
request = self.client.post(reverse('message-list'), data=self.data, **header)
response = MessageListView.as_view()(request)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_anonymous_cant_create_message(self):
request = self.client.post(reverse('message-list'), data=self.data)
response = MessageListView.as_view()(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
"ユーザー" のインスタンスでなければなりませんトレースバック
Traceback (most recent call last):
File "/home/bkovacev/PycharmProjects/silver_logic_project/posts/tests.py", line 28, in test_loggedin_user_can_create_message
response = MessageListView.as_view()(request)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch
response = handler(request, *args, **kwargs)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/generics.py", line 243, in post
return self.create(request, *args, **kwargs)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 21, in create
self.perform_create(serializer)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 26, in perform_create
serializer.save()
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 902, in create
instance = ModelClass.objects.create(**validated_data)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/django/db/models/query.py", line 397, in create
obj = self.model(**kwargs)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/django/db/models/base.py", line 537, in __init__
setattr(self, field.name, rel_obj)
File "/home/bkovacev/envs/silver_logic_project_env/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 211, in __set__
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "u'johnz'": "Message.author" must be a "User" instance.
私は他の読んだことがありますこのようなスレッドは、適切なユーザーモデルを参照しているかどうかをチェックしています。
私は間違っていますか? self.client.post()
にformat='json'
を追加すると<User: john> is not JSON serializable
となります。だから私は何が間違っているのか分からない。
EDIT:
追加さmodels.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.contrib.postgres.fields import JSONField
class Message(models.Model):
"""
"""
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='messages'
)
created_at = models.DateTimeField(auto_now_add=True)
body = models.TextField(max_length=160)
sentiment = JSONField(blank=True, null=True)
def __str__(self):
return "%s, %s, %s" % (self.author, self.created_at, self.id)
EDIT 2(添加シリアライザおよびビュー) EDIT 3(適合シリアライザ) serializers.py
class MessageSerializer(serializers.HyperlinkedModelSerializer):
author = UserSerializer()
class Meta:
model = Message
fields = ('author', 'sentiment', 'created_at', 'body', 'url')
views.py
class MessageListView(generics.ListCreateAPIView):
"""
Class Based View that lists/creates Silver Logic(s)
"""
queryset = Message.objects.all()
serializer_class = MessageSerializer
permission_classes = (IsAuthenticatedOrReadOnly,)
pagination_class = PageNumberPagination
'Message'モデルを投稿できますか? – themanatuf
@ themanatufこんにちは、モデルを含むように編集 –
ビューとシリアライザを表示する必要があります。 –