Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does my Django ORM query with naive datetimes return the same results as a PostgreSQL query with time zone-aware datetimes?
I'm using Django to filter reservations based on a date range with naive datetimes. My Django ORM query is: start_d_date_naive = "2024-11-3 00:00" end_d_date_naive = "2024-11-3 23:59" reserve_naive = Reservations.objects.filter( updated_at__range=(start_d_date_naive, end_d_date_naive), status="canceled" ) This translates to the following SQL query: SELECT * FROM "consultant_reservations" WHERE "consultant_reservations"."status" = 'canceled' AND "consultant_reservations"."updated_at" BETWEEN '2024-11-03 00:00:00' AND '2024-11-03 23:59:00' However, the results are the same as if I had run this query directly in PostgreSQL: SELECT * FROM "consultant_reservations" WHERE updated_at BETWEEN '2024-11-03 00:00:00+03:30' AND '2024-11-03 23:59:00+03:30' AND status='canceled'; Why does the Django ORM query with naive datetimes return the same results as the PostgreSQL query with time zone-aware datetimes? -
How to make an IP of a website created using Django to be a link and publicaly available to all?
I am a django learner and upon creating a website i realized that the ip of my website is not accessible on all devices but i want it to be accessed on any device using a link. I haven't tried anything about it because i don't know much about it. I am still in the learning face and am trying to get more knowledge about it. -
How to remove hidden tag on row in django if specific value was choosen in column in another row
I'm using Django to create site and need to show column only if specific value was choosen on column ie if i choose 'medium' in difficult column 'level' column show up: forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Column, Row difficult = (('1', 'low'), ('2', 'medium'), ('3', 'hard'),) level = (('1', 'bad'), ('2', 'decent'), ('3', 'briliant'),) class ContactForm(forms.Form): difficult = forms.ChoiceField(choices=difficult, label='Choose level') level = forms.ChoiceField(choices=level, label='Choose level') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row(Column('difficult', css_class='form-group col-md-4 mb-0'), css_class='form-row'), Row(Column('level', css_class='form-group col-md-4 mb-0'), css_class='form-row', hidden = 'true'), Submit('submit', 'submit', css_class="btn-success") ) views.py from django.shortcuts import render from .forms import ContactForm def index(request): form=ContactForm() if request.GET: temp = request.GET['module'] print(temp) return render(request,'info.html',{'form':form}) info.html {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width" /> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body style="padding:20px;"> <h1 class="mt-2" style="text-align:center;font-weight:bolder;color:steelblue;">Choose</h1> <hr class="mt-0 mb-4"> {% crispy form form.helper %} </body> </html> I know there must be js since it's tool that work on client side, but have no idea how to use that there. https://stackoverflow.com/questions/50947022/django-crispy-forms-hide-fields-conditional-on-other-field-value, but there some params and classes outside of provided code that i … -
Adding a JSON index to MYSQL may result in empty query results
After I added an index to the json field in the database, some of Django's queries stopped working, so I looked into the underlying SQL and found something strange. You can reproduce the problem with the following SQL. CREATE TABLE `products` ( `id` bigint NOT NULL AUTO_INCREMENT, `status` varchar(32) DEFAULT NULL, `info` json DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; ALTER TABLE products ADD INDEX tag_group_idx (( CAST(info->>'$."Group"' as CHAR(32)) COLLATE utf8mb4_bin )) USING BTREE; INSERT INTO products (status, info) VALUES('active', '{"Group": "G0001"}'); MySQL version: 8.0.29. OS: Windows Generated by Django SQL: SELECT * FROM products WHERE status = 'active' AND JSON_EXTRACT(info,'$."Group"') = JSON_EXTRACT('"G0001"', '$'); Result: id|status|info| --+------+----+ Using plain string SQL: SELECT * FROM products WHERE status = 'active' AND JSON_EXTRACT(info,'$."Group"') = 'G0001'; Result: id|status|info | --+------+------------------+ 1|active|{"Group": "G0001"}| Remove redundant query conditions SQL: SELECT * FROM products WHERE JSON_EXTRACT(info,'$."Group"') = JSON_EXTRACT('"G0001"', '$'); Result: id|status|info | --+------+------------------+ 1|active|{"Group": "G0001"}| As shown above, I tried three ways to query, but only the first one had empty results. I guess it was caused by the mismatch of the generated column types. I found that after I deleted the index, the first statement worked fine. ALTER TABLE products DROP … -
Admin login fails with http 403 when testing django server with locust
I'm trying to test my django server with locust, but admin login keeps on failing for 403 error. The instructions of Why am I getting a 403 error when running Locust? do not help. My logust-file: import time from locust import HttpUser, task, between class QuickstartUser(HttpUser): wait_time = between(1, 5) @task def hello_world(self): self.client.get("/tree") self.client.get("/editor/tilastot_teul/14mi/") @task(3) def view_items(self): for item_id in ["13bs","13bu", "13nw", "13nz", "14xe" ]: self.client.get(f"/editor/tilastot_teul/{item_id}") time.sleep(1) def on_start(self): r = self.client.get('') self.client.headers['Referer'] = self.client.base_url self.client.post("/admin/login/", json={"username":"admin", "password":"<my_admin_pw>", 'csrfmiddlewaretoken': r.cookies['csrftoken']}) -
Django Server ignores file changes with --reload in docker
TL;DR How to make django respond to changes I make in my code? I will post the way I run my server in docker. A base dockerfile for production Another one for dev that uses it the base The entrypoint runs the django server with --reload Observations When serving a working server, any change in any file (namely urls.py and views.py) is ignored. Adding syntax errors or any change is not reflected. When serving a server with syntax errors in urls.py for example, and when the server is still running removing the syntax error, the change does work, but any subsequent changes don't work. I checked that the files do change inside the docker container, and still Django ignores them. Here is the relevant code: Dockerfile (the base) # Use Python 3.11.3 as the base image FROM python:3.11.3-slim # Set environment variables ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 ENV DJANGO_SETTINGS_MODULE=config.settings # Set work directory WORKDIR /app # Install system dependencies and debugging tools RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ curl \ netcat-openbsd \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY requirements.txt /app/ RUN pip install --upgrade pip && \ pip install --no-cache-dir -r requirements.txt # … -
Django caching issue when deployed to the DigitalOcean App Platform
I followed the How To Deploy a Django App on App Platform guide from DigitalOcean and successfully created a Django server which I'm using through /admin pages. Through the App Platform, I use GitHub to push changes to production. I'm having an issue with CSS and JS files that don't update after I push changes: I've tried hard refreshing my browser, using a different browser, deleting browser caches, and nothing seems to work, the files don't update. Using the Console, I can see that the files are updated on the server (including under staticfiles), but they don't update in the browser. I read up on the STORAGES setting and the ManifestStaticFilesStorage class, so I tried adding the following setting as a means of cache busting: STORAGES = { 'staticfiles': { 'BACKEND': 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage', }, 'default': { 'BACKEND': 'django.core.files.storage.FileSystemStorage', }, } When I deploy this to production, everything seems to crash except the page I'm currently on (with the JS/CSS I've been testing). I tried deploying with DEBUG=True, but this affects the execution of the static tag by changing whether Django looks for files with their regular or hashed name, so it doesn't reproduce the errors. I'm stumped, how do I even … -
When I enabled ssl using certbot, Django Channels stopped working
I want to activate ssl on my django project, but when I do it using cerbot, Django Channels doesn't work anymore. this is nginx: server { server_name mysite; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www; } location /media/ { root /var/www; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mysite.ir/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mysite.ir/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = mysite.ir) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name mysite.ir; return 404; # managed by Certbot } How can I be on ssl and Django channels at the same time? -
Migrations in wrong order while setting up google sign in using oauth for my django app
I am working on a web app in django and I'm trying to setup Oauth for google sign in, my project is currently pretty much empty. I tried following a tutorial on how to set this up. Upon following the tutorial step by step I encountered multiple errors which i fixed easily (for example missing middleware setup in settings.py), but now I have encountered one I can't seem to fix. I am using PostgreSQL and when running makemigrations i always get this error: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration socialaccount.0002_token_max_lengths is applied before its dependency socialaccount.0001_initial on database 'default'. I tried faking the migrations using a tutorial provided by chatgpt and rerunning them somehow, but nothing seems to work. For the lack of a better tutorial and a lack of programming knowledge I find myself completely lost and unable to move forward. Can anyone help? -
React Query Not Returning Followings from Django API
I'm developing a React application that retrieves a user's followings from my Django backend API. However, I'm facing issues where the followings data is not being returned correctly. API Response When I make a GET request to the endpoint http://127.0.0.1:8000/api/chat/landing/, I receive a JSON response structured like this: { "current_followings": [ { "id": 1, "username": "Amir", "email": "Amir@amir.ir", "full_name": "amirali", "profile_photo": "/media/profile_photo/1000_F_244376003_1smlBNfWYSInMDUFymPuCcms6d1mOqaF_oU9kIP0.jpg", "banner_photo": "/media/banner_photo/header.jpg", "phone": null, "address": "", "bio": "", "profile_views": 1 } ], ... } The response includes an array of current_followings, each containing various fields like id, username, full_name, and profile_photo. Django views.py The view that handles this request is defined as follows: from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from .models import Follower, BasicUserProfile # Assuming these are defined elsewhere class ChatLandingView(APIView): permission_classes = [IsAuthenticated] def get(self, request): try: current_basic_user_profile = get_current_user_profile(request, User, BasicUserProfile) current_followings = Follower.objects.filter(follower=current_basic_user_profile).select_related('following') followings_serializer = BasicUserProfileSerializer([f.following for f in current_followings], many=True) data = { "current_followings": followings_serializer.data, ... } return Response(data, status=status.HTTP_200_OK) except ObjectDoesNotExist: return Response({"error": "Object not found"}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) This view checks for authenticated users and fetches their followings using the Follower model. It serializes the followings data before sending … -
Django Haitian Creole
I want to make a Django Project in Haitian Creole I am trying to create a django project in Haitian Creole. I put LANGUAGE_CODE = 'ht' USE_I18N = True USE_L10N = True USE_TZ = True in the settings.py I had installed gettext and run the follow command in my project folder django-admin makemessages -l ht But everytime I run my server it returns an error. Can somebody help me with this please? -
How to create a POST endpoint in Django with Tastypie
I'm learning Django and I watched and finished a tutorial (Mosh Hamedani and I purchased his videos) that created a database API GET method. I was curios how can I create a POST endpoint to add some new data. In the tutorial, he used tastypie module, if matters. In the tastypie's documents, I see it says how to add authorization, but it does not say anything about the POST. Please help me what's needed to add to and edit the question. This is api/models.py: from django.db import models from tastypie.resources import ModelResource from movies.models import Movie class MovieResource(ModelResource): class Meta: queryset = Movie.objects.all() resource_name = 'movies' excludes = ['date_created'] This is also movies/models: from django.db import models from django.utils import timezone class Genre(models.Model): name = models.CharField(max_length=255, default='Comedy') def __str__(self): return self.name class Movie(models.Model): title = models.CharField(max_length=255, default='Bararreh') release_year = models.IntegerField(default=2008) number_in_stock = models.IntegerField(default=100) daily_rate = models.IntegerField(default=150000) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default='Comedy') date_created = models.DateTimeField(default=timezone.now) These are the fields I have in the admin area to create a new movie. The main urls.py: from django.contrib import admin from django.urls import path, include from api_v1.models import MovieResource from . import views movie_resource = MovieResource() urlpatterns = [ path('', views.home), path('admin/', admin.site.urls), path('movies/', … -
NoReverseMatch at /manager/addVehicle/ Reverse for 'addVehicle' not found. 'addVehicle' is not a valid view function or pattern name
I started my first project in django and am facing the following error. Request Method: GET Request URL: http://127.0.0.1:8000/manager/addVehicle/ Django Version: 5.1.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'addVehicle' not found. 'addVehicle' is not a valid view function or pattern name. Exception Location: C:\Users\\Documents\vehicle-share-system\.venv\Lib\site-packages\django\urls\resolvers.py, line 831, in _reverse_with_prefix Raised during: manager.views.addVehicle this is my views.py folder from django.shortcuts import render # Create your views here. def addVehicle(request): return render(request,'add_vehicle.html') my add_vehicle.html file `{% extends 'base.html'%} {% block content %} <h1>Add vehicle</h1> <br/><br/> <form method="POST" action= "{% url 'addVehicle' %}"> {% csrf_token %} <div class="mb-3"> <label for="Homelocation" class="form-label">Home location</label> <input type="text" class="form-control" id="HomeLocation" name="home_location"> </div> <div class="mb-3"> <label for="Model" class="form-label">Model</label> <input type="text" class="form-control" id="Model" name="model" > </div> <div class="mb-3"> <label for="Make" class="form-label">Make </label> <input type="text" class="form-control" id="make" name="make"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> {% endblock %}` urls.py from . import views from reservations.models import Reservations from reservations.models import vehicles urlpatterns=[ path('addVehicle/', views.addVehicle) ] I am getting the error even though the fn name in views file is the exact same. I have tried copy pasting the exact name and still don't know where i am going wrong. Any help will be greatly appreciated. -
Using Django JSONField Like a NoSQL Database for a Quiz Application
I'm developing a Django-based quiz website and would like to use a JSONField in the Quiz model to store questions in a manner similar to NoSQL databases like MongoDB. My plan is to store questions as JSON data directly in the Quiz model (e.g., questions=models.JSONField()). While this simplifies the structure and avoids joins, I'm concerned about how it will perform regarding querying and filtering capabilities. Given this approach, what are the pros and cons of using JSONField for a large dataset in Django? How can I optimize performance and scalability? Any advice or best practices for managing such a structure would be greatly appreciated. Thank you! -
Django upload file to Dropbox
Is there any way to upload file from Django to Dropbox as code below for your reference: Created one folder in root directory than copy all files from root directory to dropbox. TOKEN = "xxxxxxxx" LOCALFILE = os.path.join(settings.BASE_DIR, 'dcfiles') BACKUPPATH = "/Apps/backup/"# Keep the forward slash before destination filename dbx = dropbox.Dropbox(TOKEN) with open(LOCALFILE, 'rb') as file: response = dbx.files_upload(file.read(), BACKUPPATH) Error: Internal Server Error: /app01/strequest/ Traceback (most recent call last): File "/Users/imac/Desktop/Project/Test2/myenv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/imac/Desktop/Project/Test2/myenv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/imac/Desktop/Project/Test2/myenv/lib/python3.12/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/imac/Desktop/Project/Test2/test2/app01/views.py", line 36, in strequest with open(LOCALFILE, 'rb') as file: ^^^^^^^^^^^^^^^^^^^^^ IsADirectoryError: [Errno 21] Is a directory: '/Users/imac/Desktop/Project/Test2/test2/dcfiles' -
Django admin inline performing too many queries when having additional ForeignKey
I have the following Django models: from django.db import models from django.utils.translation import gettext_lazy as _ class Enterprise(models.Model): nome = models.CharField(max_length=255) class MediaTopic(models.Model): name = models.CharField(max_length=255) class EnterpriseRelatedMedia(models.Model): enterprise = models.ForeignKey( Enterprise, on_delete=models.SET_NULL, null=True, blank=True, related_name="related_medias", related_query_name="related_media", ) topic = models.ForeignKey( MediaTopic, on_delete=models.DO_NOTHING, related_name="enterprise_related_medias", related_query_name="enterprise_related_media", blank=True, null=True, ) And this is my admin.py: from django.contrib import admin from . import models class EnterpriseRelatedMediaInline(admin.StackedInline): model = models.EnterpriseRelatedMedia extra = 1 @admin.register(models.Enterprise) class EnterpriseAdmin(admin.ModelAdmin): inlines = [ EnterpriseRelatedMediaInline, ] admin.site.register(models.MediaTopic) The problem is that since my inline contains not only the enterprise foreignkey but also an extra foreignkey pointing to MediaTopic, everytime my django admin change page loads, it makes a lot of queries to the database. Im aware that this is the famous N+1 problem, and that a select_related or prefetch_related would solve it, the problem is that i do not know where to put it, i tried putting it in the EnterpriseAdmin class as well as the EnterpriseRelatedMediaInline class, and it doesn't seem to work! Every time the admin loads the page, for each instance of the inline (which are 10), it makes a query to pull all the instances of MediaTopic to be available in the foreignkey attribute of … -
Django,pyinstaller,hidden import question
I tried to use pyinstaller to pack my project, And I meet this : `WARNING: Hidden import "usp.templatetags" not found! 155393 WARNING: Hidden import "django.contrib.contenttypes.context_processors" not found! 155395 WARNING: Hidden import "login.context_processors" not found! 155396 WARNING: Hidden import "django_apscheduler.templatetags" not found! 155411 WARNING: Hidden import "django.contrib.auth.templatetags" not found! 155412 WARNING: Hidden import "usp.context_processors" not found! 155412 WARNING: Hidden import "debug_toolbar.context_processors" not found! 155412 WARNING: Hidden import "django.contrib.staticfiles.templatetags" not found! 155689 WARNING: Hidden import "django.contrib.contenttypes.templatetags" not found! 155689 WARNING: Hidden import "login.templatetags" not found! 155695 WARNING: Hidden import "django.contrib.sessions.templatetags" not found! 155696 WARNING: Hidden import "django.contrib.staticfiles.context_processors" not found! 155696 WARNING: Hidden import "django_apscheduler.context_processors" not found! 155803 WARNING: Hidden import "importlib_resources.trees" not found!` I add the missed import to manage.spect, but it change from warning to error: `INFO: Analyzing hidden import 'usp.templatetags' 154547 ERROR: Hidden import 'usp.templatetags' not found 154547 INFO: Analyzing hidden import 'usp.context_processors' 154547 ERROR: Hidden import 'usp.context_processors' not found` then I tried venv, but it still report the same warning: `55393 WARNING: Hidden import "django.contrib.contenttypes.context_processors" not found! 155395 WARNING: Hidden import "login.context_processors" not found! 155396 WARNING: Hidden import "django_apscheduler.templatetags" not found! 155411 WARNING: Hidden import "django.contrib.auth.templatetags" not found! 155412 WARNING: Hidden import "usp.context_processors" not found! 155412 WARNING: Hidden import … -
Django + spatialite migration IntegrityError
When I modify a class/table with PolygonField, the migration stops with the following error: django.db.utils.IntegrityError: The row in table 'geometry_columns_statistics' with primary key 'new__mc_sitio_benfeitoria' has an invalid foreign key: geometry_columns_statistics.f_table_name contains a value 'new__mc_sitio_benfeitoria' that does not have a corresponding value in geometry_columns.f_table_name. My app is MC_SITIO and the class follows: class ImovelBase(ModelGis): """Base para Imóveis""" descricao = CharField(max_length=255, blank=False, null=True, verbose_name='descrição') administrador = ForeignKey(Pessoa, on_delete=SET_NULL, blank=True, null=True) RIP = CharField(max_length=255, blank=True, null=True, help_text='se for imóvel da União') codigo = CharField(max_length=255, blank=True, null=True, verbose_name='código, matricula, anúncio, ou outro documento') endereco = ForeignKey(Endereco, on_delete=SET_NULL, blank=True, null=True, verbose_name = 'endereço') poligono = PolygonField(srid=EPSG_SRID_PADRAO, blank=True, null=True, verbose_name='polígono') # area_total = UnumCharField(valid_unit=m**2, max_length=255, null=True, blank=True, verbose_name='área total', validators = [MinValueValidator(0.0)]) area_total = SympyCharField(max_length=255, null=True, blank=True, verbose_name='área total') VUP = DecimalField(null=True, blank=True, verbose_name='valor unitário padrão (VUP)', max_digits=11, decimal_places=2, validators = [MinValueValidator(0.0)]) indice_fiscal = DecimalField(null=True, blank=True, verbose_name='índice fiscal', max_digits=11, decimal_places=2, validators = [MinValueValidator(0.0)]) em_condominio = BooleanField(default=False, blank=True, verbose_name='em condomínio') observacoes = TextField(null=True, blank=True, verbose_name='observações') class Meta: abstract = True def __str__(self): return "{0}".format(self.descricao) def area(self): if self.poligono: return self.poligono.transform(get_SRID_UTM_WGS84(self.poligono.centroid), clone=True).area*m**2 return "S/N" @property def popupConteudo(self): return '<a href="/terreno-{}.html" target="_blank">{}</a>'.format(self.id, self.descricao) class TerrenoBase(ImovelBase): """Base para Terreno, tombo""" relevo = CharField(choices=RelevoClasse.choices, max_length=255, blank=True, null=True, verbose_name='classe do relevo') forma_regular … -
HOLA TENGO PROBLEMAS CON MI MODELS Y MI BASE DE DATOS MYSQL , NOSE QUE HACER AYUDAA
LA CUESTION QUE MI ME PASARON ESTE CODIGO PARA ARREGLARLO Y NO TENIA EL PRECIO_PROVEEDOR QUE YO LO VINCULE AL PRECIO DE LA APP DE PROVEDORES , EN LA CUAL ESTA LA TABLA PROVEDORESINSUMO Y TIENE LA COLUMNA LLAMADA PRECIO Y LAS VINCULES Y SIN LA BASE DE DATOS TODO ME FUNCIONABA , ya no me funciona nada D: enter image description here y este es la estructura de la base antigua enter image description here y en esta , yo no le agregue la tabla solo queria insertar los datos y agregarle el ,null nose pense que iba a funcionar y no funciono D: enter image description here pero no me funciona y me sale error todo D: espero que se me pueda arreglar y ya no tener problemas con la base de datos D: -
How to handle file upload of a certain type and size? (Looking for Best Practices / Convention)
I have the following column definition in my Django model media = models.FileField() I want to ensure that only video files (preferably in MP4 format) can be uploaded. Additionally, is it possible to set a maximum file size, like 200 MB? Would this approach create extra load on the server, since it would need to validate the MIME type and check that the file size doesn’t exceed the limit? I know client-side checks aren’t secure on their own since they can be bypassed, but does the csrf_token help address this on the backend? -
Django manage.py migration related commands not returning anything
I had an issue with migrations in a project I'm working on, a migration was deleted manually and the sync was ruined, I tried a lot of solutions but nothing worked and at the end I decided to backup the DB and delete all migrations and drop the django_migrations table from the MySQL db, now when I try to run any command like python manage.py makemigrations or python manage.py migrate nothing appears in stdout or stderr, absolutely nothing, not even an error, which has been puzzling me I can provide any information needed but I don't really know where to start here really, Any help would be appreciated a lot. -
How to create a POST endpoint in Django with Tastypie
I'm learning Django and I watched and finished a tutorial (Mosh Hamedani and I purchased his videos) that created a database API GET method. I was curios how can I create a POST endpoint to add some new data. In the tutorial, he used tastypie module, if matters. I know you need data, but I don't know what data is needed to provide you. Please help me what's needed to add to and edit the question. Update 1 This is api/models.py: from django.db import models from tastypie.resources import ModelResource from movies.models import Movie class MovieResource(ModelResource): class Meta: queryset = Movie.objects.all() resource_name = 'movies' excludes = ['date_created'] This is also movies/models: from django.db import models from django.utils import timezone class Genre(models.Model): name = models.CharField(max_length=255, default='Comedy') def __str__(self): return self.name class Movie(models.Model): title = models.CharField(max_length=255, default='Bararreh') release_year = models.IntegerField(default=2008) number_in_stock = models.IntegerField(default=100) daily_rate = models.IntegerField(default=150000) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default='Comedy') date_created = models.DateTimeField(default=timezone.now) These are the fields I have in the admin area to create a new movie. -
Bootstrap nav collapse toggle button not appearing or working
I am just starting out and I am trying to figure this out before completely scrapping the feature. Everything I look up online has no effect and I am lost as to what could possibly be causing this. Here is my code: <body> <nav class="navbar navbar-expand-lg navbar-dark fixed-top"> <a href="{% url 'home' %}" class="navbar-brand"> Inventory App </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a href="{% url 'product_create' %}" class="nav-link"> Add Product </a> </li> <li class="nav-item"> <a href="{% url 'product_list' %}" class="nav-link"> Show Products </a> </li> </ul> </div> </nav> <div class="container"> {% block content %} {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.7.1.slim.min.js" integrity="sha256- kmHvs0B+OpCW5GVHUNjv9rOmY0IvSIRcf7zGUDTDQM8=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.min.js"></script> I have tried using defer, I used the full jquery rather than slim, made sure jquery is before bootstrap, I changed data-toggle to data-bs-toggle also with target, I tried putting everything in a div container and all that did was change the positioning. I have yet to see the nav toggle button even appear on the website yet. -
Error 199 in JazzCash Sandbox Testing During Django Integration
I'm trying to integrate the JazzCash Payment Gateway with my Django project using the HTTP POST Redirect method, but I'm encountering Error 199 from their portal. I've followed the setup in their documentation and am testing using their sandbox environment. Code: Below is a snippet of my integration code, followed by the error response JSON. from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from datetime import datetime, timedelta import hashlib import hmac JAZZCASH_MERCHANT_ID = "" JAZZCASH_PASSWORD = "" JAZZCASH_RETURN_URL = "" JAZZCASH_INTEGRITY_SALT = "" def calculate_jazzcash_secure_hash(request_data, integrity_salt): sorted_data = {k: v for k, v in sorted(request_data.items()) if k != "pp_SecureHash"} final_string = integrity_salt + '&' + '&'.join(str(v) for v in sorted_data.values() if v) secure_hash = hmac.new( integrity_salt.encode(), final_string.encode(), hashlib.sha256 ).hexdigest().upper() return secure_hash def checkout(request): product_name = "Sample Product" product_price = 100 pp_Amount = int(product_price * 100) # in paisa current_datetime = datetime.now() pp_TxnDateTime = current_datetime.strftime('%Y%m%d%H%M%S') pp_TxnExpiryDateTime = (current_datetime + timedelta(hours=1)).strftime('%Y%m%d%H%M%S') pp_TxnRefNo = 'T' + pp_TxnDateTime post_data = { "pp_Version": "1.1", "pp_TxnType": "MWALLET", "pp_Language": "EN", "pp_MerchantID": JAZZCASH_MERCHANT_ID, "pp_SubMerchantID": "", "pp_Password": JAZZCASH_PASSWORD, "pp_BankID": "TBANK", "pp_ProductID": "RETL", "pp_TxnRefNo": pp_TxnRefNo, "pp_Amount": pp_Amount, "pp_TxnCurrency": "PKR", "pp_TxnDateTime": pp_TxnDateTime, "pp_BillReference": "billRef", "pp_Description": "Test transaction", "pp_TxnExpiryDateTime": pp_TxnExpiryDateTime, "pp_ReturnURL": JAZZCASH_RETURN_URL, "ppmpf_1": "1", "ppmpf_2": "2", "ppmpf_3": "3", "ppmpf_4": "4", "ppmpf_5": … -
Cronjob in Docker container uses outdated settings in Django, despite environment variables in Docker Compose
I'm facing a persistent issue with a Django app using Django REST Framework. The application has several models, including one called Project with a created_at timestamp. There’s a management command in manage.py that archives a project if a user hasn't taken action on it within 72 hours of its creation. This command is executed by a cronjob in production, and the entire setup runs within a Docker container. Initial Setup In the past, I separated the back-end environment into two Docker containers: One container ran the Django application and served the API. The other container was dedicated solely to running the cronjob that executed these management commands. Reason for Combining Containers This setup had the same issue with outdated settings, and managing both containers separately added significant overhead, as I needed to clear both containers’ caches and rebuild them frequently. To simplify, I combined the API and cronjob into a single container and used Supervisor to manage the cronjob within this container. Note that Supervisor is functioning correctly, as the cronjob itself runs on schedule (logs confirm this), but it’s only an environment variable issue within the cronjob. The Problem The cronjob uses outdated settings—specifically an old DB_HOST that points …