17

I have a model which has following attributes

from django.db import models
class ApiLogs(models.Model):
    user_id = models.BigIntegerField(null=True)
    ip = models.CharField(max_length=16)
    user_agent = models.TextField(blank=True, null=True)
    client = models.CharField(max_length=50, blank=True, null=True)
    client_version = models.CharField(max_length=50, blank=True, null=True)
    token = models.TextField(blank=True, null=True)
    uri = models.CharField(max_length=200)
    method = models.CharField(max_length=20)

I have defined a serializer

from rest_framework import serializers
class ApiSerializer(serializers.Serializer):
    user_id = serializers.BigIntegerField( allow_null=True)
    ip = serializers.CharField(max_length=16)
    user_agent = serializers.TextField(allow_blank=True, allow_null=True)
    client = serializers.CharField(max_length=50, allow_blank=True, allow_null=True)
    client_version = serializers.CharField(max_length=50, allow_blank=True, allow_null=True)
    token = serializers.TextField(allow_blank=True, allow_null=True)
    uri = serializers.CharField(max_length=200)
    method = serializers.CharField(max_length=20)

But it is showing error somewhat like this

user_id = serializers.BigIntegerField( allow_null=True)
AttributeError: 'module' object has no attribute 'BigIntegerField'

for textfield

user_agent = serializers.TextField(allow_blank=True, allow_null=True)
AttributeError: 'module' object has no attribute 'TextField'

Now how to serialize this type of data.

Abhishek Sachan
  • 934
  • 3
  • 13
  • 26

3 Answers3

34

This is because the django rest framework's Serializer doesn't have a TextField. Where your model has a TextField you need to use a CharField in the serializer.

CharField A text representation. Optionally validates the text to be shorter than max_length and longer than min_length.

Corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField.

The documentation isn't as clear about BigIntegerFields from models, but this line for the source code shows that IntegerField is again what you have to use in the serializer.

e4c5
  • 52,766
  • 11
  • 101
  • 134
  • 2
    For those looking at this answer, the updated link (08 Mar 2018) for the relevant source code is [here](https://github.com/encode/django-rest-framework/blob/d2994e0596c3163ac970b29dad6a61485f938045/rest_framework/serializers.py#L841) – Nogurenn Mar 08 '18 at 09:22
5

For text field you can follow the following convention

your_variable_name = serializers.CharField(style={'base_template': 'textarea.html'})

Suggested in rest framework documentation.

  • What different between CharField() with no defined max_length and CharField(style={'base_template': 'textarea.html'}) in serializer? – Tùng Nguyễn Mar 05 '23 at 18:17
1

Replace TextField with CharField. Both have basically the same functionality, but serializers understand only the later.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83