Given the following code:(don't mind the Fields there're just for illustration)
Models
class UserModel(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
Fields
class CommonInfo(models.Model):
delete = models.BooleanField(default=False)
Fields
class MyModel(CommonInfo, UserModel):
my_name = models.CharField(max_length=50, blank=False, null=False)
Fields
Serializer
class MySerializer(views.APIView):
class Meta:
model = MyModel
fields = '__all__'
Views
class MyViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MySerializer
URLs
router.register(r'studio', MyViewSet, basename='studio')
This upside model, Serializer & Views use. I use in Django REST Framework. but when I call MyModel they give me an error.
Return the following error when API call:
init() takes 1 positional argument but 2 were given
Error stack
Internal Server Error: /studio/
Traceback (most recent call last):
File "/home/chetan/Workspace/PhotoLab/PhotoLab/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/chetan/Workspace/PhotoLab/PhotoLab/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/chetan/Workspace/PhotoLab/PhotoLab/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/chetan/Workspace/PhotoLab/PhotoLab/venv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/home/chetan/Workspace/PhotoLab/PhotoLab/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/chetan/Workspace/PhotoLab/PhotoLab/venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/chetan/Workspace/PhotoLab/PhotoLab/venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/chetan/Workspace/PhotoLab/PhotoLab/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/chetan/Workspace/PhotoLab/PhotoLab/venv/lib/python3.8/site-packages/rest_framework/mixins.py", line 45, in list
serializer = self.get_serializer(queryset, many=True)
File "/home/chetan/Workspace/PhotoLab/PhotoLab/venv/lib/python3.8/site-packages/rest_framework/generics.py", line 110, in get_serializer
return serializer_class(*args, **kwargs)
TypeError: __init__() takes 1 positional argument but 2 were given
[21/Mar/2021 13:15:33] "GET /studio/ HTTP/1.1" 500 99610
You are inheriting from APIView for you MySerializer class.
to fix that, inherit from ModelSerializer from Django rest framework serializers
from rest_framework import serializers
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__'
and everything should be resolved.
Related
Am starter in Django and tried CreateView class and got the following error: Am unable to find the issue. ListView and DetailView works fine.
Trace Log :
System check identified no issues (0 silenced).
July 20, 2022 - 22:38:33
Django version 3.2.12, using settings 'configs.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /task/create/
Traceback (most recent call last):
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 168, in get
return super().get(request, *args, **kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 32, in get_form
form_class = self.get_form_class()
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 101, in get_form_class
return model_forms.modelform_factory(model, fields=self.fields)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 563, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 261, in __new__
fields = fields_for_model(
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 150, in fields_for_model
opts = model._meta
AttributeError: type object 'Task' has no attribute '_meta
model :
class Task(models.Model):
user =models.ForeignKey(User,on_delete=models.SET_NULL,null=True,blank=True,related_name='usertasks')
title = models.CharField(max_length=200,blank=False, null=False)
description = models.TextField(null=True, blank=True)
complete = models.BooleanField(default=False)
create = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('task-app:task', kwargs={'pk': self.pk})
def __unicode__(self):
return self.title
class Meta:
ordering = ['-create']
view :
class TaskCreate(CreateView):
model = Task
# fields = "__all__"
fields = ('title', 'description')
# fields = ['title']#,'description','completed']
success_url= reverse_lazy('task-app:tasks')
Dear All the issue is Task is Key-word and so causing issue. I renamed the model as alltask and it fixed the issue. Though this is not faced by all, but can be useful if no solution found.
I'm using django-mptt to create a tree-like structure for my Section model. Unfortunately, when I go to serialize it with drf-writable-nested, I get an error. This error only occurs when the url field is added to the serializer.
Also, when I remove uuid from the custom lookup field, the error is just replaced with pk.
I found this: https://stackoverflow.com/a/55173445/9137820, but I'm not accessing any of the data directly, so I'm not sure how that could be the issue.
Code:
# models.py
class Section(MPTTModel, TimeStampedModel):
uuid = models.UUIDField(default=uuid_lib.uuid4, editable=False)
name = models.CharField(max_length=255, unique=True)
objects = TreeManager()
parent = TreeForeignKey('self', related_name='section_children', on_delete=models.CASCADE, null=True, blank=True)
# serializers.py
class SectionSerializer(UniqueFieldsMixin, WritableNestedModelSerializer):
children = serializers.ListField(source='get_children', child=RecursiveField())
class Meta:
model = Section
fields = ['url', 'uuid', 'name', 'children']
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
}
# views.py
class SectionDetail(generics.RetrieveUpdateDestroyAPIView, viewsets.GenericViewSet):
queryset = Section.objects.all()
serializer_class = SectionSerializer
lookup_field = 'uuid'
Traceback:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/rest_framework/mixins.py", line 75, in update
return Response(serializer.data)
File "/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py", line 548, in data
ret = super().data
File "/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py", line 515, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/usr/local/lib/python3.9/site-packages/rest_framework/fields.py", line 1661, in to_representation
return [self.child.to_representation(item) if item is not None else None for item in data]
File "/usr/local/lib/python3.9/site-packages/rest_framework/fields.py", line 1661, in <listcomp>
return [self.child.to_representation(item) if item is not None else None for item in data]
File "/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py", line 515, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/usr/local/lib/python3.9/site-packages/rest_framework/relations.py", line 399, in to_representation
url = self.get_url(value, self.view_name, request, format)
File "/usr/local/lib/python3.9/site-packages/rest_framework/relations.py", line 335, in get_url
lookup_value = getattr(obj, self.lookup_field)
Exception Type: AttributeError at /api/v1/sections/3b15cbda-f61e-4a00-89fb-817beed10b14/
Exception Value: 'collections.OrderedDict' object has no attribute 'uuid'
I did some digging and this is what I can find. Dictionaries and OrderedDicts don't save keys and values as class attributes. So you cant retrieve them using getattr(). You need to request a method or attribute like dict.keys() or dict.values() from the OrderedDict. You can't use a key name.
See this example:
from collections import OrderedDict
g = OrderedDict()
g['test'] = 1
g = getattr(g, 'values')
print(list(g())[0])
That works fine but if you changed
g = getattr(g, 'values')
to
g = getattr(g, 'test')
It produces the same error you're experiencing
i am trying to convert my existing project to the DRF . However im facing the error of :
: Object of type TransitionApproval is not JSON serializable
TransitionApproval object comees from a package called django-river. Here is my code:
class ProjectDetailSerializer(serializers.ModelSerializer):
requirements = CustomerRequirementSerializer(many=True)
transitionApproval = serializers.SerializerMethodField('get_transition_approval')
class Meta:
model = Project
fields = '__all__'
depth = 2
def get_transition_approval(self,project):
transitions = TransitionApproval.objects.filter(object_id=project.pk).filter(workflow__field_name='project_status')
print(transitions)
return transitions
My console prints :
<CTEQuerySet [<TransitionApproval: TransitionApproval object (1)>, <TransitionApproval: TransitionApproval object (2)>, <TransitionApproval: TransitionApproval object (3)>]>
Is there a good way to solve this? I have tried doing this :
class ProjectDetailSerializer(serializers.ModelSerializer):
requirements = CustomerRequirementSerializer(many=True)
transitionApproval = TransitionSerializer(many=True)
class Meta:
model = Project
fields = '__all__'
depth = 2
but it seems that 'transitionApproval' is not an attribute of Project. Im not sure how to resolve this.
Here is my detail page view
class SalesProjectDetailView(RetrieveAPIView):
queryset = SalesProject.objects.all()
serializer_class = SalesProjectDetailSerializer
edits:
I have taken the advise to pass the queryset through a serializer before returning it .
class TransitionApprovalSerializer(serializers.ModelSerializer):
class Meta:
model = TransitionApproval
fields = '__all__'
class ProjectDetailSerializer(serializers.ModelSerializer):
transitionApproval = serializers.SerializerMethodField('get_transition_approval')
class Meta:
model = Project
fields = '__all__'
depth = 2
def get_transition_approval(self,project):
transitions = TransitionApproval.objects.filter(object_id=project.pk).filter(workflow__field_name='project_status')
return TransitionApprovalSerializer(transitions).data
That however returns me an error of :
Traceback (most recent call last):
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-
packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\generics.py", line 208, in get
return self.retrieve(request, *args, **kwargs)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\mixins.py", line 56, in retrieve
return Response(serializer.data)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\serializers.py", line 562, in data
ret = super().data
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\serializers.py", line 529, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\fields.py", line 1905, in to_representation
return method(value)
File "C:\Users\dream\Desktop\crmReact\backend\backend\sales\api\serializers.py", line 205, in get_transition_approval
return TransitionApprovalSerializer(transitions).data
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\serializers.py", line 562, in data
ret = super().data
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\serializers.py", line 516, in to_representation
attribute = field.get_attribute(instance)
File "C:\Users\dream\Desktop\crmReact\backend\react_env\lib\site-packages\rest_framework\fields.py", line 487, in get_attribute
raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `object_id` on serializer `TransitionApprovalSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `CTEQuerySet` instance.
Original exception text was: 'CTEQuerySet' object has no attribute 'object_id'.
object_id is a field of the TransitionApproval object , but i think the serializer is taking the queryset as the object itself
You can get this error, because your get_transition_approval method returns queryset TransitionApproval.Querysets couldn't serialize to json directly. You must return serialized data from this method. You can create another serializer and serialize your data with this serializer like that:
class TransitionApprovalSerializer(serializers.ModelSerializer):#your new serializer
class Meta:
model = TransitionApproval
fields = [...]
class ProjectDetailSerializer(serializers.ModelSerializer):
....
def get_transition_approval(self,project):
transitions = TransitionApproval.objects.filter(object_id=project.pk).filter(workflow__field_name='project_status')
# you can serialize your data here
return TransitionApprovalSerializer(transitions).data
I created a model and used random generator for it. Thus, I had to use UserManager for that model. Wen I am using this model in views, I am getting the above error. I have done this multiple times and never got an error. I don't know what is wrong. Please help. Thanks in advance!
models
def unique_rand():
while True:
code = Inventory.objects.make_random_password(length=6, allowed_chars="1234567890")
if not Inventory.objects.filter(code=code).exists():
return code
class Inventory(models.Model):
premises = models.ForeignKey(Premises, on_delete = None)
item = models.CharField(max_length=255,blank=False,unique=True)
code = models.CharField(max_length=255, null=True, blank=True,default = unique_rand)
quantity = models.IntegerField(null = True, blank=True)
is_defected = models.BooleanField(default = False)
objects = UserManager()
def __str__(self):
return self.item
views
class Inventory(ListView):
model = Inventory
template_name = 'inventory.html'
def get_queryset(self):
pre = Premises.objects.get(userprofile__user = self.request.user)
queryset = Inventory.objects.filter(premises = pre)
return queryset
edit: here is the traceback
Internal Server Error: /operations/Inventory/
Traceback (most recent call last):
File "/home/urvi/qwenv/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/urvi/qwenv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/urvi/qwenv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/urvi/qwenv/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/urvi/qwenv/local/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/urvi/qwenv/local/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/home/urvi/qwenv/local/lib/python3.6/site-packages/django/views/generic/list.py", line 142, in get
self.object_list = self.get_queryset()
File "/home/urvi/Desktop/atventus-work-spaces/operations/views.py", line 34, in get_queryset
queryset = Inventory.objects.filter(premises = pre)
AttributeError: type object 'Inventory' has no attribute 'objects'
[07/Aug/2019 18:28:06] "GET /operations/Inventory/ HTTP/1.1" 500 90758
[07/Aug/2019 18:28:06] "GET /favicon.ico HTTP/1.1" 200 5670
I have already imported models and Usermanager.
You've called your view the same name as the model. Rename the view.
I am trying to restify my backend using django-rest-gis, in such a way that POST request adds data to database and GET request lists down the data. However, I am getting following error:-
Internal Server Error: /api/
Traceback (most recent call last):
File "/home/vineet/env-tsl/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/generics.py", line 241, in get
return self.list(request, *args, **kwargs)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/mixins.py", line 48, in list
return Response(serializer.data)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework_gis/serializers.py", line 20, in data
return super(ListSerializer, self).data
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework_gis/serializers.py", line 28, in to_representation
("features", super(GeoFeatureModelListSerializer, self).to_representation(data))
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 686, in to_representation
self.child.to_representation(item) for item in iterable
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 686, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework_gis/serializers.py", line 100, in to_representation
fields = list(self.fields.values())
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 363, in fields
for key, value in self.get_fields().items():
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 1031, in get_fields
field_names, declared_fields, extra_kwargs
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 1378, in get_uniqueness_extra_kwargs
field_names, declared_fields, extra_kwargs
File "/home/vineet/env-tsl/lib/python3.6/site-packages/rest_framework/serializers.py", line 1450, in _get_model_fields
if field_name in declared_fields:
TypeError: unhashable type: 'list'
[25/May/2019 04:48:29] "GET /api/ HTTP/1.1" 500 147185
I have followed many answers on stackoverflow but could only get that it comes when you have a mutable type as key in dictionary
models.py
from django.contrib.gis.db import models
# Create your models here.
class test1(models.Model):
date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
location = models.PointField(blank=False)
plg = models.PolygonField(srid=4326, geography=True, null=True, blank=True)
city = models.CharField(max_length=50, blank=False)
state = models.CharField(max_length=50, blank=False)
def __str__(self):
return "%s" % (self.state)
serializers.py
from rest_framework_gis.serializers import GeoFeatureModelSerializer
from .models import test1
class test1Serializer(GeoFeatureModelSerializer):
class Meta:
model = test1
geo_field = ['location','plg']
auto_bbox = True
id_field = False
fields = ('city','state')
views.py
from .models import test1
from .serializers import test1Serializer
from rest_framework.generics import ListCreateAPIView
class test1SerializerCreate(ListCreateAPIView):
serializer_class = test1Serializer
queryset = test1.objects.all()
GeoFeatureModelSerializer only takes one field and it doesn't take the list, check with one field and it should work. Use Rest for multiple fields and you can parse in views. Or you can make a new GeometrySerializerMethodField field and return two geometry in that
geo_field cannot be list.
It can be this way:
class test1Serializer(GeoFeatureModelSerializer):
m_geo_field = GeometrySerializerMethodField()
def get_m_geo_field(self, obj):
return # do whatever you like
class Meta:
model = Location
geo_field = 'm_geo_field'