Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Notification system for blog app in analogy with facebook etc
I tends to extend my blog with notification as used by Facebook and other social media platforms. Can anyone suggest a notification system for my blog application? I've developed a blog with like, comment, and reply features using Django, and now I want to add a notification system. Is there a lightweight notification system available that I can easily implement in my blog app? -
TooManyFieldsSent Raised when saving admin.ModelAdmin with TabularInline even with unchanged fields
Whenever I try to save without editing any fields in Author in the admin page, I get a TooManyFields error. I am aware that I can simply set this in settings.py. DATA_UPLOAD_MAX_NUMBER_FIELDS = None # or DATA_UPLOAD_MAX_NUMBER_FIELDS = some_large_number However, not setting a limit would open up an attack vector and would pose security risks. I'd like to avoid this approach as much as possible. My admin model AuthorAdmin has a TabularInline called PostInline. admin.py class AuthorAdmin(admin.ModelAdmin) inlines = [PostInline] class InstanceInline(admin.TabularInline) model = Post Models class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class Post(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return str(self.title) The reason this error is being raised is that an Author can have multiple posts. Whenever this Author is saved (without any field change), it sends out a POST request which includes the post_id and the post__series_id based on the number of posts under that same author. This can easily exceed the default limit set by Django which is set to 1000. Is there a way to not include unchanged fields in the POST request upon save? Or a better approach to solve this issue without having to resort to updating DATA_UPLOAD_MAX_NUMBER_FIELDS? -
How to keep datas remain after switch to deocker for deployment(Wagtail into an existing Django project)
let me clear what is going on....... am working on wagtail project which is comes from ff this steps: -How to add Wagtail into an existing Django project(https://docs.wagtail.org/en/stable/advanced_topics/add_to_django_project.html) and am try to switch project to docker for deployment and do not forget am "import sql dump into postgres", and am aim to run on uwsgi and everything is perfect no error;but there are problem after everything i can't see anything on pages and when i try to access admin there is no any existed pages(which means i should create pages from scratch) here are some of cmds i used: -docker-compose -f docker-compose-deploy.yml build -docker-compose -f docker-compose-deploy.yml up -docker-compose -f docker-compose-deploy.yml run --rm app sh -c "python manage.py createsuperuser" if it needed here is the Dockerfile: FROM python:3.9-slim-bookworm LABEL maintainer="londonappdeveloper.com" ENV PYTHONUNBUFFERED=1 # Install dependencies RUN apt-get update && apt-get install --no-install-recommends -y \ build-essential \ libpq-dev \ gcc \ exiftool \ imagemagick \ libmagickwand-dev \ libmagic1 \ redis-tools \ && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ && rm -rf /var/lib/apt/lists/* # Set up virtual environment RUN python -m venv /py && \ /py/bin/pip install --upgrade pip # Copy application files COPY ./requirements.txt /requirements.txt COPY . /app COPY ./scripts /scripts … -
Is it safe to use url link to sort table rows using Django for backend?
I was asking my supervisor for an opinion to sort rows of a table. When a table head column is clicked, I basically change the url to: /?order_by=price then check if url == /?order_by=price: Inventory.objects.order_by('price') He told me I could do this in frontend with css,because if someone enters a bad input or injects smth, they can access my whole table. Is the backend logic with Django good for this problem, or should I do it as he said? -
Can't get Django view to never cache when accessing via browser
I have a Django app hosted on a Linux server served by NGINX. A view called DashboardView displays data from a Postgresql database. This database gets routinely updated by processes independent of the Django app. In order for the latest data to always be displayed I have set the view to never cache. However this doesn't seem to be applied when viewing in the browser. The only way I can force through the view to show the updated data is via a GUNICORN restart on the server. When I look at the the Network details in Google Chrome devtools everything looks set correctly. See below the cache control details shown. max-age=0, no-cache, no-store, must-revalidate, private Please see Django code below setting never cache on the DashboardView. from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache class NeverCacheMixin(object): @method_decorator(never_cache) def dispatch(self, *args, **kwargs): return super(NeverCacheMixin, self).dispatch(*args, **kwargs) class DashboardView(NeverCacheMixin, TemplateView): ...................code for view............. I am at a loss as what to look at next. The session IDs don't seem to change after a GUNICORN restart so I don't think its related to this. Where could this be failing? -
SSL configuration with Nginx with Django
I am trying to configure the SSL to the environment. The combination of technical stack nginx, Angular and Django. I downloaded the cert and placed into the server for the nginx and added the below configuration in the Django - settings.py for the SSL in the backend. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') Added the below configuration in the nginx server block. server { listen 8000 ssl; ssl_certificate /etc/ssl/servername.crt; ssl_certificate_key /etc/ssl/servername.key; ssl_password_file /etc/ssl/global.pass; server_name localhost; underscores_in_headers on; client_max_body_size 2500M; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_buffering off; proxy_set_header Connection "Upgrade"; proxy_connect_timeout 3600s; proxy_read_timeout 3600s; proxy_send_timeout 3600s; proxy_pass https://backend; proxy_ssl_protocols TLSv1 TLSv1.1 TLSv1.2; proxy_ssl_password_file /etc/ssl/global.pass; } } Tried the few stackoverflow solutions, but nothing works. I am getting the below error messge Access to XMLHttpRequest at ' https://servername/login/' from origin ' https://servername:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Just want to get more clarity on the nginx configuration. Did I miss anything? I searched few answers but unable to get the solution. -
Django POST requst post data not recived in VIEW
After the post request From the Hrml Form view, I can't get the data from key and values, not able to the data form given user , received a csrt_token as a key, but I am not able to receive a key value from views , I want o receive individual items in the value as value, and kes as meta key . **This is an HTML file ** <form action="{% url 'add_cart' single_product.id%}" method = "POST"> {% csrf_token%} <article class="content-body"> <h2 class="title">{{single_product.product_name}}</h2> <div class="mb-3"> <var class="price h4">{{single_product.price}} BDT</var> </div> <p>{{single_product.description}}</p> <hr> <div class="row"> <div class="item-option-select"> <h6>Choose Color</h6> <select name="color" class="form-control" required> <option value="" disabled selected>Select</option> {% for i in single_product.variation_set.colors %} <option value="{{ i.variation_value | lower }}">{{ i.variation_value | capfirst }}</option> {% endfor %} </select> </div> </div> <!-- row.// --> <div class="row"> <div class="item-option-select"> <h6>Select Size</h6> <select name="size" class="form-control"> <option value="" disabled selected>Select</option> {% for i in single_product.variation_set.sizes %} <option value="{{ i.variation_value | lower }}">{{ i.variation_value | capfirst }}</option> {% endfor %} </select> </select> </div> </div> <!-- row.// --> <hr> {% if single_product.stock <= 0 %} <h5>Out of stock </h5> {% else %} {% if in_cart%} <a class="btn btn-success"> <span class="text"> Added to Cart</span> <i class="fas fa-check"></i> </a> <a … -
{% static 'file' %} should fail if file not present
I am currently working on a Django application. When I use {% static 'file' %} within my template everything works great locally and on production as well, when file exists. When file does not exist, the error only occurs in production; collectstatic also seems to ignore that the file does not exist. I get a 500 when trying to get the start page. I would like this error to also occur in development mode. Did I misconfigure Django and it would normally do that? Or can it at least be configured that way? Just giving me the error page in development mode with the incorrect file path would be perfect. -
Datadog Integration to Django application running on azure
I have a django web app running on azure web app, I installed the datadog agent in my local and ran the application after setting up datadog configuration, I was able to get traces and metrics. Data dog traces or meteics doesn't work when I push these changes to prod. I followed this https://docs.datadoghq.com/integrations/guide/azure-manual-setup/?tab=azurecli#integrating-through-the-azure-cli from datadog to connect to azure. the azure resources are visible in the azure serverless view of datadog, but my application which has datadog settings configured doesn't work I tried following the official azure datadog integration through azure cli manual -
Django Deploy on Render.com: Page isn't redirecting properly browser error
I'm trying to deploy a Django application using Docker to https://render.com. The Docker container runs successfully, but when I try to open the website in a browser (Firefox Developers Edition), I get this error: Error in Firefox I've also tried opening the application in various other browsers, but I'm also getting similar errors. During the development on my machine I don't receive any errors. Dockerfile: FROM python:3.12 # Set environment variables ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ DJANGO_SETTINGS_MODULE=config.settings.prod # Set the working directory WORKDIR /app RUN python --version # Install Node.js and npm RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \ apt-get install -y nodejs # Install dependencies for MariaDB RUN apt-get update && \ apt-get install -y python3-dev default-libmysqlclient-dev build-essential pkg-config # Install Poetry RUN pip install poetry # Copy pyproject.toml and poetry.lock COPY pyproject.toml poetry.lock /app/ # Configure Poetry to not use virtualenvs RUN poetry config virtualenvs.create false # Install Python dependencies RUN poetry install --no-dev --no-root # Copy the entire project COPY . /app/ # Install Tailwind CSS (requires Node.js and npm) RUN python manage.py tailwind install --no-input; # Build Tailwind CSS RUN python manage.py tailwind build --no-input; # Collect static files RUN python manage.py collectstatic --no-input; … -
How to setup Nginx as a reverse proxy for Django in Docker?
I'm trying to setup nginx as a reverse proxy for Django in docker so I can password prompt users that don't have a specific IP. However I can't get it to work. I have a Django app with a postgreSQL database all set up and working in Docker. I also have a Nginx container I just can't see to get the two connected? I haven't used Nginx before. The closest I have got is seeing the welcome to Nginx page at localhost:1337 and seeing the Django admin at localhost:1337/admin but I get a CSRF error when I actually try and login. Any help would be much appreciated! I have tried setting up Nginx in Docker using the following files: Here's my docker-compose.yml file: services: web: build: . command: gunicorn config.wsgi -b 0.0.0.0:8000 environment: - SECRET_KEY=django-insecure-^+v=tpcw8e+aq1zc(j-1qf5%w*z^a-5*zfjeb!jxy(t=zv*bdg - ENVIRONMENT=development - DEBUG=True volumes: - .:/code - static_volume:/code/staticfiles expose: - 8000 depends_on: - db networks: - my-test-network db: image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ nginx: build: ./nginx ports: - "1337:80" volumes: - static_volume:/code/staticfiles depends_on: - web networks: - my-test-network volumes: postgres_data: static_volume: networks: my-test-network: driver: bridge Here's my dockerfile for Nginx: FROM nginx:1.25 RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d Here's my Nginx config file: upstream … -
Django Migration Error: NodeNotFoundError Due to Missing Migration Dependency in Django 5.0
My error is about this migrations and I couldn't understand, i'm burning about this error django.db.migrations.exceptions.NodeNotFoundError: Migration authuser.0001_initial dependencies reference nonexistent parent node ('auth', '0014_user_address_user_city_user_phone_number_and_more') This problem related to django? have to update it? I tried to delete all migrations but after that ruining my project. How to avoid it? -
CRITICAL: [Errno 104] Connection reset by peer in reviewboard due to UnreadablePostError: request data read error
In a reviewboard when am posting the review with rbtools (like cmd: 'rbt post') am getting CRITICAL: [Errno 104] Connection reset by peer error. In reviewboard logs am getting this StackTrace: request data read error Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.7/site-packages/django/views/decorators/cache.py", line 52, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/lib/python2.7/site-packages/django/views/decorators/vary.py", line 19, in inner_func response = func(*args, **kwargs) File "/usr/lib/python2.7/site-packages/djblets/webapi/resources/base.py", line 162, in call method = request.POST.get('_method', kwargs.get('_method', method)) File "/usr/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 146, in _get_post self._load_post_and_files() File "/usr/lib/python2.7/site-packages/django/http/request.py", line 219, in _load_post_and_files self._post, self._files = self.parse_file_upload(self.META, data) File "/usr/lib/python2.7/site-packages/django/http/request.py", line 184, in parse_file_upload return parser.parse() File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 140, in parse for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 598, in iter for sub_stream in boundarystream: File "/usr/lib/python2.7/site-packages/django/utils/six.py", line 535, in next return type(self).next(self) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 415, in next return LazyStream(BoundaryIter(self._stream, self._boundary)) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 441, in init unused_char = self._stream.read(1) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 315, in read out = b''.join(parts()) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 308, in parts chunk = next(self) File "/usr/lib/python2.7/site-packages/django/utils/six.py", line 535, in next return type(self).next(self) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 330, in next output = next(self._producer) File "/usr/lib/python2.7/site-packages/django/utils/six.py", line 535, in next return … -
Serving a dockerized react and django static files with nginx as web server and reverse proxy
I have simple dockerized react and django app that I'd like to serve using nginx as web server for serving both react and django's static files and as reverse proxy to forward user requests to the django backend served by gunicorn. But I have been struggling with nginx for serving react and django static files. here is the nginx Dockerfile: FROM node:18.16-alpine as build WORKDIR /app/frontend/ COPY ../frontend/package*.json ./ COPY ../frontend ./ RUN npm install RUN npm run build # production environment FROM nginx COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf COPY --from=build /app/frontend/build /usr/share/nginx/html here is the docker-compose file: version: '3.9' services: db: image: mysql:8.0 ports: - '3307:3306' restart: unless-stopped env_file: - ./backend/.env volumes: - mysql-data:/var/lib/mysql backend: image: vinmartech-backend:latest restart: always build: context: ./backend dockerfile: ./Dockerfile ports: - "8000:8000" volumes: - static:/app/backend/static/ env_file: - ./backend/.env depends_on: - db nginx: build: context: . dockerfile: ./nginx/Dockerfile ports: - "80:80" volumes: - static:/app/backend/static/ restart: always depends_on: - backend # - frontend volumes: mysql-data: static: here is the nginx configuration file: upstream mybackend { server backend:8000; } server { listen 80; location /letter/s { proxy_pass http://backend; } location /contact/ { proxy_pass http://backend; } location /admin/ { alias /static/; } location /static/ { alias /static/; } location / … -
Converting django serializer data to google.protobuf.struct_pb2.Struct gives error: TypeError: bad argument type for built-in operation
I want to create a response message in grpc with the following format: message Match { int32 index = 1; google.protobuf.Struct match = 2; google.protobuf.Struct status = 3; } I have a serializer and I want to convert the data into protobuf struct. my serializer is nested and long, so i have posted only a small part of the code in here. class MatchSerializer(proto_serializers.ModelProtoSerializer): competition = serializers.SerializerMethodField() match = serializers.SerializerMethodField() status = serializers.SerializerMethodField() class Meta: model = Match proto_class = base_pb2.Match fields = ['index', 'match', 'competition', 'status'] def get_competition(self, obj): data = SomeSerializer(obj.competition).data struct_data = struct_pb2.Struct() return struct_data.update(data) def get_status(self, obj): status_dict = { 0: {0: "not started"}, 1: {1: "finished"}, 2: {9: "live"}, } result = status_dict[obj.status] struct_data = struct_pb2.Struct() return struct_data.update(result) def get_match(self, obj): data = SomeOtherSerializer(obj.match).data struct_data = struct_pb2.Struct() return struct_data.update(data) Besides, I cannot find the source of what is really making this problem. I am getting this error from serializing: Traceback (most recent call last): File "/project/venv/lib/python3.10/site-packages/grpc/_server.py", line 555, in _call_behavior response_or_iterator = behavior(argument, context) File "/project/base/grpc/services.py", line 44, in GetUserSubscribedTeamsMatches return MatchSerializer(val).message File "/project/venv/lib/python3.10/site-packages/django_grpc_framework/proto_serializers.py", line 31, in message self._message = self.data_to_message(self.data) File "/project/venv/lib/python3.10/site-packages/rest_framework/serializers.py", line 555, in data ret = super().data File "/project/venv/lib/python3.10/site-packages/rest_framework/serializers.py", line 253, in … -
Ckeditor how addRichoCombo in fetch api?
CKEDITOR.plugins.add('type_elem_dropdown', { init: function (editor) { editor.on('instanceReady', function () { // Retrieve scenarioId and branchId from the editor's configuration var scenarioId = editor.config.scenarioId; var branchId = editor.config.branchId; // Function to fetch type_elements data function fetchTypeElements(scenarioId, branchId) { return fetch(`/scenario/${scenarioId}/branch/${branchId}/typeelements`) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .catch(error => { console.error('Error fetching type_elems:', error); return []; }); } // Fetch type elements and initialize the RichCombo fetchTypeElements(scenarioId, branchId).then(typeElems => { if (!typeElems || typeElems.length === 0) { console.warn('No typeElems available, aborting addRichCombo.'); return; } // Create RichCombo UI elements typeElems.forEach((element, index) => { // Add a RichCombo for each typeElem editor.ui.addRichCombo('TypeElemNames' + (index + 1), { label: 'Type Elements', title: 'Insert Type Element', voiceLabel: 'Type Elements', className: 'cke_format', multiSelect: false, panel: { css: [CKEDITOR.skin.getPath('editor')].concat(editor.config.contentsCss), attributes: { 'aria-label': 'Type Elements Dropdown' } }, init: function () { this.startGroup('Type Elements'); this.add(element.id, element.name, element.name); }, onClick: function (value) { editor.focus(); editor.fire('saveSnapshot'); editor.insertHtml(value); editor.fire('saveSnapshot'); } }); }); }); }); } }); I tried to add a dropdown list in editor with options of dropdown list by get from API (fetch(`/scenario/${scenarioId}/branch/${branchId}/typeelements`) but not working, show nothing. And I want to add many of Rich Combo, a number … -
ValueError at /admin/backoffice/profile/add/ save() prohibited to prevent data loss due to unsaved related object 'profile'
i use my prfile as a managing user models and i got this error: ValueError at /admin/backoffice/profile/add/ save() prohibited to prevent data loss due to unsaved related object 'profile'. i want add profile and then can login with these profiles that i created. my profile: class ProfileManager(BaseUserManager): def create_user(self, NATIONALID, password=None, **extra_fields): if not NATIONALID: raise ValueError("The NATIONALID field must be set") user = self.model(NATIONALID=NATIONALID, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, NATIONALID, password=None, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) return self.create_user(NATIONALID, password, **extra_fields) class Profile(models.Model): id = models.BigAutoField(primary_key=True) deathdate = models.DateField(blank=True, null=True, verbose_name='تاریخ فوت') isactive = models.BigIntegerField(default=1, blank=True, null=True, verbose_name='وضعیت کاربر') activefrom = models.DateTimeField(blank=True, null=True, verbose_name='فعال از') activeto = models.DateTimeField(blank=True, null=True, verbose_name='فعال تا') childrennumber = models.BigIntegerField(blank=True, null=True, verbose_name='تعداد فرزند') createdat = models.DateTimeField(auto_now_add=True, blank=True, null=True, verbose_name='تاریخ ایجاد') createdby = models.BigIntegerField(default=1, blank=True, null=True, verbose_name='ایجاد شده توسط') defunctdate = models.BigIntegerField(blank=True, null=True, verbose_name='') foundationdate = models.BigIntegerField(blank=True, null=True, verbose_name='') gender = models.BigIntegerField(blank=True, null=True, verbose_name='جنسیت') graduation = models.BigIntegerField(blank=True, null=True, verbose_name='سطح تحصیلات') location = models.BigIntegerField(blank=True, null=True, verbose_name='شهر') maritalstatus = models.BigIntegerField(blank=True, null=True, verbose_name='وضعیت تاهل') modifiedat = models.DateTimeField(auto_now=True, blank=True, null=True, verbose_name='تاریخ بروزرسانی') modifiedby = models.BigIntegerField(blank=True, null=True, verbose_name='بروزرسانی شده') religion = models.BigIntegerField(blank=True, null=True, verbose_name='مذهب') postalcode = models.CharField(max_length=10, blank=True, null=True, verbose_name='کدپستی') zonecode = models.CharField(max_length=10, blank=True, null=True, verbose_name='منطقه') FOREIGNERID = models.CharField(max_length=12, blank=True, … -
Media Files being unable to serve on production environment
I'm trying to deploy my django app on the render, but confronted a problem when I set DEBUG=FALSE. My media files, which are uploaded by using admin interface through the models' imagefield, are unable to show. I think the problem exists within my nginx settings and django setting. However, I've tryied several times but still unable to fix the problme. I set nginx.conf: http { include mime.types; server { listen 80; root C:/Users/USER/Desktop/onemoretime; # location / { # try_files $uri $uri/ =404; # } location /static/ { alias C:/Users/USER/Desktop/onemoretime/staticfiles/; } location /media/ { alias C:/Users/USER/Desktop/onemoretime/media/; } location / { proxy_pass http://127.0.0.1:8000; # 代理到 Waitress proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } } events {} and django setting: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') in this way. I think nginx should be able to deal with and serve all the media files, but the thing is the other way around. I'll be really thankful if someone know why the problem arise and how to fix it. Thank you so much. -
I am facing this error while running a docker file, and unable to solve it
I am getting this error while executing docker-compose build, i am unable to understand it. 1.241 The following information may help to resolve the situation: 1.241 1.241 The following packages have unmet dependencies: 1.324 mongodb-org-mongos : Depends: libssl1.1 (>= 1.1.0) but it is not installable 1.324 mongodb-org-server : Depends: libssl1.1 (>= 1.1.0) but it is not installable 1.324 mongodb-org-shell : Depends: libssl1.1 (>= 1.1.0) but it is not installable 1.327 E: Unable to correct problems, you have held broken packages. ------ failed to solve: process "/bin/sh -c apt-get install -y mongodb-org" did not complete successfully: exit code: 100 This is the docker file # set base image (host OS) FROM python:3.8 RUN rm /bin/sh && ln -s /bin/bash /bin/sh RUN apt-get -y update RUN apt-get install -y curl nano wget nginx git RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list # Mongo RUN ln -s /bin/echo /bin/systemctl RUN wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | apt-key add - RUN echo "deb http://repo.mongodb.org/apt/debian buster/mongodb-org/4.4 main" | tee /etc/apt/sources.list.d/mongodb-org-4.4.list RUN apt-get -y update RUN apt-get install -y mongodb-org # Install Yarn RUN apt-get install -y yarn # Install PIP RUN easy_install pip ENV ENV_TYPE staging … -
Django asks to migrate an unknown app: authtoken
Recently I got this message on running the server. You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): authtoken. The git branch is unchanged, no recent commit contains any authtoken relations. rest_framework.authtoken is part of INSTALLED_APPS since a long time, but as said, no recent changes relate to it. How can I discover what is causing this message in order to get rid of it? -
Django CSS not reflecting, issue only in my system
I encountered an issue where my CSS isn't loading. To troubleshoot, I tried running a previously working project created by my team, but I encountered the same problem. Even the Admin panel isn't loading correctly. It's an exact copy of the project, and I haven't made any changes. I activated the Python virtual environment and installed all the necessary requirements. Can someone help, please? I've tried most of the solutions I found online, including verifying the STATIC_URL, checking security permissions, and even reinstalling Python to match the versions on the machine where everything worked. -
Empty table in DB with django allauth
I am facing a problem with my django application which uses django-allauth as authentication framework. I need to authenticate to my application via google, store the authentication tokens, and then use the token to make some calls to the Google Search Console api. The first part (login) is going straightforward, but I am encountering a major problem in the second part. In particular, the socialaccount_socialapp table in the db remains empty. Does anyone spot any error in my settings? Or can anyone link me any resource regarding the use of Google Console API with an user authenticated with django allauth? These are my relevant parts of settings.py (default django resources omitted) SOCIALACCOUNT_PROVIDERS = { 'google' : { 'APP': { 'client_id' : os.getenv('CLIENT_ID'), 'secret' : os.getenv('SECRET'), 'key': '' }, 'SCOPE': ['profile', 'email', 'https://www.googleapis.com/auth/webmasters'], 'AUTH_PARAMS': { 'access_type' : 'offline', # per fare durare sessione }, "OAUTH_PKCE_ENABLED": True } } SOCIALACCOUNT_STORE_TOKENS = True MIDDLEWARE = [ #......... 'allauth.account.middleware.AccountMiddleware', ] INSTALLED_APPS = [ #........... 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' ] LOGIN_REDIRECT_URL = 'landing_page' LOGIN_URL = 'account_login' I did all the migrations, and it works for the login part, but when I run this view: try: social_account = SocialAccount.objects.get(user=request.user, provider='google') … -
Django formset show raw data in POST but never gets valid
I have the following Django structure. I use the latest Django version 5.1. I aim to get Formset working for the first time. Anyway, whatever I tried my formset is never valid. I can see raw data in request.POST but it does not validate therefore I never get parsed data in cleaned_data. What am I missing ? Model.py class Folder(models.Model): reference = models.CharField(max_length=64, null=False, unique=True,) class Revenue(models.Model): folder = models.ForeignKey(Folder, null=False, on_delete=models.RESTRICT,) amount = models.DecimalField(max_digits=10, decimal_places=2, null=False,) Form.py class FolderForm(forms.ModelForm): class Meta: model = models.Folder fields = ['reference'] class RevenueForm(forms.ModelForm): class Meta: model = models.Revenue fields = ["amount"] RevenueFormset = inlineformset_factory( models.Folder, models.Revenue, RevenueForm, validate_min=True, extra=1, can_delete=True ) View.py class FolderTestView(LoginRequiredMixin, UpdateView): template_name = "core/folder_test.html" model = models.Folder form_class = forms.FolderForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["revenue_formset"] = forms.RevenueFormset(instance=context["object"]) return context def post(self, request, *args, **kwargs): print(request.POST) # Contains whole form raw data formset = forms.RevenueFormset(request.POST) print(formset.is_valid()) # Always set as False return super().post(request, *args, **kwargs) def form_valid(self, form): print(form.cleaned_data) # Never gets the formset data return super().form_valid(form) def get_success_url(self): return reverse("core:folder-test", kwargs={"pk": self.kwargs["pk"]}) url.py urlpatterns = [ path('folder/<int:pk>/test/', views.FolderTestView.as_view(), name='folder-test'), ] folder_test.html <form action="{% url 'core:folder-test' object.id %}" method="POST"> {% csrf_token %} {{ form|crispy }} {{ formset.management_form }} … -
how can i used django on python 3.13?
am trying to install Django on Python 3.13 but am getting this problem (action) PS C:\Users\HP\desktop\AVP> python -m django --version Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\__main__.py", line 7, in <module> from django.core import management File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\management\__init__.py", line 19, in <module> from django.core.management.base import ( ...<4 lines>... ) File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\management\base.py", line 14, in <module> from django.core import checks File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\checks\__init__.py", line 18, in <module> import django.core.checks.caches # NOQA isort:skip ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\checks\caches.py", line 4, in <module> from django.core.cache import DEFAULT_CACHE_ALIAS, caches File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\cache\__init__.py", line 67, in <module> signals.request_finished.connect(close_caches) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^ File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\dispatch\dispatcher.py", line 87, in connect if settings.configured and settings.DEBUG: ^^^^^^^^^^^^^^ File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ val = getattr(_wrapped, name) ~~~~~~~^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'DEBUG' i tried uninstalling the existing Django the installing it again but all in vail -
How to store a `.shp` file to gisModel.GeometryField in model?
I have an example shp file and a model as follow class PolygonShape(models.Model): ... geometry = gisModel.GeometryField(null=False, srid=25832) ... def __str__(self): return self.name I want to upload the shp file and store it at GeometryField of the model. However, i dont know how to do it