Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django date format puzzle in multi language app - SHORT_DATE_FORMAT not used with English
We use Django 4.2.11 and I have a bit of a date format puzzle regarding localization in different languages in our project. We are using jquery datepicker and configure it with the current active language. The behaviour of date fields is consistent in languages such as German, Italian and French. Dates are displayed according to the SHORT_DATE_FORMAT of Django, and the returned dates of datepicker show the same formatting. Only with English it's different. The SHORT_DATE_FORMAT is defined as being m/d/Y - but the date get's displayed in the form of YYYY-MM-DD. This leads to the weird behaviour that the user gets displayed a date like for instance 2024-09-08 and when chosing a date from the datepicker the same field shows a value of 09/08/2024. But still the form can be saved without errors and the date is handled correctly. The date field is defined as declarationDate = models.DateField() in the model. We are using django-crispy-forms 2.1 with bootstrap 5. Any ideas what goes wrong here? Where can I look? (I've looked for some time now ...) -
Django autoreload raises: TypeError: unhashable type: 'types.SimpleNamespace'
When I upgrade importlib_meta from version 8.4.0 to 8.5.0 (released just yesterday, Sep 11 2024), I get the following error when I start running the development server with python manage.py runserver: File "/app/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 75, in execute super().execute(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 459, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 112, in handle self.run(**options) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 119, in run autoreload.run_with_reloader(self.inner_run, **options) File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 671, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 660, in start_django reloader.run(django_main_thread) File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 344, in run self.run_loop() File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 350, in run_loop next(ticker) File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 390, in tick for filepath, mtime in self.snapshot_files(): File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 411, in snapshot_files for file in self.watched_files(): File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 304, in watched_files yield from iter_all_python_module_files() File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 120, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) TypeError: unhashable type: 'types.SimpleNamespace' I actually could narrow the problem down to the following commit https://github.com/python/importlib_metadata/commit/56b61b3dd90df2dba2da445a8386029b54fdebf3. When I install importlib_meta just one commit before the problematic commit via pip install git+https://github.com/python/importlib_metadata@d968f6270d55f27a10491344a22e9e0fd77b5583 the error disappears. When I install … -
Django Admin: How to Set a Default Filter Without Conflicting with User-Selected Filters?
I'm working with the Django Admin panel and need to set a default filter for a model's changelist view. When the user opens the changelist page for the first time, I want it to automatically filter by a specific value (e.g., status="A"). However, when a user selects a different filter (e.g., status="B"), the default filter (status="A") should not be applied. What I Have Tried: I've overridden the changelist_view method in my ModelAdmin class to check if any status filter is present in the request. If not, I add the default filter (status=A). Here’s what my code looks like: from django.contrib import admin from django.shortcuts import redirect from django.urls import reverse from .models import Person # Replace with your actual model class PersonAdmin(admin.ModelAdmin): list_display = ('name', 'status') # Adjust fields to match your model list_filter = ('status',) # Adjust filters to match your model def get_queryset(self, request): # Get the original queryset without any default filtering qs = super().get_queryset(request) return qs def changelist_view(self, request, extra_context=None): # Check if any filters related to 'status' are already applied by looking at request.GET if 'status' not in request.GET and 'status__exact' not in request.GET: # Redirect to the same changelist URL with the default filter … -
AADSTS50011: The redirect URI 'http://127.0.0.1:8000/oauth2/callback' specified in the request does not match the redirect URIs
Message: AADSTS50011: The redirect URI 'http://127.0.0.1:8000/oauth2/callback' specified in the request does not match the redirect URIs configured for the application '456b3ef5-cdbe-4d58-aa7b-69f95fffac29'. Make sure the redirect URI sent in the request matches one added to your application in the Azure portal. Navigate to https://aka.ms/redirectUriMismatchError to learn more about how to fix this. I don't understand why I get this error, although I set everything up strictly according to the documentation. User's image enter image description here My current django setting.py file Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_auth_adfs', ] 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', # third party 'django_auth_adfs.middleware.LoginRequiredMiddleware', ] AUTHENTICATION_BACKENDS = ( 'django_auth_adfs.backend.AdfsAuthCodeBackend', 'django_auth_adfs.backend.AdfsAccessTokenBackend', ) # Microsoft Azure AD configuration AZURE_CLIENT_ID = os.environ.get('AZURE_CLIENT_ID') AZURE_TENANT_ID = os.environ.get('AZURE_TENANT_ID') AZURE_CLIENT_SECRET = os.environ.get('AZURE_CLIENT_SECRET') AZURE_REDIRECT_URI = os.environ.get('AZURE_REDIRECT_URI') AZURE_AUTHORITY = os.environ.get('AZURE_AUTHORITY') AZURE_SCOPES = os.environ.get('AZURE_SCOPES').split() AUTH_ADFS = { 'AUDIENCE': [f'api://{AZURE_CLIENT_ID}', AZURE_CLIENT_ID], 'CLIENT_ID': AZURE_CLIENT_ID, 'CLIENT_SECRET': AZURE_CLIENT_SECRET, 'CLAIM_MAPPING': {'first_name': 'given_name', 'last_name': 'family_name', 'email': 'upn'}, 'GROUPS_CLAIM': 'roles', 'MIRROR_GROUPS': True, 'USERNAME_CLAIM': 'upn', 'TENANT_ID': AZURE_TENANT_ID, 'RELYING_PARTY_ID': AZURE_CLIENT_ID, 'LOGIN_EXEMPT_URLS': [ '^api', ], } LOGIN_URL = "django_auth_adfs:login" LOGIN_REDIRECT_URL = "dashboard" LOGOUT_REDIRECT_URL = '/' Could you please tell me what could be the reason for this error? I have been trying to figure it out … -
Config pytest-django and pre-commit in Django project
I have a Django project with the following construction: . ├── db.sqlite3 ├── manage.py ├── switch │ ├── __init__.py │ ├── settings.py ├── store │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── tests | | ├── __init__.py | | ├── tests.py │ ├── apps.py │ ├── migrations │ ├── urls.py │ └── views.py ├── .pre-commit-config.yaml └── pytest.ini My author is test.ini: [pytest] DJANGO_SETTINGS_MODULE = store.settings python_files = tests.py tests_*.py *_tests.py The pre-commit file.yaml: exclude: "^docs/|/migrations/" default_stages: [commit] repos: - repo: local hooks: - id: pytest-check name: pytest-check entry: pytest language: system pass_filenames: false always_run: true When running tests locally pytest, everything works without errors. When running pre-commit locally pre-commit run --color=always --all-files, everything works without errors. When I try to commit, I get an error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. If add a forced installation of an environment variable in the test file with the path to the settings file and call django.config(), then the problem is solved. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "store.settings") django.setup() But I think this is the wrong way and there is another more optimal solution. Please … -
Using Django to visualise scraped data
Hi I'm new to django and thought it would be interesting to use it to visualise a data I scraped from certain websites, sth like this video) (https://www.youtube.com/watch?v=TcnWEQMT3_A&list=PL-2EBeDYMIbTt63EH9ubqbvQqJkBP3vzy&index=1) However I'm finding it difficult to choose a right way of how to load a data. Right now, I have a python program that scrapes stats of players from big 5 leagues, from fbref.com (football related website) and store them to a csv file. I think I have two options now? Creating a Model in django and read a csv file to store each row as a separate model. So basically, I'm storing a data at Django db, similar to Not creating a separate Django model and using pandas dataframe. (Not storing my data to Django DB). I feel like first approach is less efficient because I'm thinking of adding further data analysis later on, so I would end up using pandas dataframe mainly anyways. However I'm lowkey worried about if anything would go terribly wrong if I don't use the Django database. Which approach is better and are there better ways to do this?? Thank you! I initially tried second approach but I got worried of data managements, -
django.contrib.staticfiles.templatetags and sharedpy-0.0.106
I am trying to move a deployment from one server to another to meet some organisational requirements. The components on the source server include: Django 2.2.7 Python 3.7 Components on target (these versions are not fixed but must be current) Django 4.2.13 Python 3.10.14 When running manage.py makemigrations I receive the following error: File "/home/dtracker/dtracker/prime/models.py", line 2, in from sharedpy.django.utils import cache_get_or_set File "/home/dtracker/env/lib/python3.10/site-packages/sharedpy-0.0.106-py3.10.egg/sharedpy/django/utils.py", line 10, in ModuleNotFoundError: No module named 'django.contrib.staticfiles.templatetags' Reference to django.contrib.staticfiles.templatetags in settings.py has replaced with django.templatetags.static. As per the last line of error, django.contrib.staticfiles.templatetags cannot be found as it is not available in Django 3+. My question is, does sharedpy-0.0.106 require django.contrib.staticfiles.templatetags and if so, how can I remove the need to use sharedpy? Tried to remove sharedpy however when running command received error stating it was required. -
Not able to get email when user submits the form
I have created contact form with react and connected it with mysql database hosted using RDS. i used django for building the database. before some days i was able to get email when i am submitting the form and the data was also been stored in the database but now when i am submitting the form i am not getting an email notification of submission but i can see the data in my database. i also tried to send test email from the console and it worked. when i changed the API from urls.py and then i submitted the form, i got the mail but when i did the submission again i did not get any mail. this is my setting.py code DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('DB_NAME', default='myportfolio'), 'USER': config('DB_USER', default='root'), 'PASSWORD': config('DB_PASSWORD', default=''), 'HOST': config('DB_HOST', default=''), 'PORT': config('DB_PORT', default='3306'), } } # Email backend configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') views.py from django.core.mail import send_mail from django.conf import settings from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from .models import Form from .serializers import FormSerializer import json @csrf_exempt … -
Encountering a 302 redirect issue when submitting a form in React/Django app as API call is being made without proper authentication
In my Django/React app I want a user to be signed in to be able to successfuly submit a request to an API. I successfully login with google and I believe I am passing all of the correct data to the backend api for it to be called. I have configured CORS, ensured my CSRF tokens match, am using @login_required on my Django view, use "credentials: 'include'" in the api call, and have exhausted both ChatGPT and my own internet searching to solve the problem. From my Conversation.jsx file I want to call /api/ask_new_york from app/views.py. Even when logged in I get a 302 response. Here is all of what I think is the relevant code and the output: settings.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'allauth.account.middleware.AccountMiddleware', ] # CORS settings CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True # CSRF settings CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', 'http://localhost:8000', 'http://127.0.0.1:8000', 'http://localhost' ] # Disable CSRF cookies only if needed CSRF_COOKIE_SECURE = False LOGIN_REDIRECT_URL = '/' LOGIN_URL = '/login/' LOGOUT_REDIRECT_URL = '/' app/views.py: @csrf_exempt def get_csrf_token(request): csrf_token = get_token(request) return JsonResponse({'csrf_token': csrf_token}) @login_required def ask_new_york(request): if request.method == 'POST': try: data = json.loads(request.body.decode('utf-8')) input_value = data.get('input_value' users/views.py: This handles the … -
i am using cookiecutter-django with docker and it keeps reloading in the local env
I am starting to use cookiecutter-django 2024.07.26 with docker and after a few updates it keeps reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/contrib/sites/models.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/contrib/sites/shortcuts.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/allauth/account/views.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/generic/edit.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/allauth/account/mixins.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/generic/base.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/decorators/cache.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/decorators/debug.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/allauth/decorators.py', reloading aqua_loui_local_django | * Restarting with watchdog (inotify) aqua_loui_local_django | Performing system checks... aqua_loui_local_django | aqua_loui_local_django | System check identified no issues (0 silenced). aqua_loui_local_django | aqua_loui_local_django | Django version 5.0.7, using settings 'config.settings.local' aqua_loui_local_django | Development server is running at http://0.0.0.0:8000/ aqua_loui_local_django | Using the Werkzeug debugger (https://werkzeug.palletsprojects.com/) aqua_loui_local_django | Quit the server with CONTROL-C. aqua_loui_local_django | * Debugger is active! -
On the fly video conversion in django during upload
I an making a backend in django rest where user will be uploading videos in multiple formats such as mp4, avi, etc. I want to convert these videos to a single h264 format while storing them but rather than first taking the full video and then converting it i want to convert it while it is being uploaded how can i do that. The video file is comming through multipart/form-data I have been stucck and not able to find a plausible approach but i know that i have to use FFMpeg in some manner. -
how to send a JSON file from a windows service to a Django web site?
Me and my colleagues are trying to create a windows service which sends battery information and other information in the form of JSON files from a client PC to a Django web site where it will be recorded. What is the best approach for this? and also how do I receive it on the Django web site's side? I am completely new to windows services. Currently we have created a windows service which gives us the JSON file on the client computer itself, but we need to make it so that the file is sent to the Django web server. -
Should I use Django's `FloatField()` or `DecimalField(`) for audio length?
Using duration = float(ffmpeg.probe(audio_path)["format"]["duration"]), I collect an audio/video's length and want to store it using my models. Should I use models.DecimalField() or models.FloatField()? I use it to calculate and store a credit/cost in my model using credit = models.DecimalField(max_digits=20, decimal_places=4) -
Django filter across multiple model relationships
Let a simplified version of my models be as follows: class Order (models.Model): customer = models.ForeignKey("Customer", on_delete=models.RESTRICT) request_date = models.DateField() price = models.DecimalField(max_digits=10, decimal_places=2) @property def agent_name(self): assignment = Assignment.objects.get(assig_year = self.request_date.year, customer = self.customer) if assignment is not None: return assignment.sales_agent.name + ' ' + assignment.sales_agent.surname else: return 'ERROR' class Company (models.Model): pass class Customer (Company): pass class Assignment (models.Model): assig_year = models.PositiveSmallIntegerField() customer = models.ForeignKey("Customer", on_delete=models.CASCADE) sales_agent = models.ForeignKey("Agent", on_delete=models.CASCADE) class Employee (models.Model): name = models.CharField(max_length=32) surname = models.CharField(max_length=32) class Agent (Employee): pass In one of my views, I am displaying all orders by listing their corresponding sales agent, customer, date and price, as follows: def GetOrders(request): orders = Order.objects.order_by('-request_date') template = loader.get_template('orders.html') context = { 'orders' : orders, } return HttpResponse(template.render(context,request)) where orders.html looks something like this: <!DOCTYPE html> <html> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <main> <table> <thead> <th>Agent</th> <th>Customer</th> <th>Date</th> <th>Price</th> </thead> <tbody> {% for x in orders %} <td>{{ x.agent_name }}</td> <td>{{ x.customer.name }}</td> <td>{{ x.request_date }}</td> <td>{{ x.price }}</td> </tr> {% endfor %} </tbody> </table> </main> </body> </html> Now I would like to add some filtering capability to the html in order to select only those sales agent I'm interested in, but this … -
Docker Django mysql
Here's folder structure: 📄 Dockerfile 📄 .env 📄 requirements.txt 📁 pr/ 📁 static/ 📄 app.js 📄 manage.py 📁 pr/ 📄 wsgi.py 📄 __init__.py 📄 urls.py 📄 settings.py 📄 asgi.py 📄 docker-compose.yml Here the important file's content Dockerfile --------- # Use an official Python runtime as a parent image # syntax=docker/dockerfile:1 FROM python:3.11 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Install system dependencies RUN apt-get update \ && apt-get install -y --no-install-recommends \ gcc \ libmariadb-dev \ && rm -rf /var/lib/apt/lists/* # Upgrade pip RUN pip install --upgrade pip # Set the working directory WORKDIR /app # Install Python dependencies COPY requirements.txt /app/ RUN pip install -r requirements.txt # Copy the project code into the container COPY ./pr /app/ # Expose the Django development server port EXPOSE 8000 requirements.txt --------- psycopg2>=2.8 asgiref==3.8.1 Django==5.1.1 djangorestframework==3.15.2 mysqlclient==2.2.4 python-dotenv==1.0.1 sqlparse==0.5.1 pytz==2024.2 settings.py: .... # Database # https://docs.djangoproject.com/en/5.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE'), 'USER': os.environ.get('MYSQL_USER'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD'), 'HOST': 'dj1_mariadb', 'PORT': 3306, } } .... docker-compose.yml: services: dj1_mariadb: image: mariadb:latest container_name: dj1_mariadb restart: always environment: MYSQL_ROOT_PASSWORD: myrpass MYSQL_DATABASE: dj1 MYSQL_USER: ab_usr MYSQL_PASSWORD: mypass volumes: - ./data/mariadb:/var/lib/mysql # apt-get update && apt-get install -y mariadb-client networks: - app-network dj1_pma: … -
Django serializer returning empty array
I have minimal experience with Python, and no experience with Django, but I have been tasked with fixing a bug in a Django app. I have the following models ` class SurveyResponse(models.Model): survey = models.ForeignKey(to=Survey, on_delete=models.CASCADE, related_name="responses") # Don't want to clear out surveys if the mission is cleared. Still may be valuable mission_run = models.ForeignKey(to=MissionRun, on_delete=models.SET_NULL, blank=True, null=True, related_name="survey_responses") grade = models.CharField(max_length=15, blank=True, null=True) # grade level gender = models.CharField(max_length=15, blank=True, null=True) # gender selection race = models.CharField(max_length=50, blank=True, null=True) # race selection exported_survey_file = models.ForeignKey(to="SurveyVendorFile", null=True, blank=True, on_delete=models.SET_NULL, related_name="survey_responses") exported_evaluator_file = models.ForeignKey(to="EvaluatorFile", null=True, blank=True, on_delete=models.SET_NULL, related_name="survey_responses") class SurveyResponseAnswer(models.Model): survey_response = models.ForeignKey(to=SurveyResponse, on_delete=models.CASCADE, related_name="answers") survey_question = models.ForeignKey(to=SurveyQuestion, on_delete=models.CASCADE, related_name="answers") answers = ArrayField(models.CharField(max_length=100), null=True, blank=True) answer = models.CharField(max_length=100, null=True, blank=True) @property def reverse_coding(self): return self.survey_question.reverse_coding` and then this code to serialize a response to a POST request ` class SurveyResponseViewSet(mixins.CreateModelMixin, GenericViewSet): queryset = app_models.SurveyResponse.objects.all() permission_classes = [] serializer_class = app_serializers.SurveyResponseCreateSerializer class SurveyResponseAnswerCreateSerializer(serializers.ModelSerializer): survey_question_id = serializers.IntegerField() answers = serializers.SerializerMethodField(required=False) def get_answers(self, obj): return obj.answers if obj.answers else [] class Meta: model = app_models.SurveyResponseAnswer exclude = ["survey_response", "survey_question"] class SurveyResponseCreateSerializer(serializers.ModelSerializer): survey_id = serializers.IntegerField() answers = SurveyResponseAnswerCreateSerializer(many=True) mission_run_id = serializers.IntegerField() def create(self, validated_data): answers = validated_data.pop("answers", []) survey_response = app_models.SurveyResponse.objects.create(**validated_data) for answer in … -
Django: using sqlsequencereset programmatically inside a custom command
I am trying to create a custom command on Django, which will use the sqlsequencereset command for a list of app labels inside a loop, the idea is to run this command to generate and run the sequence setval query for each table of the app. My implementation: for app_label in app_labels: output = call_command("sqlsequencereset", app_label) with connection.cursor() as cursor: cursor.execute(output) I read inside the Django Documentation that raw queries inside cursor.execute do not support transactions, so i customized the SQL string to not include BEGIN and COMMIT keywords, but it still throws the following syntax error: File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 122, in execute return super().execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 79, in execute return self._execute_with_wrappers( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 92, in _execute_with_wrappers return executor(sql, params, many, context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 100, in _execute with self.db.wrap_database_errors: File "/home/python/.local/lib/python3.12/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 103, in _execute return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.ProgrammingError: syntax error at or near " LINE 1: BEGIN; -
Overriding queryset in Django Admin without effects
Sorry if I'm repetitive on a widely discussed topic, but I can't figure out where the error is, since debug returns the correct result, but the page in the browser does not. In short, I'm implementing an app that is multi-user and multi-tenant, with the use of the django-organizations module. Each model that identifies particular resources has a 'gruppo' field, Foreign Key to the specific tenant. Furthermore, the session contains the tenant('gruppo_utente') in use, in order to allow the change of one tenant to another simply by changing the data stored in the session. request.session['gruppo_utente']=int(tenant) # =gruppo_id This is the model: //model.py from multigroup.models import Gruppo, GruppoUser from mptt.models import MPTTModel, TreeForeignKey class ContoCOGE (MPTTModel): gruppo = models.ForeignKey(Gruppo, on_delete=models.CASCADE, related_name='contoCOCGE_gruppo') nome = models.CharField(max_length=2,default='') descrizione = models.CharField("Descrizione",max_length=50,default='') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['nome'] class Meta: verbose_name = "Conto" verbose_name_plural = "Conti" def antenati(self): tmp='' if self.is_root_node(): return format_html(f'<b> {{}} - {{}} </b>', mark_safe(self.nome), mark_safe(self.descrizione)) for i in self.get_ancestors(): tmp += i.nome + '.' return tmp+self.nome+' - '+self.descrizione antenati.allow_tags = True def __str__(self): tmp='' if self.is_root_node(): return format_html(f'<b> {{}} - {{}} </b>', mark_safe(self.nome), mark_safe(self.descrizione)) for i in self.get_ancestors(): tmp += i.nome + '.' return tmp + … -
(1452, 'Cannot add or update a child row: a foreign key constraint fails ). with data matching in the target table
I I have a django service that interacts with a mysql database that I first developed locally, here no problem however once the database is recreated online on an o2switch server, the foreign key constraints no longer work and I can't understand why, I tried to insert a row in the table 'nomchamp' with data existing in the parent table con but this still returns me the error (1452, 'Cannot add or update a child row: a foreign key constraint fails (goqo5870_lddb.nomchamp, CONSTRAINT nomchamp_ibfk_1 FOREIGN KEY (IDCon) REFERENCES con (ID))'). error raise by django I tried this command in phpmyadmin : INSERT INTO nomchamp(IDCon, NOM) VALUES (1, 'PROSPECT'); and this raise the same error I dont understand. ID in table con So the error is caused by the database not by django but I dont know why this error occurred, I create the database with a sql dump file of my local database. -
Django AJAX: Passing form CSFR verification without proper token attachment. Why?
I have a small Django 5.1.1 project, in which I use AJAX request to submit form data data. I'm using {% csrf_token %} and have the setup for attaching the form csrfToken to the xhr header. PROBLEM: The CSFR verification is SUCCESSFUL even when xhr.setRequestHeader('X-CSRFToken', csrfToken); is commented out. AJAX request goes through and gets the response. It only fails when the {% csrf_token %} is missing. From what I understand it should fail without the form csfrToken attached to the header. What am I missing here? Simplified code: <form id="form1" method="post" class="..."> {% csrf_token %} <div> <label for="A" class=""></label> <input type="text" name="symbol" id="A" class="..."> </div> <div> <button type="submit" id="submit-button"></button> </div> </form> document.getElementById('form1').addEventListener('submit', function(event) { event.preventDefault(); const xhr = new XMLHttpRequest(); const formData = new FormData(this); const csrfToken = this.querySelector('[name=csrfmiddlewaretoken]').value; xhr.open('POST', '/form-submit', true); // xhr.setRequestHeader('X-CSRFToken', csrfToken); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(formData); }); def index_view(request): return HttpResponse("", status=200) 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", ] -
Djnago websocket program which accept the send-all message and send-each message
I have React UI like this, simply it accepts the message from server. import React,{useState,useRef,useEffect,createRef,forwardRef,useImperativeHandle,useContext,RefObject} from 'react'; const WebSocketPage = forwardRef((props,ref) =>{ const webSocketRef = useRef(null); const [messages,setMessages] = useState([]); useEffect(() =>{ if ( webSocketRef.current && webSocketRef.current.readyState === WebSocket.OPEN ) { return; } webSocketRef.current = new WebSocket(`ws://127.0.0.1:8000/ws/chat/`); console.log("websocket",webSocketRef.current); console.log("websocket state",webSocketRef.current.readyState); const onOpen = () => { console.log("WebSocket Connected"); }; const onMessage = (e) => { const data = JSON.parse(e.data); setMessages((messages) => [...messages, data.message]); }; const onError = (e) => { console.log("WebSocket Error: ", e); }; const onClose = () => { console.log("WebSocket Disconnected"); }; webSocketRef.current.addEventListener("open", onOpen); webSocketRef.current.addEventListener("message", onMessage); webSocketRef.current.addEventListener("error", onError); webSocketRef.current.addEventListener("close", onClose); return () => { if (webSocketRef.current?.readyState === 1) { webSocketRef.current.removeEventListener("open", onOpen); webSocketRef.current.removeEventListener("message", onMessage); webSocketRef.current.removeEventListener("error", onError); webSocketRef.current.removeEventListener("close", onClose); webSocketRef.current?.close(); } }; },[]); return( <div>test test</div>) }); export default WebSocketPage then, in the python/django server , I can send the data to UI. def handle(self, *args, **options): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'chat', { "type": "chat_message", "message": {"content":"mytestdada","id":20} } ) It works, and It sends the messages to the every browsers. Now, I am a bit confused. When there is people (A,B,C,D,E) How can I proper use of channel_layer? channel_layer.group_send should be use for sending all people?(A,B,C,D,E) channel_layer.send should be used … -
Why do I keep getting an ModuleNotFound error everytime I runserver in the cmd terminal
I was following a django tutorial for a project but I keep getting an error everytime I runserver and this error began showing up when I added the app to the settings.py of the django project. What do I do to bypass this I tried restarting my work in new terminals and I started over in general but I still ran into the same error -
How to handle Parallel GitHub Actions and Migrations in Django + React Projects
I'm working on a Django + React project, and we use GitHub Actions for CI/CD. The typical workflow when a pull request is raised involves running Selenium tests, which require a large dataset in the database to execute effectively. Once the tests pass, I merge the branch, triggering an AWS CodePipeline that goes through source, manual approval, and deployment stages. The problem I'm facing is related to database migrations when multiple developers raise pull requests simultaneously. If I run the workflows in parallel, I end up with migration conflicts that cause issues down the road. However, if I run the workflows sequentially, the deployment process gets delayed, especially when there are several pull requests in the queue. Current Setup GitHub Actions- Runs on pull requests, runs Selenium tests, and applies migrations to a testing database. AWS CodePipeline- After tests pass and PR is merged, it handles manual approval and deployment to production. Database- I'm using a large dataset, and migrations are applied to both a testing database and the live database in different stages. Concerns Migration Conflicts- When workflows run in parallel and developers raise pull requests with migration changes, I face conflicts when these workflows try to run migrations … -
Font awesome preload warning when Django app deployed to Heroku, but not on dev server
It's my first day using heroku to deploy my Django app. When I deploy my Django app on Heroku, the chrome inspector gives this warning: The resource https://ka-f.fontawesome.com/releases/v6.6.0/webfonts/free-fa-solid-900.woff2 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate as value and it is preloaded intentionally. When I click the warning link it shows the first line of my index page html, which is blank. I don't get this warning when running in my development server and setting the Django project Debug mode has no effect. I have deleted every mention of fontawesome in my project including removing the fontawesome reference from the head of my base.html and removing it from my installed apps etc., but I still receive this warning. I used search to double check there were no font awesome references. Have tried to look up solutions for several hours today and am stumped. My base.html page looks like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Dotstory</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="shortcut icon" type="image/x-icon" href="{% static 'storymode/images/favicon.png' %}"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> and my index looks like … -
Django: GET /getMessages// HTTP/1.1" 404 2987
I am following a Django tutorial video on how to create a simple chat room. When I want to create a new room, a pop-up alert says "An error occurred". Couldn't figure out what went wrong. Errors: home.html room.html urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('<str:room>/', views.room, name='room'), path('checkview', views.checkview, name='checkview') > ] views.py from django.shortcuts import render, redirect from chat.models import Room, Message # Create your views here. def home(request): return render(request, 'home.html') def room(request, room): return render(request, 'room.html') def checkview(request): room = request.POST['room_name'] username = request.POST['username'] if Room.objects.filter(name=room).exists(): return redirect('/'+room+'/?username='+username) else: new_room = Room.objects.create(name=room) new_room.save() return redirect('/'+room+'/?username='+username) models.py from django.db import models from datetime import datetime # Create your models here. class Room(models.Model): name = models.CharField(max_length=1000) class Message(models.Model): value = models.CharField(max_length=1000000) date = models.DateTimeField(default=datetime.now, blank=True) user = models.CharField(max_length=1000000) room = models.CharField(max_length=1000000)