Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django website stuck on default Nginx welcome page
So I tried hosting my client's website on Linode and I made the site using django. I am using Nginx and gunicorn for hosting but I am stuck in the default Nginx page. The following is my Nginx config: server { listen 80; server_name my.ip.address scopeplus.org www.scopeplus.org; error_log /var/log/nginx/error.log debug; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/scope_website/scope; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } The following is my gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/scope_website ExecStart=/root/venvPath/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ scope_website.wsgi:application [Install] WantedBy=multi-user.target The following is my gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target My settings.py file is located at the following path: root@localhost:~/scope_website/scope_website# pwd /root/scope_website/scope_website root@localhost:~/scope_website/scope_website# ls asgi.py __init__.py __pycache__ settings.py urls.py wsgi.py The following is the journalctl output from the Ubuntu terminal: Jan 20 14:24:33 localhost gunicorn[7619]: Forbidden (CSRF cookie not set.): / Jan 20 14:24:33 localhost gunicorn[7619]: - - [20/Jan/2024:14:24:33 +0000] "POST / HTTP/1.0" 403 2869 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36" Jan 20 14:45:50 localhost gunicorn[7617]: - - [20/Jan/2024:14:45:50 +0000] "GET / HTTP/1.0" 200 8692 "-" "Mozilla/5.0 zgrab/0.x" Jan … -
How to connect Django project to a SQL server 2019 database?
Django + MSSQL + Apple M1: ImportError with pyodbc Symbol Not Found in flat namespace '_SQLAllocHandle' I'm trying to connect a Django project running on an Apple M1 (ARM) architecture to a Microsoft SQL Server database. I'm using the mssql-django package, and I've encountered an issue with the pyodbc module. When I run python manage.py dbshell, I get the following error: Traceback (most recent call last): File ".../site-packages/mssql/base.py", line 17, in <module> import pyodbc as Database ImportError: dlopen(.../site-packages/pyodbc.cpython-312-darwin.so, 0x0002): symbol not found in flat namespace '_SQLAllocHandle' During handling of the above exception, another exception occurred: ... django.core.exceptions.ImproperlyConfigured: Error loading pyodbc module: dlopen(.../site-packages/pyodbc.cpython-312-darwin.so, 0x0002): symbol not found in flat namespace '_SQLAllocHandle' I've tried the following solutions: Reinstalling pyodbc with the specified architecture flags. Switching to pymssql as an alternative. Follow this tutorials: Install MSODBC MacOS, Cómo Conectar Django con SQL Server | django-mssql-backend However, the issue persists. Has anyone encountered a similar problem on Apple M1 and found a solution? Additional Information: Django version: [5.0.1] mssql-django: [1.4] pip: [23.3.2] pyodbc: [5.0.1] Python version: [3.12.0] Operating System: macOS [macOs Monterey v12.3] Database backend: mssql-django When executing the command python manage.py dbshell, I anticipate a successful connection to the database without encountering the … -
All msgstr empty inside django.po
I have implemented multi-language on my app but translations end up all empty, both from html and views: Inside django.po (there is more to this, all of them empty): #: .\src\playstyle_compass\templates\playstyle_compass\index.html:11 #: .\src\playstyle_manager\settings.py:143 msgid "English" msgstr "" #: .\src\playstyle_compass\templates\playstyle_compass\index.html:18 #: .\src\playstyle_manager\settings.py:144 msgid "Romanian" msgstr "" #: .\src\playstyle_compass\templates\playstyle_compass\index.html:25 msgid "Discover Your Perfect Games" msgstr "" #: .\src\playstyle_compass\templates\playstyle_compass\index.html:26 #: .\src\playstyle_compass\templates\playstyle_compass\index.html:27 msgid "text to be translated" msgstr "" #: .\src\playstyle_compass\views.py:61 msgid "Home :: PlayStyle Compass" msgstr "" Here is my configuration: settings.py: from django.utils.translation import gettext_lazy as _ MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ... ] LOCALE_PATHS = [ os.path.join(BASE_DIR, "src", "locale"), ] LANGUAGES = [ ('en', _('English')), ('ro', _('Romanian')), ] USE_I18N = True urls.py: urlpatterns = i18n_patterns( path("admin/", admin.site.urls), path("", include("playstyle_compass.urls")), path("users/", include("users.urls")), ... ) urlpatterns += [path("i18n/", include("django.conf.urls.i18n")),] HTML: {% extends "base.html" %} {% load i18n %} {% load static %} {% block page_header %} <link rel="stylesheet" type="text/css" href="{% static 'css/playstyle_compass/index.css' %}"> <ol> <li class=""> <a class="nav-link nav-user mr-0 waves-eff" href="/en{{ request.get_full_path|slice:'3:' }}" role="button"> <span class="pro-user-name ml-1"> {% trans "English" %} </span> </a> </li> <li> <a class="nav-link nav-user mr-0 waves-eff" href="/ro{{ request.get_full_path|slice:'3:' }}" role="button"> <span class="pro-user-name ml-1"> {% trans "Romanian" %} </span> </a> </li> </ol> <div class="jumbotron"> <div class="my-header"> <h1 … -
Problem with test automation django app with Jenkins
so generally I'm trying to automate some simple tests in my django app with Jenkins. The structure looks like this structure. I tried many different setups like: installing pacakges right into cointiner and trying to test, creating virtualenv inside of it or creating venv outside and importing it from my source version control and running in jenkins but nothing worked. Always i got message that it can't find django module like it could't find enviroment: Log examples from one of the builds logfileslogfileslogslogfiles My pipeline looked like this: pipeline steps. -
ImportError: cannot import name 'views' from 'drewmix' (C:\Users\USER\Desktop\storefront\drewmix\drewmix\__init__.py)
i am trying to use the python manage.py runserver command and i am getting the following error: ImportError: cannot import name 'views' from 'drewmix' (C:\Users\USER\Desktop\storefront\drewmix\drewmix_init_.py) ----break-------break----- my workspace setup i believe my view.py is in the correct place in my workspace. also i believe my urls.py is in the correct place in my workspace. below is the code for my urls.py sheet: from django.urls import path from django.contrib import admin from django.urls import path, include from . import views app_name = 'blog' urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')), path('', views.post_list, name='post_list'), path('<int:id>/', views.post_detail, name='post_detail'), ] -----break---------------break------------- below is the code for my views.py sheet: from django.shortcuts import render from .models import Post from django.http import Http404 from django.shortcuts import render, get_object_or_404 def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, id): post = get_object_or_404(Post, id=id, status=Post.Status.PUBLISHED) try: post = Post.published.get(id=id) except Post.DoesNotExist: raise Http404("No Post Found.") return render(request, 'blog/post/detail.html', {'post': post}) ---break-----------------break--------------- can anyone tell me what i am missing? this is getting frustrating. i am using python 3.8 and django 4.2 so far i have tried jumping around the code and deleting different portions and running the commands, but i am not getting anywhere. … -
What is the best backend language to use for chat app
Which language is best for me to use for the backend of my chat application. I was thinking NodeJS is good but i am seeing a recommendation from friends that Django or flask is better. Should i consider using laravel or anyother available. -
How does the server know that API call has been made from the client?
I am currently reading articles on REST API and how the client and server interaction works. I had a question in my mind which is as follows: How does the server know that REST API call has been made from the client? (Eg: I get a notification when a receive a message. So, from that I know I message in my inbox. How does server know about the REST api) Tried to find it on internet but didn't find any relevant answers. -
How can i filter displaying data from table by own order?
Don't have any idea how to sort the list of items. I have an existing data of types /class/order/family.... They taken from database . here output is look like this :output I want output with my own order : Type : PROTOZOA Klass: EUCILIATA Klass: MASTIGOPHORA klass: CILIATA Type: APICOMPLEXA klass: SPOROZOA Type: PLATHELMINTHES Type: NEMATHELMINTHES my models.py looks like this: class table_of_matches(models.Model): kingdom= models.CharField(max_length=250) type= models.CharField(max_length=250) klass= models.CharField(max_length=250) order= models.CharField(max_length=250) suborder= models.CharField(max_length=250, blank=True, null=True) superfamily= models.CharField(max_length=250, blank=True, null=True) family= models.CharField(max_length=250) subfamily= models.CharField(max_length=250, blank=True, null=True) tribus= models.CharField(max_length=250, blank=True, null=True) genus= models.CharField(max_length=250) subgenus= models.CharField(max_length=250, blank=True, null=True) species= models.CharField(max_length=250) subspecies= models.CharField(max_length=250, blank=True, null=True) author= models.CharField(max_length=250) ru_name= models.CharField(max_length=250, blank=True, null=True) en_name= models.CharField(max_length=250, blank=True, null=True) kz_name= models.CharField(max_length=250, blank=True, null=True) species_id = models.CharField(max_length=250) and this is my html <ul class="parent"> {% for ttype, klasses in data.items %} <li > <details > <summary>-Тип: {{ ttype }}</summary> <ul> {% for klass, orders in klasses.items %} <li> <details> <summary>- Класс: {{ klass }}</summary> <ul> {% for order, families in orders.items %} <li> <details> <summary>- Порядок: {{ order }}</summary> <ul> {% for family, items in families.items %} <li> <details> <summary>- Семейство: {{ family }}</summary> <ul> {% for item in items %} <p> <a href="{{item.species_id}}"> <i> {{item.genus}} {{item.species}} </i> / … -
I am getting below error while creating multiple custom get request inside single APIview class
My Views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class Sample(APIView): http_method_names = ['get', 'post', 'put', 'patch', 'delete'] def get(self, request): # Your logic for the default GET method response_data = {'message': 'Default GET method'} return Response(response_data, status=status.HTTP_200_OK) def get_fruits(self, request): # Your logic for a custom GET method fruits = ["apple", "mango", "orange"] response_data = {'fruits': fruits} return Response(response_data, status=status.HTTP_200_OK) def get_films(self, request): # Your logic for another custom GET method films = ["Saj", "don", "Man"] response_data = {"fnames": films} return Response(response_data, status=status.HTTP_200_OK) My Urls.py from django.urls import path from .views import Sample from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'Apiapp', Sample, basename='Sample') urlpatterns = [ path('sample/get_fruits/', Sample.as_view({'get': 'get_fruits'}), name='custom-endpoint-1'), path('sample', Sample.as_view(), name='get-fruits'), path('sample/films/', Sample.as_view({'get': 'get_films'}), name='get-films'),] i am getting this error -
how to solve error problems in django settings.py
When my friend used the same coding, but in coding he experienced an error in the settings.py file with the source code error in this section BASE_DIR = Path(file).resolve().parent.parent the resukts in cmd when he wants running the server NameError: name 'file' is not defined. Did you mean: 'file'? I've looked for it but don't know the answer -
ModuleNotFoundError: No module named 'kdconnector' in test script after checking things like PYTHONPATH, __init__.py etc
I created the following script to test for ModuleNotFound error I am getting in other scripts. #kdconnecotsite/facebookapi/methods/testing.py from kdconnector.models import Master, ClientAccounts, Client, Campaigns, Ads def Execute(access_token, app_secret, ad_id): return "test completed" # Example usage if __name__ == '__main__': print('example usage test') access_token = 'EAAUIU8EilCcBABhtG7ZAQKUPMuZBo8NWOUwhBhma5MaKS2VI3s0U8W3aARwkbqKoxe0zyo4Vsdc7MStyEvyRoWvptiDICaiFTSaU5ZAlANea2nziOHuNxyNaBn9w1O3y0ZCZCk03dpd2NeBr7q6qmOixYCaHYMaEuZCn7ZCO1llBKYYHGPGtA6TVOucsPWZBLHcZD' ad_id = '23853970342650529' app_secret = '123456789' result = Execute(access_token, app_secret, ad_id) print('result = %s', result) the PYTHONPATH includes the kdconnectorsite folder above the testing.py script as well as the kdconnector folder. On creating the script, vscode finds kdconnector, models, and all the models as I type in the script. Running the script in vscode yields, File "c:\Users\MikeOliver\KDConnectorSite\kdconnectorsite\facebookapi\methods\testing.py", line 3, in <module> from kdconnector.models import Master, ClientAccounts, Client, Campaigns, Ads ModuleNotFoundError: No module named 'kdconnector' Running check does not complain. (venv) PS C:\Users\MikeOliver\KDConnectorSite\kdconnectorsite> python manage.py check kdconnectorsite.__init__ opened logging.yaml 2024-01-20 10:46:38,394 - kdconnectorsite - INFO - Configured the logger! 2024-01-20 10:46:38,897 - kdconnector.models - INFO - Now logging in models 2024-01-20 10:46:38,897 - kdconnector.models - INFO - Now logging in models 2024-01-20 10:46:38,919 - kdconnector.admin - INFO - Now logging in admin 2024-01-20 10:46:38,919 - kdconnector.admin - INFO - Now logging in admin 2024-01-20 10:46:39,217 - kdconnector.fbugenerator - INFO - Now logging in FBUGenerator 2024-01-20 10:46:39,217 … -
Django Compressor TemplateDoesNotExists Error
I have followed the guide of setting up the django compressor from flowbite docs and the official ones. However is i move the link tag with my tailwind output file inside the compressor tags it throws TemplateDoesNotExist. I cannot figure out what is wrong. If i change the paths it cannot locate the file at all - so i quess the paths are correct. Here is the relevant sections from settings.py INSTALLED_APPS = [ 'core.apps.CoreConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'compressor' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "frontend/static")] STATIC_ROOT = os.path.join(BASE_DIR, "static_root") STATICFILES_FINDERS = ('django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder',) COMPRESS_ENABLED = True COMPRESS_ROOT = os.path.join(BASE_DIR, "frontend/static") and my test.html page: {% load static %} {% load compress %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> {% compress css %} <link rel="stylesheet" href="/static/style.css"> {% endcompress %} </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.2.1/flowbite.min.js"></script> </body> </html> this is the folder structure from root: folders Error: enter image description here I followed docs but cannot get the compressor to work -
How can I make the same links to send to instant messengers?
I started writing my website on Django and today I finally launched it on VPS. I sent the link to a friend and realized that it didn’t look good enough. I have my site like what i want result desired result I tried adding meta tags to HTML: <meta property="og:title" content=" MySite "> <meta property="og:site_name" content="ORXM Until"> <meta property="og:locale" content="ru_RU"> <meta property="og:type" content="website"> -
crypto confirmation using django
hey im creating a website where users need to send thir crypto namely usdt or worldcoin, im having trouble knowing who and what amount has been sent so that i can realise products, please help this is me trying to fetch prices using api sync def home(request): # Fetch Worldcoin (WLD) and USD prices from CoinGecko API asynchronously wld_price, usd_price = await asyncio.gather(fetch_price('worldcoin'), fetch_price('usd')) return render(request, 'index.html', {'wld_price': wld_price, 'usd_price': usd_price}) async def fetch_price(currency): api_url = f'https://api.coingecko.com/api/v3/simple/price?ids={currency}&vs_currencies=usd&x_cg_demo_api_key=CG-vQnfgGR63qMZ2LVVJfLJ2Wj2' response = await asyncio.to_thread(lambda: requests.get(api_url)) data = response.json() return data[currency]['usd'] -
Not seeing my view at api/docs. Not sure if its the url or the request im trying itself
The idea is to make POST, GET and DELETE requests for photos. When I try regestering the url at URL pattern nothing is showing yet im also not getting any errors. I feel like this should be a fairly easy fix no? views.py class GroundsDrivewayPhotosViewSet(APIView): """Manage comments in the database.""" serializer_class = serializers.GroundsDrivewayPhotosSerializer queryset = GroundsDrivewayPhotos.objects.all() authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] @api_view(['POST', 'GET', 'DELETE']) def upload_grounds_driveway_photo(self, request, pk=None): """Upload an image to report.""" report = self.get_object() serializer = self.get_serializer(report, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get_queryset(self): """Filter queryset to authenticated user.""" return self.queryset.filter(user=self.request.user).order_by( 'grounds_driveway_photos') urls.py app_name = 'report' urlpatterns = [ path('photos/grounds-driveway-photos', views.GroundsDrivewayPhotosViewSet.as_view(), name="grounds-driveway-photos") ] -
Creating Custom Filter in Django Admin with JavaScript Flatpickr
I am currently working on a project where I have successfully integrated Flatpickr calendar into my Django admin view. The calendar allows users to select a date, and I want to extend this functionality by creating a custom filter. Essentially, I want to replicate the behavior of a Django-filter, but with my custom calendar. Could anyone provide guidance on how I can achieve this? Are there any existing examples or resources that demonstrate the integration of a custom JavaScript calendar with Django admin filters? I already tried with Custom filters but I can not achieve the functionality that iam looking for Thank you -
How do I configure Django / Nginx to serve later-created Media files?
In my views.py, I have a function that creates a .wav file (speech synthesis of user-created input). This file is then stored in my media folder: (views.py): filepath = synthesize_speech(text, language) if filepath: # Provide a URL to access the audio file audio_url = request.build_absolute_uri(settings.MEDIA_URL + filepath) return JsonResponse({'audio_url': audio_url}) (settings.py): MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This works together with (urls.py) really well in DEBUG: urlpatterns = [ # other URL patterns... ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But in production, using Nginx, this does not work anymore. My Nginx config looks like this (nginx.conf): server { listen 80; location / { proxy_pass http://web:8000; 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; } location /static/ { alias /usr/src/app/staticfiles/; } location /media/ { alias /usr/src/app/media/; } } Also, I have added a volume (docker-compose.yml): version: '3' services: ... nginx: build: ./nginx ports: - "80:80" volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/media depends_on: - web redis: image: "redis:alpine" volumes: static_volume: media_volume: (Please note, I have read, that it is not ideal to have the media folder within the Django project, but that is for now the easiest way for me to switch between dev and prod). I … -
Django admin login only works with superusers created from shell
i have a custom user using AbstractUser just to add timestamps and a fk to it from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings from .managers import CustomUserManager class SubUser(AbstractUser): if settings.DEBUG: parent_user_id = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True, blank=True) else: parent_user_id = models.ForeignKey('self', on_delete=models.RESTRICT, null=True, blank=True) # Timestamps created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = "username" objects = CustomUserManager() def __str__(self): return self.username I read that to encrypt passwords well I must create a manager: from django.contrib.auth.base_user import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, username, password=None, **extra_fields): user = self.model(username=username, **extra_fields) print(username) print(password) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password=None, **extra_fields): user = self.create_user(username, password, **extra_fields) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user when i create a superuser from shell: u = SubUser.objects.create_superuser(username='asd', password='asdasd') the instance creates successfully, the password is encrypted and my login in admin/ with that superuser works but if i create a normal user: u = SubUser.objects.create_user(username='qwe', password='qweqwe') the instance creates successfully, the password is encrypted and BUT my login in admin/ DOESNT work now, also i read that if I use a custom user i should use my manager, in the shell i did: user_manager = CustomUserManager() new_user = … -
Image attribute of an object not working in django
I am looping through each object and image attribute of the objects dont appear on the website. is the attribute of the objects home.html file I want to see the photos of each object with for loop on my website I did all the necessary changes in settings.py -
How to manage the increase in memory consumption of redis-server in a Docker environment?
I am using the redis-server as part of a Docker stack in a Django project that uses Celery Beat for scheduled tasks. While monitoring the processes with the htop command, I noticed that the memory used by the redis-server progressively increases over time. The increase in memory seems to be gradual and continuous. Are there recommended practices or settings that I should implement to manage the memory used by the redis-server, especially in an environment with Celery Beat?" Docker version 24.0.7 Docker Compose version v2.21.0 local.yml redis: image: redis:6 container_name: scielo_core_local_redis ports: - "6399:6379" celeryworker: <<: *django image: scielo_core_local_celeryworker container_name: scielo_core_local_celeryworker depends_on: - redis - postgres - mailhog ports: [] command: /start-celeryworker celerybeat: <<: *django image: scielo_core_local_celerybeat container_name: scielo_core_local_celerybeat depends_on: - redis - postgres - mailhog ports: [] command: /start-celerybeat base.py # Celery # ------------------------------------------------------------------------------ if USE_TZ: # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-timezone CELERY_TIMEZONE = TIME_ZONE # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-broker_url CELERY_BROKER_URL = env("CELERY_BROKER_URL") # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_backend CELERY_RESULT_BACKEND = CELERY_BROKER_URL # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-accept_content CELERY_ACCEPT_CONTENT = ["json"] # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-task_serializer CELERY_TASK_SERIALIZER = "json" # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_serializer CELERY_RESULT_SERIALIZER = "json" # http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-time-limit # TODO: set to whatever value is adequate in your circumstances CELERY_TASK_TIME_LIMIT = 5 * 60 # http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-soft-time-limit # TODO: set to whatever value is adequate in your circumstances CELERY_TASK_SOFT_TIME_LIMIT = … -
Django doesn't recognise column added using RunSQL Migration
I am trying to add a SERIAL non-primary column to an existing table. Django does not seem to have support for this (AutoField must be primary, and I cannot make this field primary). However postgres does support SERIAL columns, so in the generated migration file I can add the following operation: class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.RunSQL( sql="ALTER TABLE portal_referral ADD referral_id SERIAL;", reverse_sql="ALTER TABLE portal_referral DROP referral_id;" ) ] however, it does not appear that Django 'registers' the effects of this migration. That is to say, when running manage.py makemigrations again, the tool will attempt to add referral_id again in a new migration. The model is defined as class Referral(utils.UUIDPrimaryKeyBase, utils.TimeStampedModel): data = models.JSONField(encoder=DjangoJSONEncoder) supplier = models.ForeignKey(Supplier, blank=True, null=True, on_delete=models.PROTECT, related_name="referrals") session_id = models.UUIDField(editable=False, blank=True, null=True, unique=True) referral_id = models.IntegerField() def __str__(self): return f"<referral id={self.id} supplier={self.supplier}>" I did find a way to work around this, where after letting the migration generate its code I can insert some overriding SQL statements afterwards. class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.AddField( model_name='referral', name='referral_id', field=models.IntegerField(default=0), preserve_default=False, ), migrations.RunSQL( sql="ALTER TABLE portal_referral DROP referral_id;", reverse_sql="ALTER TABLE portal_referral ADD referral_id INT DEFAULT 0;" ), migrations.RunSQL( sql="ALTER … -
TypeError: SearchProduct.get() got an unexpected keyword argument 'query'
in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2 and axios 0.21.4 and WebStorm 2023.1.3 IDE and PyCharm Community Edition 2023.2 and djangorestframework==3.14.0 and Django==4.2.4 and djangorestframework-simplejwt==5.3.0. question : Actually, I don't know how to send this query parameter to Django's base class view that inherits from GenericAPIView , how solve this error ? BACKEND: Consider - product_views.py : class SearchProduct(GenericAPIView): serializer_class = ProductSerializer pagination_class = CustomPagination1 def get_queryset(self, *args, **kwargs): # the lead id query = self.request.GET.get("query") # this filter base on the lead id provided lookup = Q(name__icontains=query) | Q(description__icontains=query) | Q(producttag__title__icontains=query) products = Product.objects.filter(lookup).distinct() return products def get(self, request): page = self.paginate_queryset(self.get_queryset()) if page is not None: serializer = self.get_serializer(page, many=True) result = self.get_paginated_response(serializer.data) data = result.data # pagination data else: serializer = self.get_serializer(queryset, many=True) data = serializer.data payload = { 'return_code': '0000', 'return_message': 'Success', 'data': data } return Response(data , status=status.HTTP_200_OK) Consider - product_urls.py: path('search_product/<str:query>/' , views.SearchProduct.as_view() , name="search_product"), FRONTEND: Consider - productAction.py: export const productsSearchAction = (query , pageNumber) => async (dispatch , getState) => { try { dispatch({type: PRODUCTS_SEARCH_REQUEST}); const {data} = await axios.get(`http://127.0.0.1:8000/api/v1/products/search_product/${query}/?page=${pageNumber}`); dispatch({type: PRODUCTS_SEARCH_SUCCESS , payload: data}); localStorage.setItem("productsSearch" , JSON.stringify(data)); } catch (error) { dispatch({ // PRODUCTS … -
why volumes not working correctly in docker whene i try to dockerize django app?
The issue arises when I attempt to proceed without using volumes; everything works correctly. However, when volumes are included, I get the following error: django_app | python: can't open file '/app/manage.py': [Errno 2] No such file or directory docker-compose : version: '3.8' services: app: build: . volumes: - ./django:/app // the problem is here ports: - "8000:8000" image: app:django container_name: django_app command: python manage.py runserver 0.0.0.0:8000 dockerfile : FROM python:3.12.1-slim ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . -
didn't redirect to next parameter? django
my authentication view: class LoginView(auth_views.LoginView): form_class = LoginForm template_name = 'event/login.html' def post(self, request, *args, **kwargs): next_url = self.request.POST.get('next', reverse('event:create_table')) response = super().post(request, *args, **kwargs) redirect_url = reverse('event:login') + f"?next={next_url}" #ログインできたら、前の画面・ホーム画面に戻る if self.request.user.is_authenticated: return redirect(next_url) else: return redirect(redirect_url) return response class RegisterView(generic.CreateView): form_class = RegisterForm template_name = 'event/register.html' #登録できたら、前の画面・ホーム画面に戻る def form_invalid(self, form): messages.error(self.request, '会員登録に失敗しました。正しい情報を入力してください。') next_url = self.request.GET.get('next', reverse('event:create_table')) return redirect(next_url) def get_success_url(self): messages.success(self.request, '会員登録完了!ログインしてください') next_url = self.request.GET.get('next', reverse('event:create_table')) return next_url my login html: <h1>ログイン</h1> <form action="{% url 'event:login' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="hidden" name="next" value="{{ request.GET.next }}"> <!-- ログインボタン --> <button type="submit" class="submit-button" id="submit">ログイン</button> </form> My problem was it didn't redirect to the previous page after login. It worked before this but suddenly it didn't. The url included the previous url in the next parameter but after submitting the form, it redirect to the default event:create_table. Can someone give me any idea why did this happen?? i tried changing to request.POST.get('next', reverse('event:create_table')) and it kinda seems to work, but previously i use request.POST it didn't work so now I am confused. And in my test case, request.POST didnt redirect to the correct url but request.GET did so I don't know my django website couldn't work … -
How can I reset the username in Django if I mistakenly set it wrong?
Is it possible to reset the superusername in Django if it was mistakenly set incorrectly? I made an error during the initial setup and need guidance on how to rectify it. What steps can be taken to change or reset the username in Django to ensure accuracy and consistency with the intended information? I want the solution for reset the superusername n in Django