Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the Django model from its name
I have the name of the model table, for example, main_masterinventory, as a string. How do I get the model table given this name? I'm not really understanding the logic of this task, so I've got nothing to show for my work, but if you have any questions about my query, feel free to ask in the comments. -
Django filter where every item in an object's many to many list is included in provided queryset
I'm having a bit of trouble phrasing my question title, which might be why I can't find an answer. It doesn't need to be query set, it could just be a list of pks or some other method. I'll explain with an example and say what I want and what I don't. I have the following models. class Document(models.Model): allowed_groups = models.ManyToManyField(Group, related_name='allowed_documents') class Person(models.Model): permission_groups = models.ManyToManyField(Group, related_name='people') class Group(models.Model): id = models.BigIntegerField() I want to find all the documents that Person can access with the condition that they have to be a member of all of the allowed groups. I want this: Case Document(allowed_groups=1,2,7) with Person(permission_groups=1,2,6,7,11,15) -> MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=1,7) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=1,2) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=2) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=8) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=1,2,7) -> MATCH If I do this: person = Person.objects.get(pk=1) Document.objects.filter(allowed_groups__in=person.permission_groups.all()) I would match on all of the above cases except 8 (not what I want) There are many questions on stack overflow that are asking about exact matching i.e. match only on case 6 but not case 1. (also not what I want) So my question is how can I use django to do this? I've considered … -
How to properly serialize a PrimaryKeyRelatedField in Django Rest Framework
I have two Django models: Book -- which has some Wagtail StreamFields: class Book(models.Model): title = models.CharField(max_length=255) cover_image = StreamField(...) ... Publisher -- which is pure Django: class Publisher(models.Model): name = models.CharField(max_length=255) ... I wanted to have a PublisherChooser in my Wagtail admin. So I [created all that was required and then] added a field to my Book model: class Book(models.Model): title = models.CharField(max_length=255) cover_image = StreamField(...) ... publisher = models.CharField(max_length=10) panels = [ FieldPanel("title"), FieldPanel("cover_image"), FieldPanel("publisher", widget=PublisherChooser), ] Now I have a proper PublisherChooser whenever I want to create a Book in Wagtail Admin. Problem Now I want to serialize my Book model. So I have tried: class PublisherSerializer(serializers.ModelSerializer): class Meta: model = Publisher fields = [ "name", ... ] name = serializers.CharField() ... and class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = [ "title", "cover_image", ..., "publisher", publisher = serializer.PrimaryKeyRelatedField(queryset=Publisher.objects.all()) def update(self, instance, validated_data): publisher = validated_data.pop("publisher") instance.publisher_id = publisher.id return instance def to_representation(self, instance): data = super().to_representation(instance) publisher_serializer = PublisherSerializer( Publisher, context={"pk": instance.publisher} ) data["publisher"] = publisher_serializer.data return data I get publisher in the response but the publisher data doesn't seem to look right: "publisher": { "name": "<django.db.models.query_utils.DeferredAttribute object at 0x7f9ffa146310>", } -
Different format of currency using DecimalField based on choices from other models
What I am trying to do I would want Django to save different format of currency based on which preferred language that user wants to use without using localization. But I am totally lost from where to start. I have two types of currencies: US Dollar($) and Thai Baht. US Dollar can have upto maximum 2 decimal places whereas Thai Baht does not have any 2 decimal places. Here, when user chose their preferred language as USD, I would like Django save price per night of hotel room (this is defined in other models) upto 2 decimal places although its value does not have any decimal numbers. On the other hand, Thai Baht should always have 0 decimal places. Example Preferred currency is USD and price per night is $600 -> Want to save as $600.00 Preferred currency is USD and price per night is $600.12 -> Want to save as $600.12 Preferred currency is THB and price per night is ฿600 -> Want to save as ฿600 (without any decimal points) Preferred currency is THB and price per night is ฿600.12 -> This will throw validation error as there is no such 2 decimal places in THB. Below is … -
Django ORM - Annotate
G'day All, I'm trying to create a running balance of all negative transactions with a date less than or equal to the current transaction object's transaction date however if I use __lte=transaction_date I get multiple rows, while this is correct I want to sum those multiple rows, how would I do that and annotate to my queryset? Current Attempt: #getting transaction sum and negative balances to take away from running balance totals = queryset.values('transaction_date','award_id','transaction').annotate(transaction_amount_sum=Sum("transaction_amount"))\ .annotate(negative_balance=Coalesce(Sum("transaction_amount",filter=Q(transaction__in=[6,11,7,8,9,10,12,13])),0))\ #adding it all to the queryset queryset = queryset\ .annotate(transaction_amount_sum=SubquerySum(totals.filter(award_id=OuterRef('award_id'),transaction_date=OuterRef('transaction_date'),transaction=OuterRef('transaction'))\ .values('transaction_amount_sum')))\ .annotate(negative_balance=SubquerySum( totals.filter(award_id=OuterRef('award_id'),transaction_date=OuterRef('transaction_date'),transaction=OuterRef('transaction'))\ .values('negative_balance') ))\ .annotate(total_awarded=SubquerySum("award__total_awarded"))\ .annotate(running_balance=F('total_awarded')-F('negative_balance')) #This doesnt work correct, we need transaction date to be less than or eqaul not just the transaction date. #filtering on distinct, we only want one of each record, doesnt matter which one. :) distinct_pk = queryset.distinct('transaction_date','award_id','transaction').values_list('pk',flat=True) queryset = queryset.filter(pk__in=distinct_pk) What needs to be fixed: .annotate(negative_balance=SubquerySum( totals.filter(award_id=OuterRef('award_id'),transaction_date=OuterRef('transaction_date'),transaction=OuterRef('transaction'))\ .values('negative_balance') The above should really be: .annotate(negative_balance=SubquerySum( totals.filter(award_id=OuterRef('award_id'),transaction_date__lte=OuterRef('transaction_date'))\ .values('negative_balance') It will return multiple rows if I do this, what I want to do is sum those multiple rows on negative_balance. Hope the above makes sense. Any help will be greatly appreciated. Thanks, Thomas Lewin -
django rest: AssertionError at /api/v1/users/1/ 'UserDetail' should either include a `queryset` attribute, or override the `get_queryset()` method
I'm trying to follow a tutorial from the book 'Django for APIs', this tutorial consists on doing a blog project API with django rest framework. I cant get to work the UserDetail view at url: 'http://127.0.0.1:8000/api/v1/users/int:pk/' it raises the following error ,although queryset is defined in the UserDetail class in views.py: AssertionError at /api/v1/users/1/ 'UserDetail' should either include a queryset attribute, or override the get_queryset() method. here is the code: urls.py views.py serializers.py models.py urls.py: from django.urls import path from .views import UserList, UserDetail, PostList, PostDetail urlpatterns = [ path('users/',UserList.as_view()), path('users/<int:pk>/', UserDetail.as_view()), path('',PostList.as_view()), path('<int:pk>/', PostDetail.as_view()), ] views.py: from django.contrib.auth import get_user_model from rest_framework import generics from .models import Post from .permissions import IsAuthorOrReadOnly from .serializers import PostSerializer, UserSerializer # Create your views here. class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (IsAuthorOrReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer class UserList(generics.ListCreateAPIView): queryset = get_user_model().objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveUpdateDestroyAPIView): queryset_= get_user_model().objects.all() serializer_class = UserSerializer serializers.py: from django.contrib.auth import get_user_model from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: fields = ('id','author','title','body','created_at',) model = Post class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ('id','username',) models.py: from django.db import models from django.contrib.auth.models import User # … -
How to improve myself to become a full-stack freelancing developer in the aspect of technicalities and career?
I started learning coding from 5 months. My goal is to work as a full-stack web freelancing developer. I have learned programming basics (cs50) and then learned python through Youtube courses. Then I learned HTML and CSS also on youtube. Finally, I learned Django, Javascript needed for interactive client-side interface (like DOM, event listeners, fetch, API) by CS50 web programming with python and Javascript. I have applied what I learned on 5 projects (mail, auctions(e-commerce), Twitter like web site, bookstore, and google like interface). Know I'm confused about two points. The first point is what is the most compatible front-end framework that I can use with Django which will help me make better projects. The second thing is how can I work as a freelancer and any suggestions for courses or anything that will help me start my career as a freelancer. And finally, if there are any suggestions for libraries, frameworks or programming languages that will help me improve my projects and myself in web development? to summarize my questions in points: What is the best front-end framework that works and is compatible with Django? What should I do to become a full-stack freelancer (I have good experience with … -
Comparing sensor data and sending warning to Django website when below threshold
I'm able to read data from a flow sensor into python terminal and now I need to compare it to a threshold value and if it's below I need to send warning to a Django website I have created. Can anyone help with this? Thank you -
How to Ban Webmail Registration in a Django Application
How can I effectively ban: 1) Webmail (GMail, Outlook, Yahoo! and so on); and 2) Free, temporary e-mail addresses (like EmailOnDeck, 10minutemail, Mailnator) registrations in my Django Application? Is it possible to solve this problem only using built-in, Django validations? Do some Mail Sender Tool offer this feature out of the box? Thanks. -
Accordion element makes whole page move
When opening a long text accordion, the whole page (or the whole div) moves slightly. I attach a little video to show the problem visually here. I have the accordions displaying information from a django template engine loop, here's the template code: <div class="accordion accordion-borderless" id="accordion_{{ forloop.counter }}"> <div class="accordion-item"> <h2 class="accordion-header" id="heading_{{ forloop.counter }}"> <button class="accordion-button collapsed" type="button" data-mdb-toggle="collapse" data-mdb-target="#collapse_{{ forloop.counter }}" aria-expanded="false" aria-controls="collapse_{{ forloop.counter }}" > {{event.title}} </button> <div id="collapse_{{ forloop.counter }}" class="accordion-collapse collapse" aria-labelledby="heading_{{ forloop.counter }}" data-mdb-parent="#accordion_{{ forloop.counter }}"> <div class="accordion-body"> {{event.description|safe}} </div> </div> </div> </div> What is causing that movement and how can it be solved? -
Time before full counter with percent python
how to calculate based on timestamp and get the progress before the max full value? def full_energy(): time_now = 1666650096 #changes every update time_end = 1666679529 max_energy = 50 diff = datetime.utcfromtimestamp(time_now) - datetime.utcfromtimestamp(time_end) secs = diff.total_seconds() ??? # expected output # x/y (z) # 25/50 (50%) how to get the value of x and z based on this sample? -
Return Redis cached Django views with rendered React
I recently started using Django and as many Django lovers out there would say, there is nothing that beats its admin interface, auth and users out of the box. The issue is, the template syntax. That's why I am trying to integrate it with React, but I am struggling to figure out how to use Vite for development and production, but getting served from the Django server so the views are cached with Redis. I guess I am trying somehow to reinvent Next.js concept of Incremental Static Generation but in Django. What I am trying to achieve is a website where pretty much all text, titles, descriptions, images, etc. will be retrieved from a Django model that the admin can change, but it will barely be changed in the first place, thus the use of Redis an caching the views. A SPA where the html is rendered first and then the text is retrieved from an API is the solution I am trying to get away from as that affects the SEO. It could be considered Server Side Rendering (returns html with already parsed data) but caching the view. Thank you in advance. -
How to save multiple model object instances using one single form in django?
I have the three following models: class AnswerItem(models.Model): item_name = models.CharField(max_length=320) item_number = models.PositiveIntegerField() class AnswerMenu(models.Model): menu_name = models.CharField(max_length=320) answer_item = models.ForeignKey(AnswerItem) class QuestionAnswer(models.Model): answer = models.ForeignKey(AnswerMenu) answer_item = models.ForeignKey(AnswerItem) Answer menus are currently displayed on a single page using a list view, with the following template: {% for answer_menu in answer_menus %} <div>{{ answer_menu.menu_name }}</div> {% for answer_item in answer_menu %} <p> <label> <input id="{{ answer_item.pk }}" name="{{ answer_menu.pk }}" type="radio"> </label> </p> Now, the trouble I have is I would like to create a single form to save all selected answers using the radio buttons on the page. Since there are multiple answer menus shown on the page, posting through this form would create several QuestionAnswer items. How would you approach this? -
Django user model override
I'm not advanced in Django and would like to know how and if it's possible to do it. I need to override Django's user model, and change the fields "username" to "sr_usuario" and "password" to "sr_password", but I would like to continue using all Django's default authentication scheme and permissions. I want not only to change the description in the database or a label, I want to change the name of the field in the model, for when for example I needed to make a query, I would use User.objects.filter(sr_usuario="user_name") and everything would work usually. It's possible? I couldn't find anything in the documentation or on forums I've searched. Thank you very much in advance! -
Hello! Help to make dependent <select> from a database
Help to make dependent from a database. enter image description here I don't know how to configure this dependency between database tables. if possible, tell me how, or show an example of how to implement it. the tables in the database are configured one-to-many, and so many dependencies need to be made. models.py class Car_mark(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name.title() class Meta: verbose_name = 'Марка' verbose_name_plural = 'Марки' class Car_model(models.Model): model = models.ForeignKey(Car_mark, on_delete = models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name.title() class Meta: verbose_name = 'Модель' verbose_name_plural = 'Модели' class Car_engin_type(models.Model): engin = models.ForeignKey(Car_model, on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name.title() class Meta: verbose_name = 'Двигатель' verbose_name_plural = 'Двигатели' views.py class MarkList(ListView): model = Car_mark ordering = 'name' template_name = 'index.html' context_object_name = 'marka' class ModelList(ListView): model = Car_model ordering = 'name' template_name = 'index.html' context_object_name = 'model' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', MarkList.as_view()), path('', ModelList.as_view()), index.html {% load static %} <!DOCTYPE html> <html lang="ru"> <head> <link rel="stylesheet" href="{% static 'Zayavky/css/stail.css' %}"> </head> <body> <h1>Выберите автомобиль:</h1> <label> <select class="select-css"> {% for el in marka %} <option>{{ el }}</option> {% endfor %} </select> </label><br> <label> <select class="select-css"> {% for el2 in model %} <option>{{ … -
Django - how to export and import user data for database migration?
I am moving my website to another cloud server for delpoying, so I have to export all the user information (account name, password, accounts.profile from the existing database, then import to the new website hosted by the new server. I have tried to export user data using default: python manage.py dumpdata > users.json the users.json looks like: [{"model": "accounts.profile", "pk": 1, "fields": {"user": 2, "telephone": "0755-25187181", "company_name": "watchtech"}}, {"model": "accounts.profile", "pk": 2, "fields": {"user": 3, "telephone": "18696511023", "company_name": "King's Machinery"}},....}}] I noticed there is no password information exported. when I use "python manage.py loaddata user.json", how to ensure it also loads the password of users, so that users can login the new website? -
FOREIGN KEY constraint failed Django Models
I'm creating a small-ish django application using AllAuth for the authetncation, which I have customised myself to include some additional fields. Part of the sites functionality requires me to refrence the logged in user through a Foreign Key multiple times and I'm approaching this through the custom model I created, called UserProfile; (I tried Django's User model & this also gave me errors) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') phone_number = models.CharField(max_length=30, null=False) postcode = models.CharField(max_length=500, null=True, blank=True) town_or_city = models.CharField(max_length=40, null=True, blank=True) street_address1 = models.CharField(max_length=80, null=True, blank=True) street_address2 = models.CharField(max_length=80, null=True, blank=True) county = models.CharField(max_length=80, null=True) I'm referencing the above model in the activity table: class Activity(models.Model): class Meta: verbose_name_plural = 'Activities' activity_id = models.CharField(max_length=32, null=False, editable=False) host = models.ForeignKey(UserProfile, on_delete=models.CASCADE) name = models.CharField(max_length=254, null=False, blank=False) date = models.DateField() start_time =models.TimeField() end_time = models.TimeField() duration = models.DurationField(blank=True, null=True) location = models.CharField(max_length=40, null=False, blank=False) description = models.CharField(max_length=140, null=False, blank=False) available = models.BooleanField(default=True) Everything works smoothly, as I can use this to create one activity per user, however I want to make this a Many to One field, which required me to update from settings.AUTH_USER_MODEL to the Foreign Key. Unfortunately, I'm getting the following error: FOREIGN KEY constraint failed when … -
How to get information from option field in django?
I have django application with authentication and I have dropdown menu inside. Before I did it like: <select name="country" id="id_category" data="{{ data.country }}"> {% for each in living_countries_list %} <option name="country" value="{{ each.0 }}" class="living_countries">{{ each.1 }}</option> % endfor %} </select> And now I changed it to: <input list="brow" placeholder="Search for your country..." class="input_country"> <datalist id="brow"> {% for each in living_countries_list %} <option name="country" value="{{ each.0 }}" class="living_countries">{{ each.1 }}</option> {% endfor %} </datalist> <p class="country_text">Please select your living country</p> In my views.py file I passed context like: country = request.POST.get('country') professors = models.Professor.objects.all() living_countries_list = LIVING_COUNTRIES print(country) In models.py I have options like: LIVING_COUNTRIES = [ ('AFGANISTAN', 'Afganistan'), ('ALBANIA', 'Albania'), ('ALGERIA', 'Algeria'), ('ANGORRA', 'Andorra'), ('ANGOLA', 'Angola')] class Professor(models.Model): country_living = models.CharField(max_length=50, choices=LIVING_COUNTRIES, default=FRESHMAN, blank=True, null=True) So I have few options which are displayed either way but in changed I can type in input and that's what I want to be able to do. If you want me to post anything else let me know in comments -
How to copy a "default" company and all related data to a new user? [closed]
Every time a user is created I must create a copy of a "default" company already existing in the database, to be assigned to this new user. The problem is that the company table is related to other tables, for example invoices, bills, etc. The idea would also be to copy these. Since a complete copy of this company should be made, so that the new user can work with it without affecting the original one that is being copied. One thing I had thought of was to make a script that does all this process, creating the tables with these "default" values but I think there must be a better approach to this problem out there. -
Django production pages where there images-media is very slow
I just deployed my small django app on a ubuntu server using Apache. The site work fine but the page where it show images from database is extremely slow and loading forever. (I can see the picture/image though) here is how I display the image {% for photo in photos %} <div class="col-sm-12 col-md-6 col-lg-6"> <img class="card-img-top" src="{{photo.image.url}}" alt="Card image cap"> {% endfor %} My images folder is placed like this mysite --> main --> static --> images --> settings.py STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIR = [ BASE_DIR / 'static', ] MEDIA_ROOT = os.path.join(BASE_DIR, 'main/static/images') STATIC_ROOT = '/var/www/mysite/static/' I am not sure what causing this page to be slow. -
How to deploy Python Celery worker on EC2 (current error 111: Connection refused)?
Technologies: Python, Django, AWS, RabbitMQ on AWS, Celery I currently have my company's website deployed on an EC2 instance. Everything works well, my current tasks is to run a Celery worker but every time I attempt to do so I get the 111:Connection refused error. Celery runs, RabbitMQ is running but my assumption is that I can possibly not have the correct setup since I have everything within their correct VPCs and security groups. FILES: settings.py CELERY_BROKER_URL = 'amqps://<username>:<password>@<awspath>.mq.us-west-2.amazonaws.com:5671' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_TASK_DEFAULT_QUEUE = env("CELERY_TASK_DEFAULT_QUEUE", default="default") CELERY_BROKER_TRANSPORT_OPTIONS = { "region": env("AWS_REGION", default="us-west-2"), } CELERY_RESULT_BACKEND = None procfile celery: celery -A bsw_site worker -l INFO init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) error log 2022/10/20 20:57:13 [error] 4189#4189: *35 connect() failed (111: Connection refused) while connecting to upstream, client: 10.176.11.163, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "<company_website_link>", referrer: "<company_website_link>" nginx_conf.conf user nginx; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; worker_processes auto; worker_rlimit_nofile 200000; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; fastcgi_read_timeout 7200; proxy_read_timeout 7200; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; include conf.d/*.conf; map $http_upgrade $connection_upgrade { default … -
Can I use image hyperlink from the model content to show in my poster image in django templates?
OK so this might sound a bit weird. so im using ckeditor for my content field. So I want to for example run a loop in my template in my content instance. And find "<img" and if its found I wanna check if there is a "/>" so upon finding those I wanna grab the link from that image tag and add that link to my templates poster image in this line - <img src="{% static 'app/images/movie-poster.jpg' %}" width="100px" /> So basically when a user posts if that posts body contains any image then the first image will be added as the poster. So the default poster wont show. Is it possible to do that from template? Sorry im a noob and thats just some solution I thought of and looking for some code logic here. If its posssible then how can i do that ? I have a model which is this - class List(models.Model): title = models.CharField(max_length=120) genre = models.ManyToManyField('Genre') creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True) posted = models.DateTimeField(auto_now_add=True) content = RichTextField(null=True,default=' ') type = models.CharField(max_length=10,default="Movie") spoiler_choices = [(False, 'No'),(True, 'Yes')] spoiler = models.BooleanField(default=False,null=True, choices = spoiler_choices) slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True) def __str__(self): return f'{self.title}|{self.creator}' def … -
Respond an array of json objects in Django view
I have this table or model: longitude latitude session 12 34 1 99 42 2 99 42 1 99 42 3 99 42 1 99 42 2 I need to make a query to get all data by session. So I get all the data from the table and apply 'distinct' to get the sessions: sessions= GPSData.objects.values('session_new_id').distinct() I get: <QuerySet [{'session': 1}, {'session': 2}, 'session': 3}]> Now, for each session I need to get longitude an latitude. Afterwards I need to send an HttpResponse with the data in a JSON. So I'm trying in my view: def get_all_gps(request): data=[] for session in sessions: y=GPSData.objects.filter(session=session['session']) y = serializers.serialize("json", y) data.append(y) return HttpResponse(data, content_type='application/json') I get an error in the template because I am passing an array not a json object: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 190986 of the JSON data In general what I need is to respond with an array of JSON objects. Something like this: [[{json from session 1}],[{json from session 2}],[{json from session 3}]] Can this be done? -
Sync PostgreSQL and Django project
I had a legacy database which I uploaded to PostgreSQL and connected it with Django. Then, I changed DB with running SQL scripts directly in the PostgreSQL (I deleted few columns), then manually deleted few columns in django models.py. Since then, I cannot make any migrations, whenever I try it, Django is trying to delete the column which I manually deleted, and gives the error below. How do I sync my DB and Django project so that I can make modifications to the project? django.db.utils.ProgrammingError: column "confidence" of relation "Location" does not exist -
Can I use a form's is_valid function for DRF submitted data?
I have a form (not a ModelForm) with custom validators that's working fine. Now need to add an API for submitting the same data. Is it possible to use the form's is_valid() function to validate the data? I tried populating a new form instance using initial, but the form is never valid. Tried in the shell with a simple form and saw the same thing. # ./manage.py shell Python 3.6.10 (default, Jan 17 2021, 19:51:05) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django import forms >>> class DogForm(forms.Form): ... name = forms.CharField(max_length=6) ... age = forms.IntegerField() ... >>> df = DogForm(initial={'name':'Rex','age':3}) >>> df.is_valid() False I'm missing a step somewhere...