Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect 2 models in the admin, if they are already connected OnetoOne?
models.py from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) Every time for new user(when he registers) I must choose user in admin('in Customer model') https://prnt.sc/waTmROxj3-xn(screenshot), if I don't choose a new user I have error RelatedObjectDoesNotExist at / User has no customer. How to do it automatically? What I did do wrong? It is possible to catch this exception, but then what data should be added to the customer to connect it? It won't change the user's flag to his own(https://prnt.sc/waTmROxj3-xn(screenshot)): views.py def cartData(request): if request.user.is_authenticated: try: customer = request.user.customer except ObjectDoesNotExist: customer = ? order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return {'cartItems': cartItems, 'order': order, 'items': items} -
RuntimeError: There is no current event loop in thread 'Thread-1' in Django project
I have a Django project that should parse some data from a particular web-site and saves the data into the database. In the app I use requests_html that is somehow dependant on asyncio which raises an error each time i'm trying to make a request. (I have to use requests_html, not beautifulsoup because I need scripts to be rendered into html) Here is the isolated problem: # project/app/render_js.py import requests_html def render_js(url): session = requests_html.HTMLSession() r = session.get(url) r.html.render() return r.html.text # project/project/views from django.http import HttpResponse from app.render_js import render_js url = 'some url' def view(request): print(render_js(url)) return HttpResponse("<h1>success!</h1>") # project/project/urls from django.urls import path from .views import view urlpatterns = [ path('', view) ] While attempting to make a GET request to http://127.0.0.1:8000/ throws: Internal Server Error: / Traceback (most recent call last): File "C:\Users\User\PycharmProjects\project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\User\PycharmProjects\project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\PycharmProjects\project\project\views.py", line 6, in view print(render_js('https://docs.python.org/3.7/library/threading.html#threading.Thread.run')) File "C:\Users\User\PycharmProjects\project\app\render_js.py", line 7, in render_js r.html.render() File "C:\Users\User\PycharmProjects\project\venv\lib\site-packages\requests_html.py", line 586, in render self.browser = self.session.browser # Automatically create a event loop and browser File "C:\Users\User\PycharmProjects\project\venv\lib\site-packages\requests_html.py", line 727, in browser self.loop = asyncio.get_event_loop() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\asyncio\events.py", line 642, in … -
'NoneType' object has no attribute 'add' in Django Models
I have the next:'NoneType' object has no attribute 'add'. When I try to add a value to a null field (null=True) with auction.winner.add(u) it gives me that exception. I am working with Django Models and it looks like is not allowed to add a value to a null Field almost with this method. U know is there some way to do this? Thank U. -
Using a Class Based View, how do I add form kwargs without calling the form?
I have a model app/models.py: from django.db import models class MyModel(models.Model): my_field = models.Charfield(max_length=100, blank=True, null=True) I have a form in app/forms.py: from django import forms class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): custom_data = kwargs.pop('custom_field', None) super().__init__(*args, **kwargs) class Meta: fields = ['my_field'] And I have a CBV in app/views.py: from django.views import generic from .forms import MyForm class MyFormView(generic.FormView): template_name = 'my_form_template.html' form_class = MyForm Basically I want to be able to add some custom fields from my abstract User model which the form requires. I dont want to have some crazy context overrides, I just want to ensure the form always has the extra data upon initilisation. Any ideas? -
Django smtp cache with sendgrid
Since gmail smtp is not working, I am testing sendgrid smtp. It is working fine on a local host, but I cannot update it on a production site, because credentials cached there. I tried to clear cache with: python3 manage.py clearcache and from shell, but it is still now working. How can I make it work. -
Django CBVs: reuse query from get_queryset in get_context_data method in ListView
I need to pass a Tag object to the template, but without an additional query to the database in get_context_data method. Can you please tell me if there is a more elegant way to get the value from the get_queryset method in the get_context_data. And if there is a more elegant way, is it correct to declare your own fields in Django views class PostListView(ListView): model = Post paginate_by = 3 context_object_name = 'posts' template_name = 'blog/post/list.html' tag = None def get_queryset(self): data = super().get_queryset() if tag_slug := self.kwargs.get('tag_slug'): self.tag = get_object_or_404(Tag, slug=tag_slug) data = data.filter(tags__in=[self.tag]) return data def get_context_data(self, *, object_list=None, **kwargs): data = super().get_context_data(**kwargs) data['tag'] = self.tag return data -
Can't deploy to Heroku when my app uses Neomodel, because it wants to install Shapely>=1.7.1,<1.9 but it selects 1.7.1 which can't find geos_c.dll
The Django / Neo4j app I would like to deploy is this: https://github.com/enjoysmath/DiagramChasingGames Auto building on Heroku crashes with: -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> No Python version was specified. Using the buildpack default: python-3.10.6 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.10.6 -----> Installing pip 22.1.2, setuptools 60.10.0 and wheel 0.37.1 -----> Installing SQLite3 -----> Installing requirements with pip Collecting django Downloading Django-4.1-py3-none-any.whl (8.1 MB) Collecting gunicorn Downloading gunicorn-20.1.0-py3-none-any.whl (79 kB) Collecting django-heroku Downloading django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB) Collecting requests Downloading requests-2.28.1-py3-none-any.whl (62 kB) Collecting neomodel Downloading neomodel-4.0.8-py3-none-any.whl (46 kB) Collecting django-neomodel Downloading django_neomodel-0.0.7-py3-none-any.whl (14 kB) Collecting dj-database-url Downloading dj_database_url-1.0.0-py3-none-any.whl (6.6 kB) Collecting whitenoise Downloading whitenoise-6.2.0-py3-none-any.whl (19 kB) Collecting bidict Downloading bidict-0.22.0-py3-none-any.whl (36 kB) Collecting django-bootstrap5 Downloading django_bootstrap5-21.3-py3-none-any.whl (24 kB) Collecting psycopg2 Downloading psycopg2-2.9.3.tar.gz (380 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Collecting sqlparse>=0.2.2 Downloading sqlparse-0.4.2-py3-none-any.whl (42 kB) Collecting asgiref<4,>=3.5.2 Downloading asgiref-3.5.2-py3-none-any.whl (22 kB) Collecting charset-normalizer<3,>=2 Downloading charset_normalizer-2.1.0-py3-none-any.whl (39 kB) Collecting certifi>=2017.4.17 Downloading certifi-2022.6.15-py3-none-any.whl (160 kB) Collecting idna<4,>=2.5 Downloading idna-3.3-py3-none-any.whl (61 kB) Collecting urllib3<1.27,>=1.21.1 Downloading urllib3-1.26.11-py2.py3-none-any.whl (139 kB) Collecting neobolt==1.7.17 Downloading neobolt-1.7.17.tar.gz (183 kB) Preparing metadata (setup.py): started Preparing … -
Converting Nested SQL to ORM in Django
I have a Query Like this SELECT *, ( SELECT COALESCE(json_agg(product_attribute), '[]') FROM ( SELECT * FROM optimus_productattribute as product_attribute WHERE product.id = product_attribute.product_id ) AS product_attribute ) AS product_atttribute FROM optimus_product as product inner join optimus_store as store on product.store_id = store.id and I want to convert it to ORM Have Tried JSONBAgg but it says it can only be used to have Single Column Product.objects.filter(store_id=787).annotate(attributes=Coalesce(JSONBAgg(ProductAttribute.objects.filter(product=OuterRef('pk')).values_list('id', 'uuid')),[])) -
Invoice system with multiple companies/users DJANGO
I need help with creating an invoice system in Django, stucked with models, how to orginize data. The idea is that one user can be in different companies and one company can have multiple users. One company can have multiple invoices with an unlimited number of products. For example: CompanyA sends an invoice with custom products to CompanyB CompanyB receives an invoice from CompanyA and sends a debit note to CompanyA. So, Company could be either a Supplier and a Customer. I tried to make some DB scheme, maybe it would be easier to understand what I try. Sample database scheme -
Filter by URL Kwargs while using Django FilterSets
I have an endpoint that can follow this format: www.example.com/ModelA/2/ModelB/5/ModelC?word=hello Model C has a FK to B, which has a FK to A. I should only ever see C's that correspond to the same A and B at one time. In the above example, we should... filter C by those with an FK to B id = 5 and A id = 2 also filter C by the field 'word' that contains hello. I know how to use the filter_queryset() method to accomplish #1: class BaseModelCViewSet(GenericViewSet): queryset = ModelC.objects.all() class ModelCViewSet(BaseModelCViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin): def filter_queryset(self, queryset): return queryset.filter(ModelB=self.kwargs["ModelB"], ModelB__ModelA=self.kwargs["ModelA"]) I also know how to use a Filterset class to filter by fields on ModelC to accomplish #2 class ModelCFilterSet(GeoFilterSet): word = CharFilter(field_name='word', lookup_expr='icontains') But I can only get one or the other to work. If I add filterset_class = ModelCFilterSet to ModelCViewSet then it no longer does #1, and without it, it does not do #2. How do I accomplish both? Ideally I want all of this in the ModelCFilterSet Note - As hinted by the use of GeoFilterSet I will (later on) be using DRF to add a GIS query, this is just a simplified example. So I think … -
Static Files Django - HEROKU
When I turn off the PC and turn it back on and try to edit a static file on django this doesn't work. To make it work I have to rename it, and since I use HEROKU to host my site I don't want to use this method. Is there an alternative for not renaming static files and making them work anyway? -
Image links in included static CSS file not being signed using S3Boto3Storage with Django-Storages
I'm using django-storages (S3Boto3Storage) to upload my media files and libraries to S3 buckets. On my test page "delete_me.html", I include a CSS page from the datatables library, jquery.dataTables.min.css, which includes a link to an image. Including the CSS file in delete_me.html: <link rel="stylesheet" type="text/css" href="{% static "js/DataTables-1.11.5/css/jquery.dataTables.min.css" %}"> in jquery.dataTables.min.css: thead .sorting_asc{background-image:url("../images/sort_asc.png") !important}. when I look at the network tab of the chrome debugger, the CSS gets loaded using a signed URL. get request with status 200 OK for: https://mybucketname.s3.amazonaws.com/js/DataTables-1.11.5/css/jquery.dataTables.min.css?X-Amz-Algorithm=ALG_REDACTED&X-Amz-Credential=CREDENTIAL_INFO_REDACTED%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20220804T011840Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=SIGNATURE_REDACTED as I should. However, the sort_asc.png image does not get loaded. The request is to an unsigned URL: https://mybucketname.s3.amazonaws.com/js/DataTables-1.11.5/images/sort_both.png and returns a 403. I'm not sure if the Django static library is responsible for this or if it's django-storages issue. Because it's a third-party library, there's no {% load static %} in the CSS file (and I'm not sure if it would be run through the django templating system anyway). How do I get that image to load without making the image file accessible to the public at large? -
Mixed Content: The page at {URL} was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint {ENDPOINT}
I have the following projects https://github.com/codyc4321/dividends_ui and https://github.com/codyc4321/stocks_backend. The deployed app at https://octopus-app-8l8j5.ondigitalocean.app/ is getting error Mixed Content: The page at 'https://octopus-app-8l8j5.ondigitalocean.app/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://67.205.161.47:8000/dividends/wba'. This request has been blocked; the content must be served over HTTPS. this is the error I got last week but now I have gone through and done https://timonweb.com/django/https-django-development-server-ssl-certificate/ and am running the python server with https: root@username:~/stocks_backend# python3 manage.py runserver_plus --cert-file cert.pem --key-file key.pem I do not understand why my app isn't working for the request, although I notice that BEFORE using the cert file I could hit an endpoint from my local machine just fine, and now after it my local machine gets Error: connect ECONNREFUSED 67.205.161.47:8000 Why running the server using cert and key files for https not sufficient to make this api request? Thank you -
Filter many-to-many object with specific value
I have the current filter this filter works, but I also want to filter the objects inside my quotation if the user matches. If I have 2 itens, one is from the user 1 and the other from user 2, when I filter the quotation using user 1, I also want to see only the item that has the specified user. Thus, instead of this I want this -
how to containerize a Django project with Oracle Database
I am trying to containerize my Django project and set up a docker image for the Oracle Database. I am getting an error while I run docker-compose build: service "oracle-db" refers to undefined volume oracle: invalid compose project My docker-compose file is: version: "3" services: django: build: context: . dockerfile: django.Dockerfile image: kanbanboard_django restart: unless-stopped volumes: - "django-static:/app/django-static" - "media:/app/media" - "./backend/settings:/app/settings" env_file: - .env depends_on: - oracle-db certbot: image: certbot/certbot entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'" volumes: - "./data/certbot/conf:/etc/letsencrypt" - "./data/certbot/www:/var/www/certbot" oracle-db: image: sath89/oracle-19c volumes: - oracle:/u01/app/oracle/ env_file: - .env volumes: media: django-static: -
How to bulk_update in related fields modified using only one call
I'm working with two tables to change some data in there but I'm wanted to avoid two calls using bulk_update as following: queryset = MyModel.objects.all() submodels_to_upcate = [] for instance in queryset: instance.submodel = process() instance.submodel.sub_property = some_random_data() submodels_to_update.append(instance.submodel) MyModel.objects.bulk_update(queryset, ['submodel']) SubModel.objects.bulk_update(submodels_to_update, ['sub_property']) What I wanted to do is something like the following: MyModel.objects.bulk_update(queryset, ['submodel', 'submodel__sub_property']) My question here is if there is a way to achieve bulk_update in two different tables at the same time. -
Get User Password
Is there any way to get the password of the registered user? My app uses the same password to do other operations, so I need the user's password, but when I put {{request.user.password}} it comes encrypted -
How can i change file directory's name related to an instance's field too after the field get updated in Django's model
good day everyone, i am a self learner and quite new to django and i am facing some questions currently, i created a model which will have images upload to a self-defined directory as like this: class OverwriteStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): self.delete(name) return name class DealerList(models.Model): def user_dir_folder(instance, filename): return 'dealerImg/{0}/{1}'.format(instance.dealerCompanyName, filename) dealerCompanyName = models.CharField(max_length=100) Cert = models.ImageField(storage=OverwriteStorage(), upload_to=user_dir_folder) Img = models.ImageField(storage=OverwriteStorage(), upload_to=user_dir_folder) and i installed ‘django_cleanup.apps.CleanupConfig’ into the settings file to cleanup those related files in case if an instance is deleted (but the empty folder stay existed which i dont know how to deal with yet, but this is second question). now what i am facing is, if an instance’s ‘dealerCompanyName’ field is updated, the folder which created named with the ‘dealerCompanyName’ won’t get updated along (also django will delete those uploaded files that cant match any instance now after ‘dealerCompanyName’ is updated since i installed cleanup, but this is the third question), what i wanna ask is, is there anyway to update that folder’s name too if ‘dealerCompanyName’ field get updated? by the way if there are answer for the second and third questions mentioned above will be very very appreciated since i will face them … -
How to handle request methods in function based views in Django
As I am learning Django I have some questions about the handling of request methods for function based views (FBVs) in Django. What I found for FBVs: The URLconf doesn’t look at the request method. In other words, all request methods – POST, GET, HEAD, etc. – will be routed to the same function for the same URL. from URL-Dispatcher. require_http_methods(request_method_list)¶ Decorator to require that a view only accepts particular request methods from View Decorators Does that mean, I can restrict an URL defined in urls.py to a function which in turn only accepts say PUT-Requests and in case I want to handle DELETE said URL is wasted, since I restricted it to PUT? Or otherwise, I have to "dispatch" myself within the FBV? E.g. with request.method == 'PUT' Alternatively for CBVs Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching. from Introduction to class-based views Does that mean, if I want to handle PUT or DELETE in separate functions I have to a) use a class based view with the verbs being implemented like put() and delete() b) use DjangoResteFramework only for having APIViews and @api_view(['Put']) as … -
Django 1.10 or later: base.html override not working
I am creating a site in Django with a custom view, and want to link to that view on the admin page. But even though I've followed the directions to override in Documentation or Youtube, but i won't show the changes in the overide file. {% extends "admin/base.html" %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">Test</a></h1> {% endblock %} {% block nav-global %}{% endblock %} My base.html in ratonix\templates\admin Map tree: └─ratonix ----└── ratonix ----------└── settings.py ----------└── views.py ----------└── urls.py --- └── templates -----------└── admin - ------------ └── base.html └── manage.py Templates folder in the same folder as manage.py This is my current settings.py: """ Django settings for ratonix project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import pymysql import os pymysql.install_as_MySQLdb() from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY … -
I got KeyError at /cart/add/3/ 'quantity' in my django shop application and I am still unable to debug it
I got KeyError at /cart/add/3/ 'quantity' in my django shop application and I am still unable to debug it cart.py from decimal import Decimal from django.conf import settings from shopapp.models import Product class Cart(object): def __init__(self, request): #initialize the cart self.session=request.session cart=self.session.get(settings.CART_SESSION_ID) if not cart: #save an empty cart in the session cart=self.session[settings.CART_SESSION_ID]={} self.cart=cart #Access the related products in the cart through iteration #i.e iterate over the items in the cart and get the products from the database def __iter__(self): product_ids=self.cart.keys() #get the products objects and add them to the cart products=Product.objects.filter(id__in=product_ids) cart=self.cart.copy() for product in products: cart[str(product.id)]['product']=product for item in cart.values(): item['price']=Decimal(item['price']) item['total_price']=item['price'] * item['quantity'] yield item #adding a total price attribute #counting all items in the cart def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def add(self, product, quantity=1, override_quantity=False): #Add a product to the cart or update its quantity product_id=str(product.id) if product_id not in self.cart: self.cart[product_id]={'quantity':0, 'price':str(product.price)} if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): #mark the session as modified to make sure it gets saved self.session.modified=True def remove(self, product): #remove a product from the cart product_id=str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() #Calculate the total cost of items in the cart … -
the attribute 'type' and a xs:complexType local declaration are mutually exclusive
<xs:element maxOccurs="1" name="Field" type="withKey"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="Applicants" type="Applicants"/> </xs:sequence> </xs:complexType> </xs:element> I have the following tags in one of my xsd files, while executing the above code, I am getting the error xmlschema.validators.exceptions.XMLSchemaParseError: the attribute 'type' and a xs:complexType local declaration are mutually exclusive Running my code on Python 3.9 and django 4.1. Please help me with the solution, thanks in advance. -
Google Cloud App engine Internal Error 500 when deploying updates
I am using pycharm for deployments on gcloud django python project and getting this in the error log. No errors when deploying but the page won't open to the homepage or any other and only gives an Internal 500 error message: Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.7/site- packages/gunicorn/workers/sync.py", line 134, in handle self.handle_request(listener, req, client, addr) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 175, in handle_request respiter = self.wsgi(environ, resp.start_response) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception callback, param_dict = resolver.resolve_error_handler(500) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/urls/resolvers.py", line 601, in resolve_error_handler callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/layers/google.python.pip/pip/lib/python3.7/site-packages/django/urls/resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "/opt/python3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
Is there a simple way to update the data of a form rendered with django-forms
i am fairly new to django and im trying to render a django form and update its content with an ajax request to an API. So i got a form like this: from django import forms from models import ExampleModel class ExampleForm(forms.ModelForm): name=forms.CharField() comment=forms.CharField(widget=forms.Textarea()) class Meta: model = ExampleModel fields=("name","comment") got my data from the API like this: from forms import ExampleForm from models import ExampleModel def apiGetExampleData(request,name): data=ExampleModel.objects.filter(name=name).values(*getFormFields(ExampleForm())) #if there is a better way to get the data, would be thankful to know :) JsonResponse(data[0]) def getFormFields(form): output=[] for element in form: output+=[element.name] return output Now i got the form (which renders fine), and a way to get the data. So, is there some predefined way to apply data in json format to a form in Javascript? -
Django DecimalField rejecting all values with 2 and more decimal places
I have a model: class Account(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) balance = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) with a test: @pytest.mark.django_db class TestAccount: def test_it_accepts_valid_data(self): data = {"profile_id": create_profile().id, "balance": 10.55} account = Account(**data) account.full_clean() account.save() Which fails with the exception: FAILED wallets/tests/test_model.py::TestAccount::test_models - django.core.exceptions.ValidationError: {'balance': ['Ensure that there are no more than 2 decimal places.']} Reducing the test balance to a one decimal place figure e.g 10.5 passes the test. The interesting part is increasing the decimal_places argument to a higher figure e.g 5, still raises the exception on any figure with more than one decimal place Am I missing something or is this a Django bug? I'm on python3.9 and Django 4.0.6