Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Test fails even though the link works
I found a great tutorial written with Django-1.11. But I have decided to use the current version (2.0.5) and try to adapt the tutorial. If I succeed, I would like to provide an updated version of the tutorial afterwards. Changing some things that were deprecated, I have already done well with the help of official Django documentation. But while writing some tests, I encountered difficulties. I don't understand why I'm getting this 404 != 200 error. views.py # ... def board_topics(request, pk): board = get_object_or_404(Board, pk=pk) return render(request, "topics.html", {"board": board}) urls.py # ... urlpatterns = [ path("boards/<int:pk>/", views.board_topics, name="board_topics"), path("home/", views.home, name="home"), path("admin/", admin.site.urls), ] tests.py # ... class BoardTopicsTests(TestCase): def setUp(self): self.board = Board.objects.create( name="Django", description="Django discussion board" ) # ... def test_board_topics_view_contains_link_back_to_homepage(self): board_topics_url = reverse("board_topics", kwargs={"pk": 1}) response = self.client.get(board_topics_url) homepage_url = reverse("home") self.assertContains(response, 'href="{0}"'.format(homepage_url)) Traceback FAIL: test_board_topics_view_contains_link_back_to_homepage (boards.tests.BoardTopicsTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/.../boards/tests.py", line 52, in test_board_topics_view_contains_link_back_to_homepage self.assertContains(response, 'href="{0}"'.format(homepage_url)) ... AssertionError: 404 != 200 : Couldn't retrieve content: Response code was 404 (expected 200) ---------------------------------------------------------------------- Ran 7 tests in 0.038s FAILED (failures=1) I wonder why I'm getting this error although I can call the views. Did I write the test properly? Thanks in … -
Celery: Received unregistered task of type 'custom_app.tasks.function'?
In my Django project I use Celery 4 + RabbitMQ. I am tring to run amount_counting task which is inside custom profile application. Next code raise error. How to fix it? It seems like celery don't see that task. I use: Celery==4.1.1 Django==1.11.5 I use next command first: celery -A EnjoyJumping beat -l info In terminal I see: [2018-06-03 21:03:41,963: INFO/MainProcess] Scheduler: Sending due task amount-counting (profile.tasks.amount_counting) Then I use command: celery -A EnjoyJumping worker -l info In terminal I see error: celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'EnjoyJumping.settings') app = Celery('EnjoyJumping') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) settings.py: CELERY_BROKER_URL = 'amqp://localhost' CELERY_RESULT_BACKEND = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Almaty' CELERY_BEAT_SCHEDULE = { "amount-counting": { "task": "profile.tasks.amount_counting", "schedule": 30.0, }, } CELERY_IMPORTS = ( "profile", ) profile/tasks.py: from __future__ import absolute_import, unicode_literals from celery import task @task() def amount_counting(): # some code -
How do I write labels for codes in a html file with django?
In the Django 2.2 manual p 86 there is the following code: from django.db import models class Person(models.Model): SHIRT_SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) name = models.CharField(max_length=60) shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES) It then explains that I get something like 'L' by using p.shirt_size and 'Large' by using p.get_shirt_size_display(). But can I get that in an HTML-file? I get 'L' with {{ p.shirt_size }}, but if I want the actual description to be printed in the HTML-file, how do I do that? {{ p.get_shirt_size_display() }} does not work, does it? Which is the proper way to solve this problem? -anders -
Displaying django subcategories in category json as Json Child
Hi in my django oscar project which Implements django oscar. I am able to implement my custom API which I use to view categories and display them. The issue with the API now is that subcategories of a category appear in my API view as categories and I would like them to be in an array indicating that they are subcategories. My categories code is as follows customapi serializer class class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'numchild', 'name', 'description', 'image', 'slug') Views class CategoryList(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer class CategoryDetail(generics.RetrieveAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer customapi/urls.py url(r'^caty/$', CategoryList.as_view(), name='category-list'), url(r'^caty/(?P<category_slug>[\w-]+(/[\w-]+)*)_(?P<pk>\d+)/$', CategoryDetail.as_view(), name='category'), Json [ { "id": 2, "path": "0001", "depth": 1, "numchild": 4, "name": "Clothes", "description": "<p>Beautiful Clothes</p>", "image": null, "slug": "clothes" }, { "id": 8, "path": "00010001", "depth": 2, "numchild": 0, "name": "c", "description": "", "image": null, "slug": "c" }, { "id": 7, "path": "00010002", "depth": 2, "numchild": 0, "name": "b", "description": "", "image": null, "slug": "b" }, { "id": 6, "path": "00010003", "depth": 2, "numchild": 0, "name": "a", "description": "", "image": null, "slug": "a" }, { "id": 5, "path": "00010004", "depth": 2, "numchild": 0, "name": "MsWears", "description": "", "image": null, "slug": … -
Method Not Allowed (POST) in django
I'm trying to login through a bootstrap modal. The form is loading fine, but when I try to submit the form an error rises. The error I'm getting is Method Not Allowed (POST): / [03/Jun/2018 14:32:09] "POST / HTTP/1.1" 405 0 base.html <a class="nav-link" href="#modalLogin" data-toggle="modal">Iniciar sesión<span class="sr-only">(current)</span></a> {% include 'prode/login.html' %} login.html <div class="modal hide" id="modalLogin"> <form method="post"> <div class="modal-dialog modal-md"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Iniciá sesión</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> &times; </button> </div> <div class="modal-body"> {% csrf_token %} <div class="form-group"> <label for="id_username">Usuario:</label> <div> <input type="text" name="username" maxlength="254" required id="id_username" autofocus /> </div> </div> <div class="form-group"> <label for="id_password">Contraseña:</label> <div> <input type="password" name="password" id="id_password" required /> </div> </div> </div> <div class="modal-footer"> <input data-dismiss="modal" class="btn btn-secondary" type="submit" value="Cancelar"/> <input class="btn btn-submit" type="submit" value="Acceder" /> </div> </div> </div> </form> -
django not filtering datetime
I am working on a news website using django and I would like to allow users to search articles by date This is the Article model class Article(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=100,null=False,blank=False) category=models.ForeignKey(Category,null=False,blank=False) date=models.DateTimeField(auto_now_add=True) content = models.TextField(null=False, blank=False) resume=models.CharField(null=False,blank=False,max_length=400) Right now I have two articles with the following dates (datetime) 2018-05-21 11:12:03.868542 2018-05-22 19:02:12.885298 When I run this on the django shell articles=Article.objects.filter(date__day=21,date__month=05,date__year=2018) I get an empty queryset -
How to send django objects to celery tasks?
Hello Awesome People! Before my question, I tried these SO posts: Pass parameter request to a celery task in Django passing django request object to celery task None of them works! I want to keep users on a website update with new courses. With a queryset of Courses, I want to send them via email. send_daemon_email.delay(instance=instance,all_courses=Course.objects.all()) And my function looks like: @shared_task def send_daemon_email(instance,all_courses): ctx = {'instance':instance,'all_courses':all_courses} message = get_template("emails/ads.html").render(ctx) ''' ''' When I tried to send the email to a specific user The error I got is <User: First Name> is not JSON serializable Just because delay() from celery got a non serialized data. How I can send Django objects to celery task so I can use it in the template? I know that I can send information needed as python object send_daemon_email.delay(first_name='Name', last_name='Lapr',all_courses = [{'title1':'title1',},{'title2':'title2',}]) but it would be too much info. Any hint will be appreciated. Thank you! -
Django: Use same request date on page refresh
I'm building a django app. I have a function in my view that proceeds a POST form request and the renders an page dependent on it: It looks simple like that: def renderPage(request): if request.method == 'POST': form = ExampleForm(request.POST) if form.is_valid(): # Do something with the form data #here i render the page and pass some data to it return render(request, "main/mypage.html", {"example" : example, ...}) ... This works just like it should. But now i want if someone is on the rendered Page an he reloads the page (for example in chrome by clicking on the address-bar an pressing enter) that the previews request he made is preserved. I the moment when somebody is reloading the page the renderPage() function is called but there is no request (obviously then of course the request.method == 'POST' statement is False). Is there any easy way to achieve this? Is this a problem/feature of the browser? Is it something i have to do in my html code? I can only thing of very complicated ways to do this. Like for example explicitly saving the request data and then writing a script in JavaScript that creates a copy of the previous request … -
Is it possible to use DjangoCMS with javascript frontend web frameworks like angular?
I have been using djangoCMS with django for a year now, i would like to start using new front end technologies like angular but i'm not sure if its possible with djangoCMS.I have successfully used plain django with django request framework and angular with no problem but i cannot figure out how to bring the CMS to the equation.any help would be appreciated. -
Extending django-oscarapi API ROOT to custom API class
I have a django oscar application and I use django-oscarapi for my custom APIs. Some things are missing from the oscarapi like category and promotions but I have been able to use django-restframework to create the category API but the challenge I am facing now is how to add it to the API-ROOT. This is my code for rendering categories customapi serializer class class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'numchild', 'name', 'description', 'image', 'slug') Views class CategoryList(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer class CategoryDetail(generics.RetrieveAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer customapi/urls.py url(r'^caty/$', CategoryList.as_view(), name='category-list'), url(r'^caty/(?P<category_slug>[\w-]+(/[\w-]+)*)_(?P<pk>\d+)/$', CategoryDetail.as_view(), name='category'), Thanks in advance -
Whay I am getting this error from MTurk sever?
I am trying to create a toy MTurk application which will automatically create HIT on MTurk and receive results. I am using Boto 2.4 version for it and I am building my app in Django with python 3.6 Here what I am getting from the server: 5eb9b062-54f5-4848-aed7-27e091867566FalseAWS.MechanicalTurk.InvalidParameterValueThe value "http://localhost:8000/hit/" is not valid for the parameter ExternalURL. This URL must use the HTTPS protocol.. (1528030818666 s)Valuehttp://localhost:8000/hit/ParameterExternalURLDescriptionThis URL must use the HTTPS protocol.DescriptionThis URL must use the HTTPS protocol.ParameterExternalURLValuehttp://localhost:8000/hit/ Surprisingly, When I changed base URL manually to 'https://localhost:8000' (note the 'S'). it works and start creating HIT, but there is another problem, since I am using local server, I am getting this error: [03/Jun/2018 14:52:58] code 400, message Bad HTTP/0.9 request type ('\x16\x03\x01\x00À\x01\x00\x00¼\x03\x03c\x03Nܱ\x94i²KR') [03/Jun/2018 14:52:58] You're accessing the development server over HTTPS, but it only supports HTTP. Please suggest me solution -
django:pass variable from html to view
I have a variable in script tag in html file (username), I want to pass this value to my views.py how can I do it? Thanks in advance this is my javascript code: <script type="text/javascript"> function getQueryVariable(variable) { var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); if(pair[0] == variable){return pair[1];} } return(false); } var username = getQueryVariable("username"); </script> -
Trying to create new object by HTML Form, Django,. HttpResponse object. It returned None instead
I am trying to create a new object Book using HTML form but I get HttpResponse None. I find almost the same case here: Django ModelForm with foreign key but my code still doesn't work. I can't find what is wrong. models.py class Author(models.Model): """ Author's class - defines an book's author """ name = models.CharField(max_length=140) def __str__(self): return self.name class Book(models.Model): """ Book class - defines a book """ title = models.CharField(max_length=140) author = models.ForeignKey("Author", on_delete=models.CASCADE) read = models.BooleanField(default=False) forms.py class BookForm(forms.ModelForm): title = forms.CharField(max_length=200) author = forms.ModelChoiceField(queryset=Author.objects.all()) class Meta: model = Book fields = ["title", "author", "read"] class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ["name"] books.html <form class="form-inline my-2 my-lg-0" method="POST"> {% csrf_token %} <input class="form-control mr-sm-2" type="text" placeholder="Title" aria-label="addbook" name="title"> <input class="form-control mr-sm-2" type="text" placeholder="Author" aria-label="addbook" name="author"> <button class="btn btn-outline-secondary my-2 my-sm-0" type="submit">Add New Book</button> </form> views.py def books(request): if request.method == 'POST': form = BookForm(request.POST or None) if form.is_valid(): form.save(commit=True) all_books = Book.objects.all all_authors = Author.objects.all return render(request, 'books.html', {'all_books': all_books, 'all_authors':all_authors}) else: all_books = Book.objects.all all_authors = Author.objects.all return render(request, 'books.html', {'all_books': all_books, 'all_authors':all_authors}) I guess something is wrong with views.py or books.html. I read a big part of Django documentation but still … -
django-allauth Custom signup form. How to add a field with image uploadI(image field)?
I'm using Django and Allauth. I need the user to be able to upload photos when registering. Models.py: class Profile(AbstractUser): bdate = models.DateField( blank=True, null=True, default="1990-01-01") photo = models.ImageField(upload_to='accounts/', blank=True, null=True, default="" ) phone = models.CharField(max_length=128, blank=True, null=True, default="" ) def __str__(self): return "%s, %s, %s, %s" % (self.username, self.first_name, self.middle_name, self.last_name) class Meta: verbose_name = 'Пользователя' verbose_name_plural = 'Пользователи' Adapter.py class AccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=False): data = form.cleaned_data user.username = data.get('username') user.email = data['email'] user.first_name = data['first_name'] user.last_name = data['last_name'] user.bdate = data['bdate'] user.photo = data.get('photo') user.phone = data['phone'] if 'password1' in data: user.set_password(data['password1']) else: user.set_unusable_password() self.populate_username(request, user) if commit: user.save() return user Forms.py class SignupForm (forms.Form): email = forms.EmailField(widget=forms.TextInput( attrs={"class": "input_text", }), required=True,) username = forms.CharField(max_length=20, widget=forms.TextInput( attrs={"class": "input_text", }), required=True,) password1 = SetPasswordField() password2 = PasswordField() first_name = forms.CharField(max_length=20, widget=forms.TextInput( attrs={"class": "input_text", }), required=True,) last_name = forms.CharField(max_length=30, widget=forms.TextInput( attrs={"class": "input_text", }), required=True,) bdate = forms.DateField( widget=forms.TextInput( attrs={"id": "date", "type": "date" }), required=True, ) phone = forms.CharField(max_length=30, widget=forms.TextInput( attrs={"class": "input_text", }) , required=True,) photo = forms.ImageField(required=False,) class Meta: model = Profile exclude = [" "] def signup(self, request, user): user.username = self.cleaned_data['username'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.bdate = self.cleaned_data['bdate'] user.photo = self.cleaned_data['photo'] user.phone … -
'RelatedManager' object has no attribute 'save'
This is the models.py code class Profile(models.Model): user = models.ForeignKey(User, unique=True, on_delete=models.CASCADE, related_name='profile') @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): # Profile.objects.save() instance.profile.save() and This the views.py code: def signup(request): .... if request.method == "POST": user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): user = user_form.save(commit=False) user.save(using='default') login(request, user) return HttpResponse("User Loged In") Then after fill the registration form and click the submit button, Django get me the following Error: -
How to use flask api from django not exposing flask server?
I have api created in flask. I want to use django templates to serve the static files created with angular. The problem is cant expose the flask endpoint from the client side for security. So, basically should I create django views which then calls flask api and how to tandem with the SPA? -
Upload file to S3 and local server
I've a small project where I upload files to S3 with the boto3 package. file = models.FileField( storage=CustomFileStorage(), upload_to=file_path ) Is there a way that I can also save the file to my local server? So I have a copy of the file directly on the server. -
how can I prevent users form extending/ minimizing TextField Django
How can I prevent this from happening I am talking about this -
Django class method is currently overridden
This is the error when I tried to run python manage.py makemigrations in command line ERRORS: asking.Question: (models.E020) The 'Question.check()' class method is currently overridden by <function BaseManager.check at 0x7f0f104889d8>. And this is Question class in models.py: class Question(BaseModel): content = models.CharField(max_length=250) answer = models.TextField("answer", blank=True, null=True) answerer = models.ForeignKey( User, on_delete=models.CASCADE, related_name="questions" ) def __str__(self): return self.content I am using Django version 2.0.5 -
Javascript singleton class isn't getting values from DOM attributes?
The data attributes are set using jinja rendered by Django. When I try to access the data-url attrib the value is assigned to the class's URL object. I have two issues with this code. Firstly, When I try to access data-default attribute it returns null or undefined value. Secondly, when I try to assign response from the ajax call to the this.data it is not getting assigned. Below is my code <select id="value" data-url="api/values" data-default="1"> </select> $(document).ready(function(){ var value = new function(){ this.url = $("#value").attr("data-url"); this.default = $("#value").attr("data-default"); this.data = null; this.settings = { "async": true, "crossDomain": true, "url": this.url, "method": "GET", }; this.getData = function(){ $.ajax(this.settings).done(function(response){ this.data = response; $.each(response, function (i, value) { var $option = $('<option>').text(value.shift_name) .attr('value', value.id) .attr('start', value.shift_start_time) .attr('end', value.shift_end_time) .attr('shift_day', value.shift_day) if (this.default==value.id){ //Error here this.default is always undefined $option.attr('selected', 'selected'); } $('#value').append($option); });//Loop ends });//ajax ends }//sub function ends } //class ends value.getData(); }); -
How to optimise Django FormView
I have never optimised my Django code and I'm not sure I fully understand Django optimisation docs so can you tell me if this FormView class can be somehow optimised (I'm guessing yes ...)? The part of code which I'm worried about is the Patient lookup: Patient.objects.get(patientId=self.kwargs['patientId']) - it's happening 3 times ... Does it mean Django will hit the database 3 times or only once? Can/should this be optimised, and if yes - how? class PatientNotes(SingleObjectMixin, FormView): slug_url_kwarg = 'patientId' slug_field = 'patientId' pk_url_kwarg = 'patientId' template_name = "patient/patient_detail.html" form_class = AddNewNoteForm def get_queryset(self): queryset = super(PatientNotes, self).get_queryset() self.current_patient = Patient.objects.get(patientId=self.kwargs['patientId']) my_result = queryset.filter(patient=self.current_patient) return my_result def post(self, request, *args, **kwargs): self.object = Patient.objects.get(patientId=self.kwargs['patientId']) return super().post(request, *args, **kwargs) def form_valid(self, form): self.object = form.save(commit=False) self.object.patient = Patient.objects.get(patientId=self.kwargs['patientId']) self.object.note_created_by_date = datetime.date.today() self.object.save() return super().form_valid(form) def get_success_url(self): return reverse('PatientDetailView', kwargs={'patientId': self.object.patient.patientId}) -
Single page apps and backend API's
When creating single page apps that communicate with a backend API via ajax, what is common (best?) practice regarding updating different server side database objects as a result of one client side action? For example lets say I delete something on the client which in turn results in needing to update several other items. Perhaps we have an app that simulates people standing in a line. Each person has a position in the line. The user has the ability to delete a person from the line which results in two actions. First, delete the person from the database. Second, update the remaining people in the database to reflect their new position in the line. Should the above be done in two separate ajax requests? First send the DELETE request and if the server replies with a success message, then send a PATCH request to update the remaining people positions. Or should both of those be combined into a single ajax call? The reason I ask is because doing two separate requests would be more RESTful from the API perspective. ie: Send a DELETE request for a single object, get a success reply on the client, then send a PATCH request … -
Django Rest Framework: Respond with 404 if no result found
With the help of some others here I managed to get my DRF driven API to a good point to work with. I'm now trying to mingle out some details. Currently. Here's the view: class EpisodeViewSet(viewsets.ModelViewSet): queryset = Episode.objects.all().order_by('-published_at') filter_backends = (DjangoFilterBackend,) filter_fields = ('show_id', 'number') def get_serializer_class(self): if self.action == 'retrieve': return EpisodeDetailSerializer if self.request.GET.get('show_id') and self.request.GET.get('number'): return EpisodeDetailSerializer return EpisodeSerializer and here's my serializer: class EpisodeDetailSerializer(serializers.ModelSerializer): chapters = ChapterMarkSerializer(source='chaptermark_set', many=True) media = MediaClipSerializer(source='mediaclip_set', many=True) show = ShowSerializer() guest = GuestSerializer(source='guest_set', many=True, read_only=True) topic = TopicSerializer(source='topic_set', many=True, read_only=True) # def get_queryset(self): # show = self.request.query_params.get('show') # number = self.request.query_params.get('number') # queryset = self.objects.get(show_id=show, number=number) # return queryset class Meta: model = Episode fields = ('id', 'title', 'number', 'subtitle', 'show', 'published_at', 'updated_at', 'description_title', 'description', 'show_notes', 'supporters_title', 'supporters_text', 'supporters_button', 'forum_title', 'forum_text', 'forum_link', 'cover_image', 'updated_at', 'chapters', 'media', 'guest', 'topic') depth = 1 I'm not sure anymore where the get_queryset function came from but the results weirdly are the same with and without, that's why it's commented out at the moment. Background is I'm querying episodes in two different ways: through their primary key api/episodes/123 through a filter by show and number api/episodes?show_id=1&number=2 In the first case the api returns one object if … -
Django - arguments in form?
views.py from django.shortcuts import render from basic_app.forms import UserForm,UserProfileInfoForm # Extra Imports for the Login and Logout Capabilities from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required # Create your views here. def index(request): return render(request,'basic_app/index.html') @login_required def special(request): # Remember to also set login url in settings.py! # LOGIN_URL = '/basic_app/user_login/' return HttpResponse("You are logged in. Nice!") @login_required def user_logout(request): # Log out the user. logout(request) # Return to homepage. return HttpResponseRedirect(reverse('index')) def register(request): registered = False if request.method == 'POST': # Get info from "both" forms # It appears as one form to the user on the .html page user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) # Check to see both forms are valid if user_form.is_valid() and profile_form.is_valid(): # Save User Form to Database user = user_form.save() # Hash the password user.set_password(user.password) # Update with Hashed password user.save() # Now we deal with the extra info! # Can't commit yet because we still need to manipulate profile = profile_form.save(commit=False) # Set One to One relationship between # UserForm and UserProfileInfoForm profile.user = user # Check if they provided a profile picture if 'profile_pic' in request.FILES: print('found it') # If … -
Django Rest Framework - Required ListField values
I'm building a simple API with DRF for the first time. I want to submit a list of location points to the API, but for some reason required attribute isn't working as I expect. This are my serializers from rest_framework import serializers class RouteSerilizer(serializers.ListField): pickup = serializers.CharField(required=True) dropoff = serializers.CharField(required=True) class CalculateRatesSerializer(serializers.Serializer): service_start = serializers.DateTimeField() service_end = serializers.DateTimeField(required=False) pax_count = serializers.IntegerField(min_value=1) route = RouteSerilizer(min_length=2) The request { "pax_count": 3, "service_start": "2019-12-12T12:12", "route": [{ "dropoff": "34.232342342" }, { "dropoff": "39.232342342" }] } Response { "service_start": "2019-12-12T12:12:00", "pax_count": 3, "route": [ { "dropoff": "34.232342342" }, { "dropoff": "39.232342342" } ] } My question is, why is this request considered valid where i've explicitly set the fields(pickup,dropoff) to required?