Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I configure i18n with django rosetta in react?
I'm writing the frontend code using react. I need to change the language on the site using Django. I don't know where to start. Should i use i18next? How can I configure if I need to use it import i18n from "i18next"; import detector from "i18next-browser-languagedetector"; import backend from "i18next-http-backend"; import { initReactI18next } from "react-i18next"; i18n .use(detector) .use(backend) .use(initReactI18next) // passes i18n down to react-i18next .init({ fallbackLng: "en", // use en if detected lng is not available saveMissing: true // send not translated keys to endpoint }); export default i18n; -
Django debug toolbar not catch query from local db
django = "4.0.8" django-debug-toolbar = "^4.3.0" drf-spectacular = "^0.26.5" Django container is connected to local database. So when call API then return response data that get from local database. But no sql query on debug toolbar panel. When I enter SQL page then only this statements are exist. SQL queries from 0 connections No SQL queries were recorded during this request. I set host.docker.internal to connect to container to local db that on host. extra_hosts: - "host.docker.internal:host-gateway" .local.env DB_ENGINE="django.contrib.gis.db.backends.postgis" DB_HOST="host.docker.internal" DEBUG=True I assigned True and False to INTERCEPT_REDIRECTS. But not worked Why django debug toolbar can not catch sql query? local_settings.py from dotenv import load_dotenv load_dotenv(".env.local") from .base_settings import * import socket DEBUG = True LOGGING["loggers"]["django"]["handlers"] = ["console", "file"] CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://127.0.0.1:8000", "http://localhost:80", "http://127.0.0.1:80", "http://localhost:3000", "http://127.0.0.1:3000", "http://host.docker.internal:8000", ] CORS_ALLOW_METHODS = [ "GET", "POST", ] INTERNAL_IPS = [ "*", "127.0.0.1", "localhost", "192.168.0.1", "10.0.2.2", "host.docker.internal", ] hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips] def show_toolbar(request): return True DEBUG_TOOLBAR_CONFIG = { "INTERCEPT_REDIRECTS": True, "SHOW_TOOLBAR_CALLBACK": show_toolbar, } if DEBUG: import mimetypes mimetypes.add_type("application/javascript", ".js", True) base_settings.py #... INSTALLED_APPS = [ "django.contrib.staticfiles", "drf_spectacular", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "real_estate", "accounts", "modu_property", "django_celery_beat", "rest_framework", "rest_framework_simplejwt", "django.contrib.gis", "debug_toolbar", "corsheaders", … -
I hosted a django project using Heroku but it keeps displaying application error. I am using gitlab
this is the error am getting this is my procfile web: gunicorn Ecom.wsgi:application and my requirements asgiref==3.7.2 attrs==23.2.0 blinker==1.7.0 certifi==2024.2.2 cffi==1.16.0 click==8.1.7 colorama==0.4.6 coverage==7.4.4 dj-database-url==2.1.0 Django==5.0.3 django-heroku==0.3.1 gunicorn==21.2.0 h11==0.14.0 idna==3.6 itsdangerous==2.1.2 Jinja2==3.1.3 MarkupSafe==2.1.5 outcome==1.3.0.post0 packaging==24.0 pillow==10.2.0 psycopg2==2.9.9 pycparser==2.21 PySocks==1.7.1 python-decouple==3.8 selenium==4.18.1 sniffio==1.3.1 sortedcontainers==2.4.0 sqlparse==0.4.4 trio==0.25.0 trio-websocket==0.11.1 typing_extensions==4.10.0 tzdata==2024.1 urllib3==2.2.1 waitress==3.0.0 Werkzeug==3.0.1 whitenoise==6.6.0 wsproto==1.2.0 and my wsgi.py """ WSGI config for Ecom project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Ecom.settings') application = get_wsgi_application() i honestly don't know what is going wrong. it keeps on stating that ecom module is not found but ecom is the name of my projectand login is the name of my app I wish for the app to run it builds and deploys the app successfully but doesnot run it -
Bulk remove many-to-many entries?
Well consider I have 1000s of users, those users are used in a many-to-many relation with "companies". Now I wish to remove all users which are "inactive" (which is the majority) from the company list. There is the trick I could use with remove: for user in User.filter(active=False): Company.customers.remove(user) However this would do also 1000s of database hits, making it really really slow. Is there a way I can do this in django? Without going to rawsql? -
django-dbbackup mediarestore causes ValueError: Cannot determine path without bucket name
I'm trying to restore my media files to my Google Cloud Storage bucket. When I run python3 manage.py mediarestore -I [FILEPATH], I get the error ValueError: Cannot determine path without bucket name. I have tried specifying my Google Cloud storage information in settings.py with: DBBACKUP_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' DBBACKUP_STORAGE_OPTIONS = { "bucket_name": "my-bucket-name", "project_id": "my-project-id", "blob_chunk_size": 1024 * 1024 } but I still get the error. Is there some other setting I need to configure? -
Creating templates and static files for Django project ( with React ) [closed]
I'm currently working on a web application using the Django Framework. In my project, I need to create several pages using React. I'm wondering whether it's better to integrate these React pages within the Django project or to develop them separately, create a build, and then include the static files within Django. I'm seeking advice on the architectural implications and the simplicity for a novice web developer. What are the pros and cons of each approach, especially considering the integration with Django and the ease of development for someone who is relatively new to web development? -
On clicking the hamburger icon on mobile devices, the navigation bar is not showing up
So, I am making a django web application, and I have designed the template to show the navigation bar when user clicks on the hamburger icon, but currently on clicking the icon, nothing is showing. HTML : <nav> <ul class="show"> <li><a href="#whatwedo">What We Do?</a></li> <li><a href="#pricing">Pricing</a></li> <li><a href="#about-page">About Us</a></li> <li><a href="#contact" class="contact-btn">Contact Us</a></li> </ul> </nav> <div class="hamburger-menu"> <div class="bar"></div> <div class="bar"></div> <div class="bar"></div> </div> CSS : @media only screen and (max-width: 768px) { nav { display: none; /* Hide the nav by default on mobile */ } .hamburger-menu { position: absolute; top: 0; right: 0; display: block; cursor: pointer; padding: 10px; z-index: 1001; /* Ensure the hamburger icon is above other elements */ } .bar { width: 25px; height: 3px; background-color: #ffffff; margin: 5px 0; } /* Show the nav links when hamburger icon is clicked */ nav ul { margin: 0; padding: 0; list-style: none; transition: transform 0.3s ease; /* Add transition property */ transform: translateY(-100%); position: fixed; top: 0; right: 0; background-color: #ffffff; border: 1px solid #ccc; padding: 10px; z-index: 1000; } nav ul.show { transform: translateY(0); /* Slide down to show menu */ } } /* Media query for larger screens (computers) */ @media only screen and … -
Django Q cannot connect to mysql
I deploy my Django, Django-Q, mysql, metabase, redis on docker, but recently, I run the services and use simpleui to change admin page, but it shows the error as follow: Traceback (most recent call last): django_q | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection django_q | self.connect() django_q | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner django_q | return func(*args, **kwargs) django_q | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect django_q | self.connection = self.get_new_connection(conn_params) django_q | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner django_q | return func(*args, **kwargs) django_q | File "/usr/local/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 247, in get_new_connection django_q | connection = Database.connect(**conn_params) django_q | File "/usr/local/lib/python3.10/site-packages/MySQLdb/__init__.py", line 121, in Connect django_q | return Connection(*args, **kwargs) django_q | File "/usr/local/lib/python3.10/site-packages/MySQLdb/connections.py", line 193, in __init__ django_q | super().__init__(*args, **kwargs2) django_q | MySQLdb.OperationalError: (2002, "Can't connect to server on 'mysql' (115)") django_q | django_q | The above exception was the direct cause of the following exception: django_q | django_q | Traceback (most recent call last): django_q | File "/app/manage.py", line 22, in <module> django_q | main() django_q | File "/app/manage.py", line 18, in main django_q | execute_from_command_line(sys.argv) django_q | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line django_q | utility.execute() django_q | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute django_q … -
How to properly set my setting.py file when using django-mongoengine with Django Rest Framework?
I'm trying to make my first migration using django and django-mongoengine. I'm rather new to the topic. When i launch my first python manage.py makemigrations, I get the following error: AttributeError: module 'mongoengine' has no attribute 'mongo_admin' ... ModuleNotFoundError: No module named 'mongoengine.mongo_admin' Here is my INSTALLED_APPS list INSTALLED_APPS when I comment #'mongoengine.mongo_admin' I get the following error: Error when commenting mongoengine.mongo_admin Here is my pip list result: (venv) PS C:\Users\sabat\Documents\Diginamic\Stage\CampingBack\Camping\WebCamping> pip list Package Version ---------------------------------- -------- asgiref 3.8.1 blinker 1.7.0 build 1.2.1 certifi 2024.2.2 charset-normalizer 3.3.2 click 8.1.7 colorama 0.4.6 Django 3.0 django-admin-honeypot-updated-2021 1.2.0 django-axes 5.27.0 django-browserid 2.0.2 django-classy-tags 3.0.1 django-cors-headers 3.11.0 django-cors-middleware 1.5.0 django-environ 0.11.2 django-filter 21.1 django-ipware 4.0.2 django-missing 1.1.0 django-mongo-auth 0.1.3 django-mongoengine 0.4.6 django-sekizai 3.0.1 djangorestframework 3.15.1 dnspython 2.6.1 environ 1.0 idna 3.6 Markdown 3.6 mongoengine 0.27.0 oauthlib 3.2.2 packaging 24.0 panda 0.3.1 pip 23.2.1 pip-tools 7.4.1 pymongo 4.6.3 pyproject_hooks 1.0.0 pytz 2024.1 requests 2.31.0 requests-oauthlib 1.3.1 setuptools 65.5.0 sqlparse 0.4.4 tweepy 4.14.0 urllib3 2.2.1 wheel 0.43.0 I haven't find any informations on this topic in the doc of mongoengine. Should I use a less recent version of django or other version of mongoengine and/or django-mongo-auth and/or django-mongoengine? Or is anybody has a working project with … -
Django Testing: Error handling in setUpTestData
I want to write a test for a data-loading command, which creates a large number (thousands) of objects variously related by foreign keys. There are two ways I might structure it Invoke the management commands in setUpTestData, and then write data consistency tests as ordinary tests Write one large test method to run the management commands, and then subtests to check the data consistency subtests are a Python unittest feature which the Django test runner inherits: with self.subTest("Subtest Foo"): self.assertFalse( True) # FAIL message includes [Subtest Foo] with self.subTest("Subtest Bar"): self.assertFalse( True) # and failure doesn't stop the next subtest from running Is there any particular reason to prefer one over the other? Does setUpTestData wrap the entire class in a DB transaction, so the tests DB is left unchanged should it fail here rather than inside one or more of the tests? Incidentally, I've never seen any reference to how to write a test that will never run unless the ./manage.py test ... command explicitly asks for it. So this might be useful to somebody: from unittest import skipIf import sys @skipIf( not 'test123' in sys.argv, "Runs only with --tag test123") @tag('test123') class Test03( TestCase): ... will run Test03 … -
query in many to many field order by first related object
in django i want to query in a many to many field that ordered by first related object. that means the queryset have to serach in the objects in the first location of many to many objects then others. as a simple incorrect sample i want to get objects like this: queryset = Practitioner.objects.filter(practices__0__city__slug='toronto') queryset += Practitioner.objects.filter(practices__other__except__0__city__slug='toronto') Note: practices is a ManyToManyField of Practice model in Practitioner model -
"GET / HTTP/1.1" 400 143 "-" "Render/1.0"
When I try to deploy Django to render, the following characters are displayed and I cannot deploy. ==> Detected service running on port 10000 ==> Docs on specifying a port: https://render.com/docs/web-services#port-detection 10.209.24.8 - - [04/Apr/2024:19:06:48 +0900] "GET / HTTP/1.1" 400 143 "-" "Render/1.0"[![enter image description here][1]][1] When I asked chatgpt, I was told that ALLOWED_HOSTS may not be set, but I think ALLOWED_HOSTS is set properly. from pathlib import Path from django.core.management.utils import get_random_secret_key import dj_database_url from dotenv import load_dotenv import os SECRET_KEY = os.environ.get('SECRET_KEY', 'xxxxxxxxxxxxxx') ALLOWED_HOSTS = ['10.209.25.170', 'django-render-xxx.onrender.com'] -
Django 'When' object is not iterable
I'm using django-filter to show work-hour of employs. models.py: ... class Attendance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Attendances") day = models.DateField() start_time = models.TimeField() end_time = models.TimeField() is_confirmed = models.BooleanField() task = models.ForeignKey(Tasks, on_delete=models.CASCADE) ... filter.py: class WorkhourFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super(WorkhourFilter, self).__init__(*args, **kwargs) start_date = ... end_date = ... self.queryset = self.Meta.model.objects.filter(user=self.request.user, day__gte=start_date, day__lte=end_date).values('task__project__title', 'task__project').annotate( raw_work_hour=Sum(F('end_time') - F('start_time'), ), confirmed_work_hour=Sum(Case(When(is_verified=1, then=F('end_time') - F('start_time'))))).order_by('task__project') I get 'When' object is not iterable error. confirmed_work_hour has problem but the raw_work_hour alone is not a problem. This query is working well in get_queryset() of corresponding View but when I trying to apply filters it'll break. trace : Django Version: 4.2.5 Python Version: 3.9.13 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'crispy_forms', 'crispy_bootstrap5', 'django_tables2', 'django_htmx', 'django_filters', 'jalali_date', 'ckeditor', 'ckeditor_uploader', 'guardian', 'django_cascading_dropdown_widget', 'dashboard.apps.DashboardsConfig', 'auth.apps.AuthConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_htmx.middleware.HtmxMiddleware'] Traceback (most recent call last): File "D:\Python\DjangoTest\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Python\DjangoTest\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\DjangoTest\venv\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "D:\Python\DjangoTest\venv\lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "D:\Python\DjangoTest\venv\lib\site-packages\braces\views\_access.py", line 438, in dispatch return super(StaffuserRequiredMixin, self).dispatch( File "D:\Python\DjangoTest\venv\lib\site-packages\braces\views\_access.py", line 375, in … -
How to display the uuid field of my serializer as a string in a get request with django restframework
Here is my serializer class AgenceSerializer(serializers.Serializer): uuid = serializers.UUIDField(format='hex',allow_null=True,required=False) <------- p1 = serializers.CharField(max_length=50,required=True) p2 = serializers.CharField(max_length=50,required=True) views.py @api_view(["POST"]) def details_agence(request): if request.method == "POST": serializer = AgenceUUIDSerializer(data=request.data) if serializer.is_valid(): agence_repr = serializer.agence_details(data=request.data) serializer = AgenceSerializer(agence_repr) print(serializer) return Response(serializer.data,status=status.HTTP_200_OK) <--------- ... a print on the serializer gives me the following: AgenceSerializer({'uudi': 'A75DF036-6C16-4311-9825-22B1295D8A26', 'p1': 'Ozangue', ...}): uuid = UUIDField(allow_null=True, format='hex', required=False) ... But when I display the data, in the response, the uuid field is always null How to solve this problem ? -
Deploy a django application that uses PostgreSQL into a cloud VM
I have a django web application which I would like to deploy in a cloud VM. As of now I am planning to deploy that into AWS EC2. Planning to use gunicorn as WSGIServer and NGINX as web server. I have gone through many documentations all of which explains in a way that the whole source code is present in the VM. Mainly I would like to know how can I package my application and deploy it? For example, in case of web applications using java, we normally creates a war file. How can we do similar thing with django? I am new to Django and Python. -
Django Static Files - CSS File loading problem
The error I am getting in the browser my project details what is the problem? How should I resolve this? every configuration is correct still not working. I am not able to upload my front in the django project. Thanks in advance -
Clearing cache when threre is change in model
I've model called Announcement and Announcement model has connected with reverse relationship with 20 another models. I cached my Announcement list API. I should clear cache, if I got changes in one of reverse related model. -
Celery Worker doesn't find the task
I use the worker in conjunction with beats and beats finds everything perfectly, but as soon as beat passes the task to the worker, an error pops up: KeyError: 'tasks.cache_popular_posts' all information: Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see https://docs.celeryq.dev/en/latest/internals/protocol.html for more information. The full contents of the message body was: b'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) The full contents of the message headers: {'lang': 'py', 'task': 'tasks.cache_popular_posts', 'id': 'bdaa8c59-8b84-4f79-af1c-7fe34468894d', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': 'bdaa8c59-8b84-4f79-af1c-7fe34468894d', 'parent_id': None, 'argsrepr': '()', 'kwargsrepr': '{}', 'origin': 'gen3644@WIN-7483UVBHTO4', 'ignore_result': False, 'replaced_task_nesting': 0, 'stamped_headers': None, 'stamps': {}} The delivery info for this task is: {'exchange': '', 'routing_key': 'celery'} Traceback (most recent call last): File "C:\Users\User\VsCodeProjects\Pastebin_hardEdition\venv\lib\site-packages\celery\worker\consumer\consumer.py", line 658, in on_task_received strategy = strategies[type_] KeyError: 'tasks.cache_popular_posts' this task #posts/tasks.py @app.task def cache_popular_posts(): try: popular_posts = Post.objects.filter(views__gt=10) for post in popular_posts: hash = post.postmeta.hash_id cache.add(key=hash, value=post) except Exception as ex: return ex #app/celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Pastebin_hardEdition.settings") app = Celery("Pastebin_hardEdition") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() #beats app.conf.beat_schedule = { 'cache-popular-post&Meta-every-30-seconds': { 'task': 'tasks.cache_popular_posts', 'schedule': 30.0, }, } app.conf.timezone = … -
Ckeditor styles not applying with my tailwind website
from django.db import models from ckeditor.fields import RichTextField class Project(models.Model): category = models.ForeignKey(ProjectCategory, on_delete=models.CASCADE) client = models.CharField(max_length=100) title = models.CharField(max_length=100) description = RichTextField(null=True) pdf = models.FileField(null=True, blank=True) def __str__(self): return self.title I am using tailwind css in my frontend and i am displaying the project description {{project.description}} but the styles i have added why i filled the description with ckeditor didn't apply when i displayed the description in my tailwind frontend how to fix that?? -
Why HTML Registration Form Data is not Received in django
I have below configurations of demo\urls.py, user\urls.py, views.py & HTML Form. Still when I press the submit button of HTML Form it says File Not Found. Taking help from ChatGPT which provided two Solutions as mentioned in attached file, even then I am getting Error. What to do demo\urls.py urlpatterns = [ path('admin/', admin.site.urls), path('user', views.register), ] user\urls.py urlpatterns = [ path('register', views.register), ] views.py def register(request): if request.method == 'POST': name = request.POST.get("name") email = request.POST.get("email") password = request.POST.get("password") created_at = request.POST.get("created_at") updated_at = request.POST.get("updated_at") I have following code in HTML Form ``` {% csrf_token %} ``` <label for="name">Name:</label><br> ``` <input name="name" type="text" id="name" name="name"><br> ``` <label for="email">Email:</label><br> ``` <input name="email" type="email" id="email" name="email"><br> ``` <label for="password">Password:</label><br> ``` <input name="password" type="password" id="password" name="password"><br> ``` <script> ``` // Generate current datetime for Hidden fields ``` var current_datetime = new Date().toISOString(); ``` document.getElementById('current_datetime').value = current_datetime; ``` </script> ``` <!-- Hidden fields for created_at and updated_at --> ``` <input type="hidden" name="created_at" value="{{ current_datetime }}"> ``` <input type="hidden" name="updated_at" value="{{ current_datetime }}"> ``` <button type="submit">Register</button> ```</form> ```</body> ```</html> When I press the submit button of HTML Form it says File Not Found. What is the Error & how to fix it I had … -
nginx for development server or connect manage.py runserver from local network
I have development environment (on mac) and access from the android in the same local network. For example my Mac IP is 192.168.0.5,then connecting from android http://192.168.0.5/ Now I have two choices uwsgi and python manage.py runserver When using uwsgi, I need to restart uwsgi for reflecting the code change. When using python manage.py runserver, It doesn't connected from the android. Is there a way to solve this? -
Error with PgBouncer on Heroku with Django and Docker
I'm currently running into database connection issues with my Django & Postgres app hosted on Heroku. Before upgrading my database plan, I wanted to try solving the issue with pgbouncer. According to this article by Heroku, the Procfile would need to be updated from something like web: gunicorn hellodjango.wsgi to web: bin/start-pgbouncer-stunnel gunicorn hellodjango.wsgi after provisioning the pgbouncer buildpack. The thing is, I don't use a Procfile but a heroku.yml. Currently, my yml file has this: run: web: command: - gunicorn --bind 0.0.0.0:$PORT --workers 1 --threads 8 --timeout 0 my_app.asgi:application -k uvicorn.workers.UvicornWorker I tried updating the web command to this: bin/start-pgbouncer-stunnel gunicorn --bind 0.0.0.0:$PORT --workers 1 --threads 8 --timeout 0 my_app.asgi:application -k uvicorn.workers.UvicornWorker but that gives me this error: bin/start-pgbouncer-stunnel: not found I tried this answer as well, but get an pgbouncer: unrecognized service error. Any ideas on how to solve this? -
Django doesnt update the translation
I am trying to add Translation to russian from english I tried clearing the cache, deleting locale folder, changing the translation. it all doesnt work #: core/templates/core/layout.html:59 core/templates/core/layout.html:112 msgid "Home" msgstr "Главная" But it displays "Начало" instead of "Главная". my settings.py: LANGUAGE_CODE = 'en' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = ( ("en", ('English')), ("ru", ('Russian')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale/'), ) -
Django test suite throws error on field that's not loaded: "could not convert string to float"
The following simple test throws the errors ValueError: could not convert string to float: '' The above exception was the direct cause of the following exception: ValueError: Field 'amount' expected a number but got ''. from django.test import TestCase from .models import Customer class TestSetup(TestCase): def setUp(self): self.testCustomer = Customer(firstname='Ron', street_name='Somestreet', street_suffix='Dr', street_number='1', phone='111-111-1111', city='Somecity', zipcode='87000') The field 'amount' does exist, but in a model that isn't loaded for any tests: class Appointment(models.Model): amount = models.FloatField(blank=True, default=0.0) But just in case it's instantiating that model in the process of creating the test database, I migrated "default=0.0" to "default='0.0' " (Single quotes around the value). Same error. I'm initiating the test with python manage.py test from the project directory. -
Django form is invalid and not submitting?
I have four main parts: The BaseJournal form, The JournalTemplate form, a model Journal and amy view which handles it. Here is the Journal Model: class Journal(models.Model): MOOD_CHOICES = [ ('happy', 'happy.png'), ('angry', 'angry.png'), ('neutral', 'neutral.png'), ('sad', 'sad.png'), ] user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) date = models.DateField(auto_now_add=True, editable=False) title = models.CharField(blank=False, max_length=50, default="default title") mood = models.CharField(max_length=20, choices=MOOD_CHOICES, default='neutral') custom_fields = JSONField(default=dict) field_order = JSONField(default=list) @property def attached_files(self): return AttachedFile.objects.filter(journal=self) Here is BaseJournal form: class BaseJournalForm(forms.ModelForm): def __init__(self, user=None, **kwargs): super().__init__(**kwargs) self.fields['mood'].label = '' files = MultipleFileField(required=False) class Meta: model = Journal fields = ['title', 'files', 'mood'] widgets = { "mood": forms.HiddenInput(), "files": MultipleFileInput(), } Here is my Journal Template form: class JournalEntryForm(BaseJournalForm): template = forms.ModelChoiceField( queryset=JournalTemplate.objects.all(), empty_label='No Template', # Set the placeholder text required=False, widget=forms.Select(attrs={'class': 'form-control'}) ) num_questions = forms.IntegerField(label='Number of Questions', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) num_feelings = forms.IntegerField(label='Number of Feelings', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) num_subheadings = forms.IntegerField(label='Number of Subheadings', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) num_events = forms.IntegerField(label='Number of Events', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) template_name = forms.CharField(label='Template Name', required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = Journal fields = BaseJournalForm.Meta.fields + ['template', 'num_questions', 'num_feelings', 'num_subheadings', 'num_events', 'template_name'] Here is my view which handles the form: def create_journal_entry(request): templates = JournalTemplate.objects.all() …