0

I there, so i am trying to use DRF Unit testing and i am having some problems with the .post

I think it has something to do with the foreign keys i am using but i couldn't find any good examples.

Serializer:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ('password', 'id', 'username', 'email')
        write_only_fields = ('password',)

    def restore_object(self, attrs, instance=None):
        # call set_password on user object. Without this
        # the password will be stored in plain text.
        user = super(UserSerializer, self).restore_object(attrs, instance)
        user.set_password(attrs['password'])
        return user

class MultimediaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Multimedia


class SpaceSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    avatar = serializers.HyperlinkedRelatedField(view_name='multimedia-detail')
    contents = serializers.HyperlinkedRelatedField(
        many=True, view_name='multimedia-detail'
    )
    api_key = serializers.SerializerMethodField('get_api_token')

    class Meta:
        model = Space

models:

class UserProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    avatar = models.ForeignKey(
        'core.Multimedia', blank=True, null=True,
        related_name='user_profiles_avatares'
    )
    language = models.ForeignKey('core.Language', blank=True, null=True)
    birth_date = models.DateTimeField(blank=True, null=True)
    country = CountryField(blank=True, default='PT')
    about_me = models.TextField(blank=True, default='')
    facebook_token = models.TextField(blank=True, default='')
    space_themed_motivation = models.TextField(blank=True, default='')
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)
    last_login_on = models.DateTimeField(auto_now=True)


class Space(UserProfile):
    degree = models.CharField(max_length=200, blank=True)
    galleries = models.ManyToManyField('core.Gallery', blank=True, null=True)
    contents = models.ManyToManyField('core.Multimedia', blank=True, null=True)

So my body data that i use in this endpoint is:

def test_register_space(self):
    url = reverse('space-list')
    data = {
      "user": {
        "username": "blaya2", 
        "email": "[email protected]",
        "password": "blayablaya" 
      },
      "avatar": "http://localhost:8000/api/v1/multimedia/1/",
      "contents": [
        "http://localhost:8000/api/v1/multimedia/1/",
        "http://localhost:8000/api/v1/multimedia/2/" 
      ],
      "language": "PT",
      "birth_date": "2014-10-30T10:59:22Z",
      "country": "PT",
      "about_me": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
      "facebook_token": "CAALDUez5gFsBAHGZCsi1BOeKwc",
      "space_themed_motivation": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
      "created_on": "2014-10-30T10:59:30.556Z",
      "updated_on": "2014-10-30T11:30:00.717Z",
      "last_login_on": "2014-10-30T11:30:00.717Z",
      "degree": "Mestrado" 
    }

    response = self.client.post(url, data, format='json')
    print response.data

and then i call it using response = self.client.post(url, data, content_type='application/json') I have also tried json.dumps() with no luck. I am always getting a 400 status code.

when i do print response.data i get:

{'language': [u"Invalid pk 'PT' - object does not exist."], 'user': [{u'non_field_errors': [u'Invalid data']}], 'contents': [u'Invalid hyperlink - object does not exist.'], 'avatar': [u'Invalid hyperlink - object does not exist.']}

I understand i must have the links to point to, but i dont know the syntax to get this working.

Does anyone know how i can get this to work?

1
  • 1
    i know it has been a long time since you posted this, but did you ever figure out a solution? Commented Feb 24, 2016 at 2:06

2 Answers 2

2

400 status code implies that you have some bad data in your json. Maybe you're missing required field etc. You should try to print out response.content. If everything is OK, it will show you the object. Otherwise it shows the error message which should be more informative than 400.

Sign up to request clarification or add additional context in comments.

3 Comments

its definetly required fields as well, but the foreign keys dont seem to be working. i have updated my code above with models/serializers
One problem seems to be that you're giving 'PT' for language but it's expecting a hyperlink. This goes for 'language', 'user', 'avatar'.
whats the correct syntax i am supposed to use for hyperlinks when testing??
0

In tests you must serialize your JSON data with json.dumps.

response = self.client.post(url, json.dumps(data), content_type='application/json')

If this still doesn't work, you should check what the response contains. It should give you a more specific error message that will help you in solving your problem.

2 Comments

i there, i had tried this as well with no luck. I updated my post with the models/serializers. i am gettting {'language': [u"Invalid pk 'PT' - object does not exist."], 'avatar': [u'Invalid hyperlink - object does not exist.'], 'contents': [u'Invalid hyperlink - object does not exist.']} maybe because i im not setting the foreign keys properly but i am not sure how to do that
do you have an example with foreign keys??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.