Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter model method - Django
I want to filter the Preschooler with their BMI tag but BMI tags are from model method. How do I filter Preschoolers with their BMI tag? models.py from pygrowup import Calculator, helpers class Preschooler(Model): birthday = models.DateField(null=True, blank=True) height = models.FloatField(null=True, validators=[MinValueValidator(45.0), MaxValueValidator(120.0)]) weight = models.FloatField(null=True, validators=[MinValueValidator(1.0), MaxValueValidator(28.0)]) gender = models.CharField(max_length=100, choices=GENDER, null=True) def bmi_tag(self): calculator = Calculator(adjust_height_data=False, adjust_weight_scores=False, include_cdc=False, logger_name='pygrowup', log_level='INFO') try: age_months = int((date.today().year - self.birthday.year) * 12) whfa_value = float(calculator.wfl(self.weight, age_months, helpers.get_good_sex(str(self.gender)), self.height)) if whfa_value > 2.0: return 'ABOVE NORMAL' elif whfa_value >= -2.0 and whfa_value <= 2.0: return 'NORMAL' elif whfa_value >= -3.0 and whfa_value < -2.0: return 'BELOW NORMAL' else: return 'SEVERE' except: pass I would like to filter a preschooler like this: preschooler_normal = Preschooler.objects.filter(bmi_tag='NORMAL') But I am aware that we cannot query against model methods. How can I achieve this? Thanks! -
Login page is not working. Why am I getting redirected to my homepage
Whenever I do /login I get redirected to my homepage which is named pplLst. I think it is something wrong with how I am redirecting but I watching this tutorial (https://www.youtube.com/watch?v=llbtoQTt4qw&t=3399s) which I used in my code urls.py from django.urls import path from .views import pplCreate, pplCreate, pplList, pplDetail,pplUpdate,pplDelete,authView urlpatterns = [ path('login/', authView.as_view(),name='login'), path('', pplList.as_view(), name='pplLst'), path('people/<int:pk>', pplDetail.as_view(), name='pplDet'), path('people-update/<int:pk>', pplUpdate.as_view(), name='pplUpd'), path('people-create/', pplCreate.as_view(), name='pplCre'), path('people-delete/<int:pk>', pplDelete.as_view(), name='pplDel'), ] views.py from distutils.log import Log import imp from .models import People from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.contrib.auth.views import LoginView # Create your views here. class authView(LoginView): template_name = 'base/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('pplLst') class pplList(ListView): model = People context_object_name = 'people' class pplDetail(DetailView): model = People context_object_name ='cnd' template_name = 'base/people.html' class pplCreate(CreateView): model = People fields = '__all__' success_url = reverse_lazy('pplLst') class pplUpdate(UpdateView): model = People fields = '__all__' success_url = reverse_lazy('pplLst') class pplDelete(DeleteView): model = People context_object_name = 'cnd' success_url = reverse_lazy('pplLst') -
username=self.kwargs.get('username') returning Not Found: /
Hi I am trying to set the show the items the is only related to a specific user who is currently logged in. I have made sure that the user has items under his username. I want to filter the items to be viewed only to the related user. Currently I am getting an error of Not Found: / I am not sure why? Here is the models.py: class Item(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) Here is the urls.py: urlpatterns = [ path('', home.as_view(), name='home'), I have tried to have a queryset with the filter to the logged in user but returned back the same error. Here is my views that I have tried class home(LoginRequiredMixin, ListView): model = Item template_name = 'app_name/base.html' context_object_name = 'items' # queryset = Item.objects.filter(user=User) def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) print(user) # return Item.objects.filter(user=user) In the home.html I added: {% block head_title %} {{ view.kwargs.username }} | {% endblock %} My question: How can I show the list of items that is only related to the logged in user? what am I doing wrong in here? -
Query in Django to sort in one table based on result of another table
I have two models listing model is: class listing(models.Model): productTitle= models.CharField(max_length=60) description = models.TextField() category = models.ForeignKey(category,on_delete=models.CASCADE,null=True) productPrice = models.FloatField(default=0.0) def __str__(self): return self.productTitle my watchlist model is: item = models.ForeignKey(listing, on_delete= models.CASCADE) watchlist = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.item In my index.html I want to show the list item if watchlist attribute is False. Now, my views.py for index.html is as follows: def index(request): if request.user != "AnonymousUser": items= listing.objects.exclude(id=watchlist.objects.filter(user=request.user)) else: items = watchlist.objects.all() context = {'items':items} return render(request, "auctions/index.html", context) I couldn't filter the items on listing models based on the result of watchlist model i.e if watchlist=True then I do not want to render items on index.html. Because, I want to render watchlist items in separate pages. How to query in django if there are two models used? -
I have used the international phone numbers(intlTelInput) in my django app but it seems the form isn't saving the number
So i have basically used the intl-tel-input plugin in my registration form. My webapp is in django. But whenever i submit the form, i get an error which is like the phone_number field is required, even though i have filled in the number. Seems like the form isn't saving the phone number data. How can i solve this? form temlplate looks like this: {% load static %} {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/css/register.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script> </head> <body> </body> </html> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> </body> </html> </head> <body> <div class="container"> <div class="title">REGISTER </div> <div class="content"> <form action="#" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="user-details"> <div class="input-box"> {{form.name|as_crispy_field}} </div> <div class="input-box"> {{form.email|as_crispy_field}} </div> <div class="input-box"> <span class="details">Phone number</span> <input id="phone" type="tel" name="phone" /> </div> <div class="input-box"> {{form.address|as_crispy_field}} </div> <div class="input-box"> {{form.nin|as_crispy_field}} </div> <div class="input-box"> {{form.LC1_letter|as_crispy_field}} </div> <div class="input-box"> {{form.National_Id|as_crispy_field}} </div> <div class="input-box"> {{form.password1|as_crispy_field}} </div> <div class="input-box"> {{form.password2|as_crispy_field}} </div> </div> <div class="form-check d-flex justify-content-center mb-5"> <input class="form-check-input me-2" type="checkbox" value="" id="form2Example3c" /> <label class="form-check-label" for="form2Example3"> First agree with all statements in <a href="#!">Terms of service</a> to continue </label> </div> <div class="button"> <input type="submit" value="Register" href="#"> <input type="submit" value="Login" style="margin-left: … -
Django drf group by a model date field
I have an attendance model with the below structure class Attendance(models.Model): class PRESENCE(models.TextChoices): P = "P", "Present" A = "A", "Absent" L = "L", "On leave" user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="user_attendance", blank=False, null=True) leave_reason = models.CharField(max_length=355, blank=True, null=True) date = models.DateField(blank=False, null=True, auto_now=False, auto_now_add=False, editable=True) presence = models.CharField( choices=PRESENCE.choices, max_length=255, blank=False, null=True) attendance_taker = models.ForeignKey( User, on_delete=models.CASCADE, related_name="attendance_taker", blank=False, null=True) def __str__(self): return f'{self.user}' class Meta: verbose_name = _("Attendance") verbose_name_plural = _("Attendance") constraints = [ UniqueConstraint( fields=('user', 'date'), name='unique_attendance_once_per_date') ] I would like to create a table with the list of dates but simply using a generic view wouldn't cut it since different users will have similar dates, I need a way to merge the same dates into one and group the attendance instances that have similar dates. -
Insert i18n language into the request
I'm using the i18next lib, together with react in my front, and i intend to pass the information of my current language to my api through every request. I have a axios client wrapped in a constant that i use in my whole application, like this: ` const client = axios.create({ baseURL: CONSTANTS.API.BASE, headers: { "Content-Type": "application/json", }, timeout: TIME_OUT, }); ` I'd like to know if there some easy way to do this, and then get the language information in the back. By the way, i'm using Django REST Framework in my api. I tried to simply declare a variable into the headers in the client, just for test, but i couldn't get the value in the request in the api -
How to override `Model.__init__` and respect `.using(db)` in Django?
I have the following code: print(f"current database: {self.db}\ninfusate from database: {infusate._state.db}\ntracer from database: {tracer._state.db}") FCirc.objects.using(self.db).get_or_create( serum_sample=sample, tracer=tracer, element=label.element, ) That is producing the following output and exception: current database: validation infusate from database: validation tracer from database: validation Validating FCirc updater: {'update_function': 'is_last_serum_peak_group', 'update_field': 'is_last', 'parent_field': 'serum_sample', 'child_fields': [], 'update_label': 'fcirc_calcs', 'generation': 2} Traceback (most recent call last): File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 581, in get_or_create return self.get(**kwargs), False File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( DataRepo.models.fcirc.FCirc.DoesNotExist: FCirc matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/views/loading/validation.py", line 91, in validate_load_files call_command( File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/management/commands/load_animals_and_samples.py", line 134, in handle loader.load_sample_table( File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/utils/sample_table_loader.py", line 426, in load_sample_table FCirc.objects.using(self.db).get_or_create( File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 588, in get_or_create return self.create(**params), True File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 451, in create obj = self.model(**kwargs) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/models/maintained_model.py", line 430, in __init__ super().__init__(*args, **kwargs) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 485, in __init__ _setattr(self, field.name, rel_obj) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 229, in __set__ raise ValueError('Cannot assign "%r": the current database router prevents relation between database "%s" and "%s".' % (value, instance._state.db, value._state.db)) ValueError: Cannot assign "<Tracer: … -
execute django raw querie using ilike sentence
I got a query that compared with ORM is much more simpler using direct sql, Trying to execute it directly is in the part related to the ilike clause, I tried different ways but all fails (added a shorter query just to exemplify the problem) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike '%%%s%%'", ["jan"]) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike %%%s%%", ["jan"]) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike %s", ["jan"]) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike '%%%s%%'", ["jan"]) the error: LINE 1: SELECT cc.name FROM customer cc WHERE name ilike '%'jan'%' LINE 1: SELECT cc.name FROM customer cc WHERE name ilike %'jan'% LINE 1: SELECT cc.name FROM customer cc WHERE name ilike 'jan' LINE 1: SELECT cc.name FROM customer cc WHERE name ilike '%'jan'%' -
djangosaml2idp Issue with Importing Expired Certificates
was interrupted by the expiration of the service provider. Is there any way to fix this part? I couldn't touch it because I didn't know at all. -
Django: could not convert string to float: ''
I am trying to write a function to display all items in cart, but it keeps showing this error could not convert string to float: " and i cannot tell where the problem is coming from? i have tried chaging the float(...) method to int(...). what the possible error? def cart_view(request): cart_total_amount = 0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_amount += int(item['qty']) * float(item['price']) return render(request, "core/cart.html", {'cart_data':request.session['cart_data_obj'], 'totalcartitems': len(request.session['cart_data_obj']), 'cart_total_amount':cart_total_amount}) else: return render(request, 'core/cart.html', {'cart_data':'','totalcartitems':0,'cart_total_amount':cart_total_amount}) -
Unable to connect Oracle 19 database into Django container with Oracle database running into another container
I am pretty new on Docker and Iam trying to run a Django application with Oracle 19 database with Docker thanks to a docker-compose.dev.yml file. The problem is that my database container works but not my Django application which fails to connect to database. Here's the file : version: "3.9" services: oracle-database: image: icsvaccart/oracle19c:latest volumes: - ./data/db:/opt/oracle/oradata ports: - "1521:1521" - "5500:5500" django-back-end: build: . volumes: - .:/app ports: - "8000:8000" env_file: - pythonPOC/.env depends_on: - oracle-database Then I ran the command docker compose -f docker-compose.dev.yml up --build and after a couple of minutes, the process ends with the following complete logs : (venv) PS D:\Vianney\Documents\Projets\pythonPOC> docker compose -d -f docker-compose.dev.yml up --build Building 439.7s (11/11) FINISHED [internal] load build definition from Dockerfile 0.0s transferring dockerfile: 32B 0.0s [internal] load .dockerignore 0.0s transferring context: 34B 0.0s [internal] load metadata for docker.io/library/python:3 1.5s [auth] library/python:pull token for registry-1.docker.io 0.0s [1/5] FROM docker.io/library/python:3@sha256:fc809ada71c087cec7e2d2244bcb9fba137638978a669f2aaf6267db43e89fdf 0.0s [internal] load build context 0.1s transferring context: 16.98kB 0.1s CACHED [2/5] WORKDIR /app 0.0s CACHED [3/5] COPY requirements.txt /app 0.0s CACHED [4/5] RUN pip install -r requirements.txt 0.0s [5/5] COPY . . 417.3s exporting to image 17.7s exporting layers 17.7s writing image sha256:f7909ee3f0cf378b86a4c6d64bc7c37ad69b1014cfea06b345cb9345e6310365 0.0s naming to docker.io/library/pythonpoc-django-back-end 0.0s … -
How to serve response in django then down the server
I need a advice I want create a path in django for example /stop-server When somebody send a request to /stop-server server return a response and then become killed What's your proposal?......... -
Tests for Django Channels/WebSockets
what is the good & easy way to test consumers.py in Django Channels (websocket endpoints). I've seen https://channels.readthedocs.io/en/stable/topics/testing.html but to me that's kinda too complicated a bit and not sure if that's I want. For example I haven't find info about how to pass user to scope for proper consumer testing or how to make my custom middleware for authentication. Maybe there's someone "advanced" at django channels and you've tested consumers. If yes, please share the way you did it, because I really can't google how to test this stuff. I have already reached this stage: class TestConsumer(TestCase): async def test_consumer(self): communicator = WebsocketCommunicator(UserLocationConsumer.as_asgi(), path='/ws/user-track-location')) connected, subprotocol = await communicator.connect() self.assertTrue(connected, 'Could not connect') await communicator.send_json_to(content='test') result = await communicator.receive_json_from() print(result) await communicator.disconnect() That allows me to enter my consumer BUT inside consumer there is no scope, because no authorization where passed, so I can't fully cover my consumer's functionality with tests: ERROR: test_consumer (gps.tests.test_consumers.TestConsumer) self.user_id = self.scope['user'].id KeyError: 'user' -
Django .save() doesn't update on PUT request
I am trying to update a foreign-field with a PUT request on a resource. My serializer.data and the http response is correct after callig .is_valid, but the object doesn't get updated. View def put(self, request, user_pk): try: userById = getUserById(user_pk) except ChatUser.DoesNotExist: raise Http404 serializer = ChatUserInputSerializer(userById, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer class IdentificationInputSerializer(serializers.ModelSerializer): class Meta: model = Identification fields = "__all__" read_only_fields = ["id"] class ChatUserInputSerializer(serializers.ModelSerializer): identification = IdentificationInputSerializer() class Meta: model = ChatUser fields = ["id", "userId", "identification"] read_only_fields = ["id", "userId"] def update(self, instance, validated_data): identification = validated_data.pop('identification') instance.identification.salutation = identification.get('salutation', instance.identification.salutation) instance.identification.firstname = identification.get('firstname', instance.identification.firstname) instance.identification.name = identification.get('name', instance.identification.name) instance.identification.street = identification.get('street', instance.identification.street) instance.identification.plz = identification.get('plz', instance.identification.plz) instance.identification.city = identification.get('city', instance.identification.city) instance.identification.country = identification.get('country', instance.identification.country) instance.save() return instance -
How to associate a URL with an IP address?
I developped multiple REST APIs in Django--each with a specific IP address--and I would like to point them to a single domain name. With A records I could associate IPs of the APIs with subdomains like s.example.com, c.example.com and so on, but how can I associate IPs with URLs ? is it possible ? The desired URL pattern would be something like this : https://example.com/s/api # IP 1 https://example.com/c/api # IP 2 https://example.com/t/api # IP 3 https://example.com/b/api # IP 4 https://example.com # IP 2 -
Way to fix "missing QuerySet" and "override QuerySet" with Django
I'm trying to code a blog with django but I want to add a placeholder to my form when creating or editing an article. So I had the forms.py because before that I wasn't using a form from this file because I only needed the models.py file. I fount a way to do what I wanted and so add my placeholder into my input from my forms. But one problem, when I updated my website and went to my pages to see the changed an error appeared. So I tried to fix the problem by looking on the web and I saw a lot of people having approximately the same problem but the answers were that I had to add a get_qeryset definition in my views in views.py for the specific forms. I didn't find what I have to set in the definition of the get_queryset and not very understood where I have to put these definitions. I would be very grateful if you can help me. Here's my code : My views in view.py : class BlogHome(ListView): model = BlogPost context_object_name = "posts" def get_queryset(self): queryset = super().get_queryset() if self.request.user.is_authenticated: return queryset else: return queryset.filter(published=True) @method_decorator(login_required, name='dispatch') class BlogPostCreate(CreateView): … -
Django installation failed
My pc recently started giving error in installing Django.... Look at the error message, what could be the cause please? I tried installing Django for my project, and it just throw an unexpected error message. I have the right Venv activation code so I expected it to work. -
Using django-bootstrap-modal-forms on success, redirect to the initial page
Using django-bootstrap-modal-forms, I would like to redirect to the initial page, say /d/SimulationScenario/123/, after a successful POST request of modal form. My guess is that this is done using success_url, but how can I pass an argument indicating the ID of the scenario, which is different each time, like here: class EventCreateView(BSModalCreateView): template_name = 'form_scenario_event_create.html' form_class = SimulationEventForm success_message = 'Success: Event was added to the scenario.' success_url = reverse_lazy('detail_scenario', kwargs={'scenario_ID':123}) -
Pythonanywhere: Error running WSGI application. ModuleNotFoundError: No module named 'dotenv'
My web blog on Pythonanywhere was deployed a long time ago, today I redid the design and hid my secrets with the help of Dotenev. After that, I pushed everything to github, then deployed it to Pythonanywhere. As a result, when I launch the site, I get this window: After reading the logs, I saw the source of the problem, but I can’t find a solution anywhere, and now I’m turning to your community. This is what it says in my logs: enter image description here I imported everything in the code correctly, activated it, and set the parameters in a new .env file. I wrote variables for the secrets, and so that they are read by the setting.py file. I read the logs, I saw this error, but I can't find a solution to it -
Django {% extends 'base.html' %} {% block content %} {% load static %} does not work, nothing works actually
I have a html template i want to code in django. For now i need to take the header and footer parts and make images, css and js into static files. I tried to do it but it does not quite work, can anyone help me with it? I would greatly appreciate if someone can fix my mistakes and send me the file {% extends 'base.html' %} {% block content %} {% load static %} none of them work -
How to create an SMPP server
I have built am sms platform in django that connects to providers via HTTP, but now i want my application to communicate in SMPP protocol. Please has anybody built such an application.? I have searched through the internet, I found this repo https://github.com/dtekluva/shorty_SMPP. But I cannot for the life of me, get it to run. I have also tried to reach out to the developer. -
Django doesn't recognize worker.js file which is created by react.js
I have an app where I create frontend with react.js and then send the template files into django app and then run only django app. I'm having trouble with django recognizing a file within in this "build" folder that comes from react. Here is my index.html file: <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app"/> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <link rel="manifest" crossorigin="use-credentials" href="./manifest.json" /> <script> if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('./worker.js').then(function(registration) { console.log('Worker registration successful', registration.scope); }, function(err) { console.log('Worker registration failed', err); }).catch(function(err) { console.log(err); }); }); } else { console.log('Service Worker is not supported by browser.'); } </script> <title>SettledHead</title> </head> <body> <div id="root"></div> </body> </html> When I run react app directly, it works and this is the screenshot of the end-result: And this is the screenshot from the page which will create problem at django part (but works fine here): Then I run "npm run relocate" and send the build folder into django app. When I dont do anything about serviceworker, my app works well with this structure. But when I try to implement pwa - serviceworker into it, it doesnt … -
How to add django-editorjs-fields EditorJsTextField or EditorJsJSONField in html template
I am trying to add block style editor with django-editorjs-fields. It work django admin fine but not working with template. I properly configure urls.py for static files. Here is my code sample..... models.py class Post(models.Model): title = models.CharField(max_length=255, blank=False) slug = models.CharField(max_length=255, unique=True) image = models.ForeignKey(Media, on_delete=models.SET_NULL, blank=True, null=True) content = EditorJsTextField(blank=True, null=True) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' widgets = { 'content': EditorJsWidget(plugins=["@editorjs/image", "@editorjs/header"]) } views.py class PostFormView(FormView): form_class = PostForm template_name = 'add.html' success_url = '/' def form_valid(self, form): form.save() return super().form_valid(form) template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> </body> </html> Output: https://prnt.sc/ytMX_522Y4zF Not showing expected output. Show only normal textfield Expected output: https://prnt.sc/l0Uku9Xt-yNl -
django rest framework POST error. When I send a JSON/dictionary inside a Json it returns: "Not a valid string."
I'm trying to get this test API working, it is very simple and the model consist of only one class with 2 fields. My viewset inherits from ModelViewset and I added(to make it more explicit, and make some changes in the future) the list and create function. I could POST a few JSONs with succes, but when I try to post this one that has a 'nested json' it returns "Not a valid string." Here is the code and the JSON: views.py: class SessionViewset(viewsets.ModelViewSet): """" A simple viewset for listing or retrieving 'sessions' """ queryset = Session.objects.all() serializer_class = SessionSerializer def list(self, request): queryset = Session.objects.all() serializer = SessionSerializer(queryset, many=True) return Response(serializer.data) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) JSON: { "meta":"aca va la metadata", "reunion":{"juan":500, "pedro":300, "jose":1000} } and it returns: { "reunion": [ "Not a valid string." ] } screenshot: Do you know if there is any limitation that I'm not aware of, or how can I solve this issue? Thanks Tried to POST that JSON, into the API endpoint, with said error response