Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to save video and use it like I do with an image
I'm using django and I'm just wondering how to use video. <video class="video-fluid" style="max-width:100%; height: auto;" autoplay loop muted> <source src="https://mdbootstrap.com/img/video/Tropical.mp4" type="video/mp4" /> </video> how do I save video in my directory? where do I save it? in the media folder? and use static to call it like I do with images? -
Django: Form ModelMultipleChoiceField with annotated queryset
I´m trying to make a multiple choice field in a form. Instead of using the full queryset I want to annotate some values. The annotation productos_incluir = ProductosBase.objects\ .filter((Q(region__region__icontains="Argentina") | Q(region__region__icontains="Todas")) & Q(estatus_contenido__id__gt=2))\ .values("marca__marca", "producto", "packaging").annotate(variantes=Sum("producto"))\ .order_by("marca__marca", "producto", "packaging") The form field productos = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=productos_incluir, required=False) The view <div>{{ filter_form.productos }}</div> The result I get the list displayed in the view but I get the "Label" next to the checkbox like this: {'marca__marca': 'Cramer', 'producto': 'Cutter - Shark', 'packaging': 'Bolsa individual', 'variantes': 0.0} My desire What I want is to be able to show the labels without the field info. I guess it has to do with the queryset type change when annotating, but I can´t find how to show this. Cramer | Cutter - Shark Bolsa | individual Thanks in advance! -
redirect to API login page and get back token
I am amateur in web programming and I don't know if my question is stupish: I'm developing an app that uses an API (Trello API) to work and I don't know how to redirect user to Trello login page and and get back token to run my app using his/her account Trello Authorization manual: https://developers.trello.com/page/authorization -
Upload image whit Selenium and Python on Ubuntu 18.04
I have a problem... This is my code: upimage = ActionChains(webdriver).move_to_element( webdriver.find_element_by_class_name("button")) print ('open') sleep(5) upimage.send_keys("/home/user/Image/2.jpg") print ('selected') sleep(5) it open popup for choose file and print "open" after if print "selected" but not select and load any image!!! Whats' wrong? EDIT 1: I try with: upimage.send_keys("/home/user/Image/2.jpg").perform() no effect! -
MultiValueDictKeyError: 'content'
i'm going to make the todo list using django...i did some code...but it throws an multiplevaluekeyerror i tried c = request.POST.get('content', False) but it gives always as False value views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .models import TodoItem # Create your views here. def home(request): return render(request, 'home.html') def work(request): all_todo_items = TodoItem.objects.all() return render(request, 'work.html', {'all_items': all_todo_items}) def addTodo(request): c = request.POST['content'] new_item = TodoItem(content = c) new_item.save() return HttpResponseRedirect('/work/') def deleteTodo(request, todo_id): item_to_delete = TodoItem.objects.get(id=todo_id) item_to_delete.delete() return HttpResponseRedirect('/work/') work.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/work.css' %}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> <link rel="icon" href="{% static 'images/list.png' %}" type="image/png"> <title>Tasks</title> </head> <body> <div class="container justify-content-center wrap1"> <div class="text-center heading"> <p><u>write your everyday task here!!!<u></p> </div> </div> <ul style="list-style: none; color: #1b0573; font-weight: bold;" class="text-center"> {% for todo_item in all_items %} <li> <div class="row"> <div class="col-sm-6"> {{ todo_item.content }} </div> <div class="col-sm-2"> {{ todo_item.date_created }} </div> <div class="col-sm-1"> <form action="/deleteTodo/{{ todo_item.id }}" method="post" style="display: inline;"> {% csrf_token %} <div class="form-group"> <button class="btn btn-outline-danger"><i class="fas fa-trash"></i></button> </div> </form> </div> </li> {% endfor %} </ul> <div class="container"> … -
Data not being saved by form in Django
I have this form in Django: class MyForm(forms.ModelForm): key = forms.CharField() secret = forms.CharField() class Meta: model = MyModel fields = ("key", "secret") def save(self, commit=True): send = super(MyForm self).save(commit=False) if commit: send.save() return send And its model: class MyModel(models.Model): key = models.CharField(max_length=200) secret = models.CharField(max_length=200) def save(self): # ALL the signature super(MyModel, self).save() This is the view: def MyView(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): send = form.save(commit=False) send.save() messages.success(request, f"Success") else: form = MyForm() return render(request, "main/template.html", context={"form":form}) URL: path("MyView/", views.MyView, name="MyView"), The problem i keep having, is that the data submitted to the form is not being saved on my Database. When i use the form everything works, i don't get any errors, i get a Success from Django, but nothing happens on my DB. The only errors i'm getting are the following: [2019-08-02 18:22:38,279] log: WARNING - Not Found: /template/... And on Chrome: GET http://127.0.0.1:8000/apis/... 404 (Not Found) -
Automatically filled form in class-based view
I want to automatically fill some form in class-based view and save in database. post function in my view def post(self, request, *args, **kwargs): form_2 = self.form_class_2(self.request.POST) if form_2.is_valid(): keyword = form_2.cleaned_data['keyword'] books = self.search(keyword) if books: for book in books: title = self.add_title(book) form = self.form_class(initial={"title": title, }) if form.is_valid(): form.save() else: return HttpResponseRedirect(reverse_lazy('add_books')) return HttpResponseRedirect(reverse_lazy('import_books')) else: return HttpResponseRedirect(reverse_lazy('index_books')) return reverse_lazy('import_books') Basically I have 2 forms. form 2 is used to input value which is used as argument in my search function. then this search function return .json, then i took some value from this .json and assign to "title" then this title is my input data for form. And everything works fine until part with validation. My form isn't valid but when I print my form before validation part I see that my initial data is in form as expected. -
django can't run exiftool himself
I'm using exiftool in django project but it's seem can't run it . i dont know how i can found why because not any error hapen when i call process is using exiftool . but i think its about permission of users . when i run exiftool -j <image> in terminal all going well and i can see correct result but when i use below code to use exiftool in project ,the result shown me django can't run exiftool : cmd_get_meta = 'exiftool -j "{filename}"'.format(filename=absolute_file_path) process = subprocess.Popen(cmd_get_meta, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) raw_result = process.communicate() meta = json.loads(str(raw_result[0], 'utf-8'))[0] the error is : File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None so obvious that exiftool -j "{filename}" is not running by django. for more information i should tell this problem appear after i updated exiftool and i'm sure code is correct. django are running by uWSGi and here is user that running exiftool and uwsgi by : $ ps aux | grep uwsgi backend 1243 0.0 0.0 14224 988 pts/9 S+ 14:52 0:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn uwsgi www-data 20469 0.0 0.7 222664 63984 ? S 2018 32:55 /usr/bin/uwsgi --ini /usr/share/uwsgi/conf/default.ini --ini /etc/uwsgi/apps-enabled/hamclassy.ini … -
Django admin site is changed to normal html
Unfortunately my admin site got changed into a normal html site. I don't how it is happened. Did anyone came-across this problem and overcome of it. Actual result: Expected Result: -
How to display Changed Data in Django With AJAX
Actually am trying to make an cart for my website Now What i am trying to do is using Ajax i want to add and remove the item from my cart Here what i have done so far urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.cart_home, name = 'cart_home'), path('add/<int:product_id>', views.cart_add, name = 'cart_add'), path('delete/<int:product_id>', views.cart_delete, name = 'cart_delete'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And Here is my delete item from cart function in views.py def cart_delete(request, product_id): cart_id = request.session.get('cart_id') cart = Cart.objects.filter(id = cart_id ).first() ###REMOVING PRODUCT FROM CART########## cart.Product.remove(product_id) ################################### # GETTING TOTAL PRICE cart = Cart.objects.filter(id = cart_id).first() if cart is None: pass else: total = 0 for x in cart.Product.all(): total += x.price cart.total = total cart.save() print(total) return HttpResponse('Item Removed') and here is my Cart Model models.py class Cart(models.Model): User = models.ForeignKey(User, blank = True, null = True, on_delete = models.DO_NOTHING) Product = models.ManyToManyField(Product, blank = True,null = True) total = models.IntegerField(blank = True, null=True) sub_total = models.IntegerField(blank = True, null = True) created_at = models.DateField(auto_now=True) and now what i have done so far //Deleting Cart $(document).on('click','.cart_delete',function(e){ e.preventDefault() url = $(this).attr('href'); var p = $(this) $.ajax({ url: url, beforeSend: function(data){ $(".alert").html("<div class='alert alert-success' >Removing</div>") }, success: … -
How can you create an excel from a serialized model in DJANGO REST FRAMEWOK to be consumed (downloaded)
Good afternoon I have a query how I could generate an excel of a serialized model in DJANGO REST FRAMEWORK to be downloaded from a frontend (Angular). This excel I want to have the possibility that it has a filter, for example I want it to only bring me the records that have the P79COL01 equipment column in the property or property, in addition to other filters. My Model Interfaces class Interfaces(models.Model): id_interface=models.PositiveIntegerField(primary_key=True) id_EquipoOrigen=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_origen') id_PuertoOrigen=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_origen',null=True,blank=True) estatus=models.BooleanField(default=False) etiqueta_prtg=models.CharField(max_length=80,null=True,blank=True) grupo=models.PositiveSmallIntegerField(default=0,blank=True) if_index=models.PositiveIntegerField(default=0,blank=True) bw=models.PositiveSmallIntegerField(default=0,blank=True) bw_al=models.PositiveSmallIntegerField(default=0,blank=True) id_prtg=models.PositiveSmallIntegerField(default=0,blank=True) ospf=models.BooleanField(default=False) description=models.CharField(max_length=200,null=True,blank=True) id_EquipoDestino=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_destino') id_PuertoDestino=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_destino') ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Interfaces' My Serializer Model Interfaces class InterfaceSerializer(serializers.ModelSerializer): # Las siguientes lineas me permiten agregan campos de otros modelos al modelo en cuestion que estoty serializando a traves de llaves foraneas. #Se le agrega la propiedad de read_only=True para que el campo no sea editable. EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True) PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True) LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True) CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True) EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True) PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True) LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True) CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True) Vendedor=serializers.CharField(source='id_EquipoOrigen.vendedor',read_only=True) class Meta: model=Interfaces fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','Vendedor','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',) My ModelViewSet Interfaces class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interfaces.objects.all() serializer_class=InterfaceSerializer pagination_class=PostPageNumberPagination filter_class=InterfacesFilter class PostPageNumberPagination(PageNumberPagination): page_size=10 page_size_query_param = 'page_size' max_page_size = 1000 #Funcion Para El Filtro del Modelo Interfaces. class InterfacesFilter(filters.FilterSet): # Lineas de Codigo para filtrar campos relacionados, es decir campo que estan en el serializador del modelo Interfaces … -
Switching Git branches while running in Docker container causes permission error
I'm running Docker 19 on Windows 10 for development. A container volume binds directly to a Git repo folder and serves the Django app in that folder. I use Mingw-w64 to run Git (aka Git Bash). Occasionally, I'll do the following (or something similar to the following): Request a page served by the Docker container. (To replicate an error, for example.) Switch to a different branch. Request a page served by the Docker container from the new branch. Switch to a different branch. On the last branch switch, Git will freeze for a bit and then say permission denied on a particular file. The file is a difference between the two branches, so Git is trying to change it. Process Explorer tells me the files are used by the system process so the only way to get it to let go is by restarting. My gut is telling me the Django web process (manage.py runserver) is likely locking the file until the request connection is fully closed and is probably lingering as an established connection. Is my gut right? If it is... Why is the lock held by the system process and not Docker? Is there anything to do to … -
HTTPConnectionPool(host=\'0.0.0.0\', port=7000): Max retries exceeded with url (Caused by NewConnectionError
I'm using python to make 2 APIs communicate between them, i made tests and both APIs work fine on their own, the problem arises when i try to send a request to API A (made with flask) so A can pass the data to API B(made with django) and then return the result to A again. When i try to test this endpoint, the response is: HTTPConnectionPool(host='0.0.0.0', port=7000): Max retries exceeded with url: /verify?0 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fa0b939df50>: Failed to establish a new connection: [Errno 111] Connection refused')) The test file and the manual test fail in this way, if i make a request to API B with the url that API A is making it returns a ok message. I'm thing i missing something about the config in API B, but where? -
Django Please enter the correct username and password for a staff account
I have created the superuser before the deployment of app on Heroku server my domain is gizga.herokuapp.com when u enter gizga.herokuapp.com/admin a Django Admin dashboard comes and then u have to enter the username and password but it shows the following error "Django Please enter the correct username and password for a staff account Note that both fields" even I have created the superuser -
How do I force Django's DateTimeField to always use microseconds
This answer helped me quite a bit, but I am trying to go for something different, and wondering if there is an easy way to do it. I have some data that always needs to have microsecond precision. Currently, I'm just storing it as a BigIntegerField and converting it when needed. However, I would like to store it as a DateTimeField or something similar so I don't have to litter the code with converters. I know Django will preserve this information on our production database, but our tests run using the SQLite DB. It's one of those edge cases, where it shouldn't matter, but I want to try to future-proof the application a bit. Does anyone know if Django has a fallback method or if its fallback is just to throw away the extra information when using databases that don't support that level of precision? -
Django - How do I change the sort order of search results while still on the page?
I have a list of results from a user's search and I want the user to be able to re-order them as they wish. It is simple enough to pre-sort the queryset on the backend, in views.py which is what every Google search brings up on the topic. But I need to have this done by the user. On the frontend. This is usually done with a dropdown with options allowing alphabetical sort A-Z or sort by date added or so on. I can't find an answer with Google search or a single tutorial that covers it, yet I see it used almost everywhere. Does the solution involve ajax? How would I use ajax to do it? Is there a py module that does this in Django? -
Optimizing Django app in Google App Engine
I am facing slow page load time (list page in Django admin) for a simple Django app, deployed on Google App Engine, with postgres Cloud SQL. There are fewer than 20 records. SQL time is negligible, even with 30 queries. Majority of the time is shown as domLoading I assume that domLoading is probably referring to the initial loading of the case/ page, which took 3 seconds. Most of the solutions online refer to tweaking apache/nginx settings. But since I am using Google App Engine (PaaS), I cannot directly control webserver settings. gcloud app deploy is supposed to handle the load-balancing and code versioning. How do I improve the basic load time of Django App on GAE? Both GAE and Cloud SQL are hosted in the same region. PS: I did find some answers like Optimizing my Django app on Google App Engine, but they refer to optimizing SQL queries, which is not the case here. -
Amazon s3 alternative for django app on heroku [on hold]
Is there an alternative to amazon s3 for storing and serving media files (images) for django app deployed in heroku? Can we use google drive for this purpose? -
add multiple forms to page on button click
I am working on developing a permitting app using django. This is my first django project so bear with me here... we have a default utility permit that contains some basic info like property owner and address. Then from that you can attach a sewer, or water or row or any combination of related tables to the permit. Basically I am looking for a way to return a page with the default utility permit then have a series of links or buttons to add more forms to that page. I made some model forms for each of the models and can display them individually on the page forms.py class UtilityPermitForm(forms.ModelForm): class Meta: model = UtilityPermit fields = ['...'] class SewerPermitForm(forms.ModelForm): class Meta: model = SewerPermit fields = ['...'] class WaterPermitForm(forms.ModelForm): class Meta: model = WaterPermit fields = ['...'] I successfully added them to a list and could iterate through and get them to add views.py class BuildForms(View): permits = [] utility_form = UtilityPermitForm sewer_form = SewerPermitForm water_form = WaterPermitForm permits.append(utility_form) permits.append(sewer_form) permits.append(water_form) template_name = 'engineering/UtilityPermitForm2.html' def get(self, request, *args, **kwargs): out_permits = [] for form in self.permits: out_permits.append(form()) return render(request, self.template_name, {'form': out_permits}) def post(self, request, *args, **kwargs): if request.GET.get('testButton'): … -
Set checkbox disabled if already opted by user
I designed a seat layout with checkbox code looks something like this <div class="asiento"> <input type="checkbox" value="1" id="asiento1" name="check" > <label for="asiento1">1</label> </div> <div class="asiento"> <input type="checkbox" value="2" id="asiento2" name="check" /> <label for="asiento2">2</label> </div> <div class="asiento"> <input type="checkbox" value="3" id="asiento3" name="check" /> <label for="asiento3">3</label> </div> <div class="asiento"> <input type="checkbox" value="4" id="asiento4" name="check" /> <label for="asiento4">4</label> </div> <div class="asiento"> <input type="checkbox" value="5" id="asiento5" name="check" /> <label for="asiento5">5</label> </div> I tried to fetch data from Database using loop and i am getting output like this ['1', '2'] ['5'] can i do something to remove [ ] maybe use JQuery or JS to disable the checkbox that are already selected by other users, this is the loop that i used to get value {% for seat in seat %} {{seat.useat}} {% endfor %} -
Django fetching static files in absolute path instead of relative path
I'm trying to fetch a css file from my static folder (as declared in STATIC_URL=/static/) which path is $app/src/static/css/about.css to my html file located in $app/templates/about.css. I'll show the code below The thing that works but is not advisable by Django docs is I changed the STATIC_URL = 'static/' but this is not a good practice... However this way the static variable in html is static/... and it works. In about.html: link rel="stylesheet" href="{% static 'css/about.css' %}" And I don't know if this is needed but in urls.py is the following: urlpatterns = [ .. ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Expected result in href is =static/css/about.css What happens: href = /static/css/about.css Also I'm sorry for formating errors, I'm new to posting here -
How to save a Model Form with a foreign key of User to django models
I am trying to save user API keys to a Django Model with a foreign key of User such that each set of unique API keys has a unique User associated with them in the database. I am using the built in Django User Model and I have created my own Model Form in forms.py. I have tried including user in the Model form and Meta class to no avail. I have tried passing the keys and password as parameters to the model and form before saving. I have tried using instances of the form with commit set to False before adding the User to form.user. I've tried looking up the latest Django documentation but its fragmented and hard to follow. I'm purposefully leaving out imports unnecessary to this problem. This is my Models.py: from django.db import models from django.contrib.auth.models import User from django.conf import settings # Create your models here. class UserApiDetails(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None) key = models.CharField(max_length=32) password = models.CharField(max_length=32) def __str__(self): out = "key: " + str(self.key) + '\n' + "Password: " + str(self.password) def keys_exist(self): if UserApiDetails.objects.filter(pk=User.pk).exists(): return True else: return False This is my forms.py: from django import forms from .models import UserApiDetails … -
Django user with limited permissions can see all default models in Rest Framework
I'm using Django 2.2 with djangorestframework-3.9.2 and djangorestframework_simplejwt-4.1.3. Using the admin interface I've defined some users as super users, and some with limited permissions to only view a few endpoints. However, when I log in with the limited user, the user can view everything, and it can even edit and delete entries everywhere. The user is required to log in to access the api, but once authenticated the individual permissions don't seem to work. In my settings I have the following: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissions', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', ), } Is there anything else I explicitly have to set to block access to views? An example of how my views are defined follows: class CustomersViewSet(viewsets.ModelViewSet): queryset = Customer.objects.all() serializer_class = CustomerSerializer along with the serializer and model: class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' class Customer(models.Model): identifier = models.CharField(max_length=255, unique=True) entryDate = models.DateTimeField(default=timezone.now, blank=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True ) def save(self, *args, **kwargs): user = get_request().user self.user = user super(Customer, self).save(*args, **kwargs) def __str__(self): return self.identifier Finally, the views are added in urls.py: router.register('api/customers', CustomersViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), path('api/', include('rest_framework.urls', namespace='rest_framework')), … -
How can i display database data on a Django form?
I created a page where the user submits an order. The order is submitted to the SQLite DB and has the following fields: Time - Status - Rate. Once the order is submitted, i would like my django template to show it below an 'Active orders' tab. I don't know how to do it in terms of code, but i figured out that i need to create a query to db where all the user's `orders are fetched (maybe fetching the orders where ID = user's id?). How would i be able to perform such a operation in Django? In my views? Here is the template's view: def myview(request): item = get_object_or_404(market, item=item) if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): send = form.save() send.save() messages.success(request, f"Success") else: form = MyForm() return render(request, "main/mytemplate.html", context={"form":form}) And part of the template: <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form1 %} <button name="button1" type="submit" class="btn btn-primary">BUY</button> </form> <h3> ACTIVE ORDERS </h3> <p> Here should go the orders... </p> -
DRF: Nested serializer return in extra dictfield
I have the following object returned from a request which I want to serializer and return. 'data': [ { 'more_data': [ { 'name': 'more_data', 'value': 'test' }, ] 'data_attributes': [ { 'name': 'Package 1', 'attribute': '1', 'type': 'Test' }, ], } ] I want to return the data in the following format, basically nesting the data_attributes inside an extras DictField. { "data": [ { "name": "Package 1", "extras": { "data_attributes": [ { 'name': 'Package 1', 'attribute': '1', 'type': 'Test' } ] } } ] } I'm not sure how to write a nested serializer for this?