Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Configure a Reverse Proxy for a Django Project on GoDaddy with Apache to Hide Port 8000
I have a Django project that I've uploaded to a GoDaddy server running Apache. I’m using a domain with the .com extension, and I've started the Django development server with the command python manage.py runserver 0.0.0.0:8000. This makes the project accessible through the domain with port 8000 (e.g., www.example.com:8000). I would like to hide the port or route requests internally to port 8000 using a reverse proxy, but it’s not working. Additionally, when I try to access the site directly through the domain without specifying the port, it shows my folder structure instead of the Django application. Could you help me with configuring the reverse proxy or resolving the issue with accessing the Django project directly through the domain? I’ve attempted various commands and configuration setups in the .conf file to configure a reverse proxy and hide the port, but nothing seems to work -
Django Admin: Model visible locally but not in production
I'm encountering an issue with a Django application. I created a model and registered it in the admin. Everything works fine locally and I can see the model in the admin interface, but in production, it doesn't appear. I have verified that the migrations have been applied correctly both locally and in production. I used showmigrations and everything seems to be in order. I checked the production database via shell_plus and the model's table exists. I also created a record manually to ensure it works. My admin.py is configured correctly and looks identical in both the local and production environments. # admin.py from django.contrib import admin from myapp.models import MyModel @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ('field1', 'field2', 'field3') I cleared the browser cache and tried a different browser, but nothing changed. I can't figure out why the model doesn't appear in the admin in production. Any suggestions on what I might check or do to resolve this issue? -
How can I have a different method instead of user.is_authenticated?
I have an academy website , which has 3 different kinds of users. The first one is the staff that I handle with the admin panel. The second one is parents or people who are going to get some information about the academy. The third one is students who have a different panel. My question is how can I authenticate this students ? I mean we have a method that is {% user.is_authenticated %} but it isn't ok for me because I want to check a different model named "students" and I used this method for other places. I expect a different authentication system. Because the one which I used is for regular users and I want to check that if he is a student he can have access to the special panel. Please share your ideas. -
Socket IO is rejecting requests from Nginx proxy
I have this docker application running several containers. One of these containers is a Python application that can handle both socket io requests and normal HTTP requests. Django's ASGI handles HTTP/ASGI requests while python-socketio handles socket requests. Since there are 4 other applications like this which must all be server via Nginx, I have to specify namespace URLs for both the socket io and ASGI applications for all the applications. I am using the following configuration for the application: location /app/ { 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; proxy_pass http://app:8000/; # docker container name is "app" } location /app/socket.io/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; 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; proxy_pass http://app:8000/socket.io/; # docker container name is "app" proxy_read_timeout 86400s; proxy_send_timeout 86400s; } asgi.py import os import socketio from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") django_application = get_asgi_application() from app.async_socketio.server import sio # noqa 402 # this allows Socket IO to handle requests by default to a # default path of /socket.io and forwards any other requests # to the Django application. application = socketio.ASGIApp(sio, django_application) # just so all my socket event handles can … -
Django reduce number of returned rows for chart
I have model with timestamp=DateTimeField() and some extra numerical data. In table I stores data from sensor collected each minutes. I have views returning chart with data from mentioned table which is parameterize by start_date and end_date. Chart works great for data from max few days period, but everything "explode" when period is longer (do many records). I don't want to reinvent the wheel. I want return only n representatives records for time period (for example with avg value). I believe that my problem is common one, but I can not google ready solution for it. -
Django DateField persistence
I have a model / Form / view for a request that works well, but when I want to update a request all the fields are loaded except the due_date field (with a date widget) witch remains empty. If I don't pay attention I validate and the due_date become None. I would like it to load the date that was saved during creation by default and then I modify it or not. Here is the code. Model class Request(models.Model): thematic = models.ForeignKey( Thematic, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Thématique", ) context = models.ForeignKey( Context, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Contexte", ) technical_element = models.CharField( max_length=255, verbose_name="Élément technique", blank=True, null=True ) due_date = models.DateField(verbose_name="Date d'échéance", blank=True, null=True) def __str__(self): return self.context class Meta: verbose_name = "Request" verbose_name_plural = "Requests" Forms class RequestForm(forms.ModelForm): new_thematic = forms.CharField( max_length=255, required=False, label="New Thematic" ) new_context = forms.CharField( max_length=255, required=False, label="New Context" ) due_date = forms.DateField( widget=forms.DateInput(attrs={"type": "date"}), required=False, ) class Meta: model = Demande fields = "__all__" widgets = { "thematic": forms.Select(attrs={"class": "form-control"}), "context": forms.Select(attrs={"class": "form-control"}), "technical_element": forms.TextInput(attrs={"class": "form-control"}), "due_date": forms.DateInput( attrs={"class": "form-control", "type": "date"} ), } def __init__(self, *args, **kwargs): super(DemandeForm, self).__init__(*args, **kwargs) if "instance" in kwargs: instance = kwargs["instance"] if instance.due_date: self.fields["due_date"].initial = instance.due_date self.fields["thematic"].queryset = Thematic.objects.all() … -
stuck with multithreading
i am reading multiple hdf5 files and those hdf5 file will be having datasets in heirarchy , i am fetching data from these hdf5 files , i am using multi threading inside hdf5 file to increase reading speed, also tell how can i make this fast, do i need to change my structure or reading way, i amm using python 2.7 and django 1.8: present is : their are multiple client_id.hdf5 , inside it multiple ship_ids -> report_types-> time_stamp-> in that data for that time i did this , it is only printing till Data fetched. Starting multiprocessing... ('Processing client:', 112): import h5py import os import json import time from datetime import datetime from multiprocessing import Pool from vast import models import dateutil.parser from_date = dateutil.parser.parse('2023-06-01') to_date = dateutil.parser.parse('2024-04-30') boss_dir = '/home/bwit-laptop3/boss' new_structure_dir = os.path.join(boss_dir, 'Data/new_mirror_data_for_fetching') def fetch_and_save_data(): data_dict = {} mirrors_info = models.mirrorv2_info.objects.filter(report_date__gte=from_date, report_date__lt=to_date, client_id=112) for mirror_info in mirrors_info: ship_id = mirror_info.ship_id report_date = mirror_info.report_date client_id = mirror_info.client_id report_type = mirror_info.report_type client_dict = data_dict.setdefault(client_id, {}) ship_dict = client_dict.setdefault(ship_id, {}) report_type_dict = ship_dict.setdefault(report_type, {}) date_string = report_date.strftime("%Y-%m-%d %H:%M:%S") report_date_list = report_type_dict.setdefault(date_string, []) print("Data fetched. Starting multiprocessing...") get_data_multiprocess(data_dict) file_path = os.path.join(boss_dir, 'data_fetch_new_way.json') directory = os.path.dirname(file_path) if not os.path.exists(directory): os.makedirs(directory) with open(file_path, … -
django.db.utils.OperationalError: could not translate host name "postgres.railway.internal"
django.db.utils.OperationalError: could not translate host name "postgres.railway.internal" to address: nodename nor servname provided, or not known my django project was working great, until a changed the setting.py file to deploy it in railway, using the variables railway provides. since then i can't runserv or migrate, that i get this error... here is the database settings a changed to use the railway variables DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'railway', 'USER': 'postgres', 'PASSWORD': DB_PASSWORD_RAIL, 'HOST': 'postgres.railway.internal', 'PORT': '5432', } } error when i runserver or migrate django.db.utils.OperationalError: could not translate host name "postgres.railway.internal" to address: nodename nor servname provided, or not known -
Why celery beat scheduler still running after expires in django celery
PeriodicTask.objects.create( interval=interval, crontab=crontab, clocked=clocked, name=data["name"], task=data["task"], # dropdown args=json.dumps(json.loads(data["args"])), one_off=True if schedule_type == "clocked" else False, expires=datetime.strptime(data["expires"], '%Y-%m-%d %H:%M:%S.%f') if data["expires"] else None ) -its still running after set expires time -its not calling function but its hit worker ex: in worker terminal [2024-07-22 07:06:16,334: INFO/MainProcess] Task test[390404a1-9814-4208-85a2-6e1269bc09d9] received [2024-07-22 07:06:16,334: INFO/MainProcess] Discarding revoked task: test[390404a1-9814-4208-85a2-6e1269bc09d9] and in celery beat terminal [2024-07-22 07:06:16,327: WARNING/MainProcess] 390404a1-9814-4208-85a2-6e1269bc09d9 has an expiration date in the past (16.325898s ago). We assume this is intended and so we have set the expiration date to 0 instead. According to RabbitMQ's documentation: "Setting the TTL to 0 causes messages to be expired upon reaching a queue unless they can be delivered to a consumer immediately." If this was unintended, please check the code which published this task.``` -
Python (Django) Data Manipulation
"How can I transform Excel attendance data into a specific database insertion format?" **I have data in Excel that looks like this: ** This is data format I **need to convert this into a format suitable for database insertion, like this: ** Data That i want -
Uploaded media doesn't server in production mode without restarting django
I need to serve media in Django in production mode and it is very little need to serve telegram user photos in Django admin. so I know everything about Django it's not for serving files or media so there is no need to repeat repetitive things. I just need to serve media in production mode for my purpose so I use WhiteNoise to do this and append this lines: MIDDLEWARE = [ ... 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'medias') in urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('botAPI.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS[0]) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) else: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in wsgi.py I put this: ... application = get_wsgi_application() application = WhiteNoise(application, root=MEDIA_ROOT, prefix='/media/') .... It works correctly and serves media files in production mode. but for new media for example uploading an image in Django admin I have to restart Django to access that media. is there any way to solve this problem or another way in Django to serve … -
Use correct Bootstrap CSS in Django forms for Radio select form input
How to get Django forms to render correct Bootstrap to a Radio select form input? I passed form-control form-check classess in the form, yet the form HTML produced is not accurate for radio select option. I am looking to render the bootstrap primary color and inline radio buttons. Form class PersonForm(forms.Form): Gender = forms.ChoiceField(required=True, widget=forms.RadioSelect( attrs={"label":"Gender", "id":"G", "placeholder": "Gender", "class":"form-control form-check"}), choices=genders.items) HTML <div id="G" class="form-control form-check"> <div> <label for="G_0"><input type="radio" name="Gender" value="M" label="Gender" id="G_0" placeholder="Gender" class="form-control form-check" required=""> Male</label> </div> <div> <label for="G_1"><input type="radio" name="Gender" value="F" label="Gender" id="G_1" placeholder="Gender" class="form-control form-check" required=""> Female</label> </div> <div> <label for="G_2"><input type="radio" name="Gender" value="N" label="Gender" id="G_2" placeholder="Gender" class="form-control form-check" required=""> Not-Applicable</label> </div> -
Why does Prefetch perform better than annotation in django?
Hello I made a code to make it irregular. Can someone tell me why prefetch is faster when the prediction should be faster? annotate test: execution time: 6.65 seconds prefetch test: execution time: 3.02 seconds @transaction.atomic() def set_default_like_place_annotate(start, end): start_time = time.time() print(f"Start time: {start_time}") place_query = Place.objects.filter(removed_at__isnull=True).annotate( exist_liking_count=models.Count('place_likers', filter=Q(place_likers__removed_at__isnull=True)))[start:end] for place in place_query: place.liking_count = place.exist_liking_count place.save() end_time = time.time() elapsed_time = end_time - start_time print(f"execution time: {elapsed_time:.2f} seconds") Here is prefetch code @transaction.atomic() def set_default_like_place_prefetch(start, end): start_time = time.time() print(f"Start time: {start_time}") place_query = Place.objects.filter(removed_at__isnull=True).prefetch_related( models.Prefetch( 'place_likers', queryset=LikingPlace.objects.filter(removed_at__isnull=True), to_attr='_place_likers', ))[start:end] for place in place_query: place.liking_count = len(place._place_likers) place.save() end_time = time.time() print(f"End time: {end_time}") print(f"execution time: {end_time - start_time:.2f} seconds") -
In Django, how do I pass custom information from the user signup html form to the models?
In my Django project, I have two types of profiles (person and business). Based on the form a user fills in signup.html (which is very rudimentary right now) one of the types profiles will be created. (My implementation is based on this - section Extending User Model Using a One-To-One Link). models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) company_name = models.TextField(max_length=100, null=True, blank=True) phone_number = models.TextField(max_length=20, null=True, blank=True) is_vendor = models.BooleanField(default=False) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py: class SignupForm(UserCreationForm): class Meta: model = User fields = ('username', 'email', 'password1', 'password2',) username = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': 'Your username', 'class': 'w-full py-4 px-6 rounded-xl' })) ... class BusinessSignupForm(SignupForm): class Meta(SignupForm.Meta): model = User fields = SignupForm.Meta.fields + ('company_name',) company_name = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': 'Company name', 'class': 'w-full py-4 px-6 rounded-xl' })) class PersonSignupForm(SignupForm): class Meta: model = User fields = SignupForm.Meta.fields + ('phone_number',) phone_number = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': 'Phone number', 'class': 'w-full py-4 px-6 rounded-xl' })) views.py: def signup(request): form_personal = PersonSignupForm() form_business = BusinessSignupForm() if request.method == 'POST': if 'personal_account' in request.POST: form = PersonSignupForm(request.POST) elif 'business_account' in request.POST: form = BusinessSignupForm(request.POST) else: return render(request, 'core/signup.html', {'error': 'Invalid … -
How to register Django hooks with PyInstaller
I want to use the Django hooks in Pyinstaller. I have tried the following: python -m PyInstaller --runtime-hook='hook-django.contrib.sessions.py' --runtime-hook='hook-django.core.cache.py' --runtime-hook='hook-django.core.management.py' --runtime-hook='hook-django.db.backends.py' --runtime-hook='hook-django.py' --runtime-hook='hook-django.template.loaders.py' ... --noconfirm --console --clean manage.py But I am getting FileNotFoundError: [Errno 2] No such file or directory: '.../hook-django.*.py' Should I use the additional-hooks-dir parameter even with the built-in hooks, if so what value should I provide? -
getting error "Application not found" whenever i restart my django app on cpanel
Am trying to set up my django app in c-panel but facing a certain. Whenever i restart the app, Am getting the below error No such application (or application not configured) And whenever i edit the app config and click save i get the below error Error KeyError: 'Config does not contain directory: mutoconsults.kimdigitary.com/muto-consults' Below is my app configuration, and cpanel shows my app is already running. enter image description here And if i navigate to the domain name i get the below info it works python 3.9 -
One project (Django 3 with mod_wsgi installed within py 3.8 venv) works but another (Django 5 with mod_wsgi installed within py 3.12) fails
Issue: Internal Server Error with Django and mod_wsgi on Ubuntu Server Setup: Ubuntu 20.04 Python 3.8 for existing project Python 3.12.4 for new project Apache system mod_wsgi installed in respective virtual environments. The system level has been removed. Projects: Existing Project (Working ✅) Directory: /var/www/existing-project/ Python Version: 3.8 Virtual Environment Path: /var/www/existing-project/venv WSGI File Path: /var/www/existing-project/project/project/wsgi.py Apache Configuration: Protocols h2 http/1.1 WSGIApplicationGroup %{GLOBAL} LoadModule wsgi_module "/var/www/existing-project/venv/lib/python3.8/site-packages/mod_wsgi/server/mod_wsgi.cpython-38-x86_64-linux-gnu.so" <VirtualHost *:80> ServerAdmin admin@example.com ServerName existing-project.com DocumentRoot /var/www/existing-project/project/ RemoteIPHeader CF-Connecting-IP ErrorLog ${APACHE_LOG_DIR}/existing-project_error.log CustomLog ${APACHE_LOG_DIR}/existing-project_access.log combined <Directory /var/www/existing-project/project/project> <Files wsgi.py> Require all granted </Files> </Directory> Alias /favicon.ico /var/www/existing-project/project/static/images/favicon/favicon.ico Alias /static /var/www/existing-project/project/static <Directory /var/www/existing-project/project/static> Require all granted </Directory> <IfModule mod_expires.c> <FilesMatch "\.(png|jp?g|gif|ico|mp4|wmv|mov|mpeg|css|map|woff?|eot|svg|ttf|js|json|pdf|csv)"> ExpiresActive on ExpiresDefault "access plus 1 year" </FilesMatch> </IfModule> WSGIDaemonProcess existing-project python-home=/var/www/existing-project/venv python-path=/var/www/existing-project/project WSGIProcessGroup existing-project WSGIScriptAlias / /var/www/existing-project/project/project/wsgi.py RewriteEngine on RewriteCond %{SERVER_NAME} =existing-project.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> New Project (Not working ❌) Directory: /var/www/new-project/ Python Version: 3.12.4 Virtual Environment Path: /var/www/new-project/venv WSGI File Path: /var/www/new-project/project/project/wsgi.py Apache Configuration: WSGIApplicationGroup %{GLOBAL} LoadModule wsgi_module "/var/www/new-project/venv/lib/python3.12/site-packages/mod_wsgi/server/mod_wsgi-py312.cpython-312-x86_64-linux-gnu.so" <VirtualHost *:80> ServerAdmin admin@example.com ServerName new-project.com DocumentRoot /var/www/new-project/project/ RemoteIPHeader CF-Connecting-IP # Basic HTTP Authentication <Directory /var/www/new-project/project> AuthType Basic AuthName "Restricted Area" AuthUserFile /etc/apache2/.htpasswd Require valid-user </Directory> ErrorLog ${APACHE_LOG_DIR}/new-project_error.log CustomLog ${APACHE_LOG_DIR}/new-project_access.log combined <Directory /var/www/new-project/project/project> <Files wsgi.py> Require all granted </Files> </Directory> Alias … -
I have been trying to launch an application for about 4 days in Django to Render
`System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\backends\base\base.py", line 275, in ensure_connection self.connect() File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\backends\base\base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\backends\postgresql\base.py", line 277, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: connection to server at "viaduct.proxy.rlwy.net" (35.212.103.87), port 52584 failed: received invalid response to SSL negotiation: I The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1045, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 982, in run self._target(*self._args, **self._kwargs) File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\core\management\commands\runserver.py", line 136, in inner_run self.check_migrations() File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\core\management\base.py", line 581, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\migrations\loader.py", line 58, in init self.build_graph() File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\migrations\recorder.py", line 89, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\db\migrations\recorder.py", line 63, in has_table with self.connection.cursor() as cursor: ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\DEV\DJANGO\dealer_project\env\Lib\site-packages\django\utils\asyncio.py", line … -
How can I pass headers in Swagger UI?
I am trying to hit the API using Django Swagger UI, but I am not getting header in API. I have tried all the answered solutions but I don't know how none of them worked for me. What am I doing wrong? I am using: drf-spectacular v0.26.2 module. Here is my API view: from rest_framework.permissions import IsAuthenticated from drf_spectacular.utils import extend_schema from rest_framework.views import APIView from rest_framework.response import Response authorization_params_in_header = OpenApiParameter( "Authorization", OpenApiTypes.STR, OpenApiParameter.HEADER, required=True ) class ProtectedView(APIView): permission_classes = (IsAuthenticated,) @extend_schema( tags=["Protected"], parameters=[authorization_params_in_header], responses={200: "Success"}, ) def get(self, request): data = {"message": "This is a protected resource"} return Response(data) When I hit the API, even if I put header in the field, Swagger does not pass it in curl also, which you see in picture below. -
Change title (verbose name plural) in custom admin.TabularInline
In my Django admin UI I use a TabularInline like this: class MyCustomInline(admin.TabularInline): # ... def get_queryset(self, request): # ... The overridden functions adds a filter, so that only a subset of related objects is displayed. In the admin UI I get table using the plural of the model class as title, which is wrong in this case. I would like to give it a custom name. I cannot do this for the model itself, because I want to change the title only for this filtered set. Not for the model class in general. I tried to figure it out from the source code. In the template I found out that the verbose_name is passed in via opts, but could not follow its path to find a way to override it. Could somebody give me a hint how to change the title aka verbose name just for this specific TabularInline? -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.User' that has not been installed
I just create Django project and get this error django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.User' that has not been installed this my files settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "rest_framework", "api", ] AUTH_USER_MODEL = "api.User" models from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth import get_user_model class User(AbstractUser): ACTIVE = 0 DEACTIVE = 1 STATUS = [ (ACTIVE,"active"), (DEACTIVE,"deActive") ] chatID = models.PositiveBigIntegerField() fname = models.CharField(max_length=20) lname = models.CharField(max_length=20) invitedBy = models.ForeignKey(to=get_user_model(),on_delete=models.PROTECT,default=None) point = models.PositiveBigIntegerField(default=0) team = models.ForeignKey(to=TelegramGroup,on_delete=models.CASCADE) custom_status = models.PositiveSmallIntegerField(choices=STATUS,default=0) def __str__(self) -> str: return self.chatID When I delete all the fields and just set user table like this from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass I get no errors -
Cannot connect to Django app's PostgreSQL database
I am trying to use this app from Github https://github.com/realsuayip/django-sozluk it is a PostgreSQL & Django app that available on port 8000. I installed it and when I open locahost:8000 it successfully opens. But I can't connect the database via DBEAVER or PSQL. connection infos of the App: /conf/django.env DEBUG=0 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 192.168.2.253 CSRF_TRUSTED_ORIGINS=http://127.0.0.1:8000 DJANGO_SETTINGS_MODULE=djdict.settings_prod SQL_ENGINE=django.db.backends.postgresql SQL_PORT=5432 DATABASE=postgres SQL_HOST=db SQL_DATABASE=db_dictionary SQL_USER=db_dictionary_user SQL_PASSWORD=db_dictionary_password EMAIL_HOST=eh EMAIL_PORT=587 EMAIL_HOST_USER=eh_usr EMAIL_HOST_PASSWORD=pw I wrote this command to see which ports are listening: sudo lsof -i -P -n | grep LISTEN and result: systemd-r 665 systemd-resolve 15u IPv4 21662 0t0 TCP 127.0.0.53:53 (LISTEN) systemd-r 665 systemd-resolve 17u IPv4 21664 0t0 TCP 127.0.0.54:53 (LISTEN) cupsd 1435 root 6u IPv6 25882 0t0 TCP [::1]:631 (LISTEN) cupsd 1435 root 7u IPv4 25883 0t0 TCP 127.0.0.1:631 (LISTEN) docker-pr 7811 root 4u IPv4 53897 0t0 TCP *:8000 (LISTEN) docker-pr 7816 root 4u IPv6 53902 0t0 TCP *:8000 (LISTEN) docker-pr 8136 root 4u IPv4 55578 0t0 TCP *:80 (LISTEN) docker-pr 8143 root 4u IPv6 55581 0t0 TCP *:80 (LISTEN) as you see there is no port 5432. however I tried psql command also: psql -U db_dictionary_user result: psql: hata (error): connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: no file or directory Is … -
Can login as superuser but not as normal user
i have made a super user and registering other users. but only able to log in as superuser and when i try to login as normal user its shows "Invalid phone number or password". Can someone help me with this models.py class CustomUserManager(BaseUserManager): def create_user(self, phone_number, email=None, name=None, password=None, **extra_fields): if not phone_number: raise ValueError('The phone number must be set') email = self.normalize_email(email) if email else None user = self.model(phone_number=phone_number, name=name, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone_number, email=None, name=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(phone_number, email, name, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField(unique=True, max_length=20) name = models.CharField(max_length=150, default='') email = models.EmailField(unique=True, blank=True, null=True) is_active = models.BooleanField(default=True) is_superuser=models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) objects = CustomUserManager() USERNAME_FIELD = 'phone_number' EMAIL_FIELD = 'email' def __str__(self): return self.phone_number views.py @api_view(['POST']) def login_api(request): if request.method == 'POST': serializer = LoginSerializer(data=request.data) if serializer.is_valid(): phone_number = serializer.validated_data.get('phone_number') password = serializer.validated_data.get('password') user = authenticate(request, phone_number=phone_number, password=password) if user is not None: if user.is_active: login(request, user) return Response({'message': 'Login successful'}) else: return Response({'error': 'User account is disabled'}, status=status.HTTP_401_UNAUTHORIZED) else: return Response({'error': 'Invalid phone number or password'}, status=status.HTTP_401_UNAUTHORIZED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'error': 'Method not allowed'}, status=status.HTTP_405_METHOD_NOT_ALLOWED) settings.py AUTH_USER_MODEL='detectapp.CustomUser' I made … -
PUT metod make the password field are required and when i put the value in fields its save it as a text in th database with no hash
views.py from .serializers import CreateUser,ShowUser,MeSerializer,ChangePasswordSerializer from rest_framework import viewsets from django.contrib.auth.models import User from rest_framework.decorators import action from rest_framework.response import Response class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() create_serializer_class = CreateUser show_serializer_class = ShowUser # serializer_class = ChangePasswordSerializer def get_serializer_class(self): if self.action in ["list","retrieve"]: return self.show_serializer_class if self.action in ["partial_update","destroy","create","update"]: return self.create_serializer_class return self.serializer_class @action(detail=False,serializer_class=MeSerializer) def me(self, request): self.kwargs["pk"] = request.user.pk return super().retrieve(request) @action(methods=['put'],detail=True,serializer_class=ChangePasswordSerializer ,url_path="change-password") def change_password(self,request,pk=None): super().update(request) return Response({ "stats" : "Password Changed" }) serializers.py from rest_framework import serializers from django.contrib.auth.models import User class CreateUser(serializers.ModelSerializer): password = serializers.CharField(write_only=True) confirm_password = serializers.CharField(write_only=True) class Meta: model = User fields = [ "username", 'first_name', 'last_name', 'email', 'password', 'confirm_password' ] def validate(self, data): password = data.get('password') confirm_password = data.get('confirm_password') if password != confirm_password: raise serializers.ValidationError("The password must match") else: return data def create(self, validated_data): user = User.objects.create( username=validated_data.get('username'), first_name=validated_data.get("first_name"), last_name= validated_data.get("last_name"), email= validated_data.get("email") ) user.set_password(validated_data.get("password")) user.save() return user class ShowUser(serializers.ModelSerializer): class Meta: model = User exclude = [ 'password' ] class MeSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ "id", "username", "first_name", 'last_name', 'email', ] class ChangePasswordSerializer(serializers.ModelSerializer): old_password = serializers.CharField(write_only=True) new_password = serializers.CharField(write_only=True) new_password_confirmation = serializers.CharField(write_only=True) class Meta: model = User fields = [ 'old_password', 'new_password', 'new_password_confirmation' ] def validate_old_password(self, value): user = self.context["request"].user … -
Django create() not applying annotations applied on manager
Imagine the following model, manager and queryset: from django.db import models class BlaQuerySet(models.QuerySet): def annotate_field(self): return self.annotate(bla_field=Value('Bla') class BlaManager(models.Manager): def get_queryset(self): return BlaQuerySet(self.model, using=self._db).annotate_field() class Bla(models.Model): hello = models.CharField(max_length=10) Now that we have the model. Let's create something: bla_instance = Bla.objects.create(hello='something') bla_instance.bla_field returns `AttributeError: 'Bla' object has no attribute 'bla_field' On the other hand, when you filter that item: bla_instance = Bla.objects.get(hello='something') bla_instance.bla_field returns the expected Bla How can I force the create() to use my manager instead of the default one?