Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am not able to implement Manty to One relationship in developing a search in multiple attributes across multiple models. One to Many works
model.py view.py search_form.html search_reslut.html form.py ######################################################### I am doing a search app, that allows users to search books with their properties and authors. So it is " Multiple properties across multiple models". The problem is I can't bring the One-to-Many relationship search. The Many-to-one works. I want to retrieve books written by the one author. When I search book, It shows, the author, isbn, pages. But when I search author, cant get books. -
how to solve the psycopg2 and pillow installation problem on cpanel (
for hours I have been trying to deploy my django project on cpanel of lws, I created a python application and activated the virtual environment but as soon as I try to install the dependencies I receive an error error: subprocess-exited-with-error × Building wheel for Pillow (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [143 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-39 creating build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/BlpImagePlugin.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/ImageFilter.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/SpiderImagePlugin.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/ImageGrab.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/GimpPaletteFile.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/FpxImagePlugin.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/DdsImagePlugin.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/XpmImagePlugin.py -> build/lib.linux-x86_64-cpython-39/PIL running egg_info writing src/Pillow.egg-info/PKG-INFO writing dependency_links to src/Pillow.egg-info/dependency_links.txt writing requirements to src/Pillow.egg-info/requires.txt writing top-level names to src/Pillow.egg-info/top_level.txt reading manifest file 'src/Pillow.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*.c' warning: no files found matching '*.h' warning: no files found matching '*.sh' writing manifest file 'src/Pillow.egg-info/SOURCES.txt' running build_ext building 'PIL._imaging' extension creating build/temp.linux-x86_64-cpython-39/src/Tk declaration -fPIC -DHAVE_LIBJPEG -DHAVE_LIBZ -DHAVE_LIBTIFF-DHAVE_XCB -DPILLOW_VERSION=\"10.0.1\" -I/usr/include/freetype2 -I/usr/include -I/home/uloyxtlb/virtualenv/core/Ulc_loyola_core/3.9/include -I/opt/alt/python39/include/python3.9 -c src/_imaging.c -o build/temp.linux-x86_64-cpython-39/src/_imaging.o error: command '/usr/bin/gcc' failed: Permission denied [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel … -
Two objects are created after registering with Django
After registration, two objects are entered in the database, one with only the user, the other with the user and first and last name. This is because I save twice, but when saved once will fail u = UserProfile(user=user, name=user_name, last_name=last_name) u.save() views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user_name = form.cleaned_data['username'] last_name = form.cleaned_data['last_name'] if UserProfile.objects.filter(user__username=user_name).exists(): messages.error(request, 'This username is already taken. Please choose a different one.') else: user.save() u = UserProfile(user=user, name=user_name, last_name=last_name) u.save() login(request, user) messages.success(request, 'Successful registration') return redirect('home') else: messages.error(request, 'Registration error') else: form = UserRegisterForm() return render(request, 'service/register.html', {'form': form}) models.py class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=150, verbose_name='Name') last_name = models.CharField(max_length=150, verbose_name='Last name') def __str__(self): return f'User: {self.user}' forms.py class UserRegisterForm(UserCreationForm): username = forms.CharField(label='Name', widget=forms.TextInput( attrs={'class': 'form-control', 'autocomplete': 'off'})) last_name = forms.CharField(label='Last name', widget=forms.TextInput( attrs={'class': 'form-control', 'autocomplete': 'off'})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput( attrs={'class': 'form-control'})) password2 = forms.CharField(label='Again password', widget=forms.PasswordInput( attrs={'class': 'form-control'})) class Meta: model = User fields = ('username', 'last_name', 'password1', 'password2') I tried to save with one save, but it saves without a first and last name or an error pops up save() prohibited to prevent data loss due to unsaved related … -
Problem starting Django container in production (Whitenoise?)
I have suddenly started having trouble starting up my website in production after I moved to a new VPS hosting service. I was using Vultr and moved to Digitalocean because response time was way faster when using Ansible (for the same machine configuration). In both cases I was using Ubuntu 23.10 as a host. I also tried to do "compose up" with production.yml in my dev machine and the error is the same, so I guess it has nothing to do with the change of hosting service. Here's an extract of Docker's output: cymentcom-django-1 | PostgreSQL is available cymentcom-django-1 | Post-processing 'vendor/purecounter/purecounter_vanilla.js' failed! cymentcom-django-1 | cymentcom-django-1 | Traceback (most recent call last): cymentcom-django-1 | File "/app/manage.py", line 39, in <module> cymentcom-django-1 | execute_from_command_line(sys.argv) cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line cymentcom-django-1 | utility.execute() cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute cymentcom-django-1 | self.fetch_command(subcommand).run_from_argv(self.argv) cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv cymentcom-django-1 | self.execute(*args, **cmd_options) cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute cymentcom-django-1 | output = self.handle(*args, **options) cymentcom-django-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle cymentcom-django-1 | collected = self.collect() cymentcom-django-1 | ^^^^^^^^^^^^^^ cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 154, in collect cymentcom-django-1 | … -
Wagtail page edit, 'NoneType' object has no attribute 'get_actions'
I got a strange error, when trying to view page in wagtail admin 'NoneType' object has no attribute 'get_actions' at wagtail/admin/views/pages/edit.py in workflow_action_is_valid at line 469 Not sure, how this can happen? And what is the possible solution to fix that? -
django userprofile nested relationship is empty in django REST
Hello I have an UserProfile model in django, and I want to serialize my User model with its UserProfile nested to receive it via ajax in my template but it cames empty. Model UserProfile class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.DO_NOTHING) departamento = models.ForeignKey(Departamento,on_delete=models.PROTECT,related_name="pertenece_a") class Meta: db_table = 'UserProfile' def user_profile(sender, instance, signal, *args, **kwargs): Userprofile, new = UserProfile.objects.get_or_create(user=instance) signals.post_save.connect(user_profile, sender=User) Serializers class ProfileSerializer(serializers.Serializer): class Meta: model = UserProfile fields = ["departamento"] class GestionUsuarioSerializer(serializers.ModelSerializer): profile = ProfileSerializer(many=True,read_only=True) class Meta: model = User fields = ["id","username","email","first_name","last_name","profile"] Result -
Please help django
I want the results from the columns on the left to be in one main column on the right, to be distributed according to categories and subcategories. results from the columns on the left to be in one main column on the right, to be distributed according to categories and subcategories. -
Make inner joins by using Q objects in Django
I'm customizing a model's Admin change list page in my project. This model contains a Many to Many field and I want to allow multi-selection filtering. I've used the Django Admin Multi Select Filter package to do this but I noticed that the default behaviour in Django's __in lookup is to be inclusive and not exclusive. Imagine I have an object A associated with M2M objects 1 and 2 and object B associated with M2M objects 2 and 3. If I make the following query Model.objects.filter(m2m_model__in=[1,2]) I will have both objects A and B being retrieved, since the search will use the following condition: Index Cond: (models_model_m2mfield.model_id = ANY ('{1,2}'::bigint[])) I was able to customize the behaviour of the search by doing the following: for choice in choices: queryset = queryset.filter(**{self.lookup_kwarg: choice}) This generates inner joins and returns the value I'm waiting for (only objects matching every option). INNER JOIN "models_model_m2mfield" ON ("models_m2mmodel"."id" = "models_model_m2mfield"."m2mfield_id") INNER JOIN "models_model_m2mfield" T4 ON ("models_m2mmodel"."id" = T4."m2mfield_id") WHERE ("models_model_m2mfield"."model_id" = 4 AND T4."model_id" = 5) I've tried using Q objects to get the same result, but I couldn't make it work. Is it possible to achieve the same behaviour using the Q class? -
why commands in command line starting with python is not working and giving output "Python"?
When I'm running a command starting with python in Windows PowerShell I always have just output "Python" Example: PS C:\Users\----\Django\jobapp> python -m venv env Python Example 2: PS C:\Users\----\Django\jobapp> python manage.py runserver Python I had a python version 3.9 and then I tried to reinstall python for a new version(3.12), but nothing have changed -
"commands out of sync; you can't run this command now" on first use of cursor
I am using MySQL in Django (Python). The draft version of this code worked and was stable, but it created cursors without closing them, and I just rewrote it to manage the cursor with enter/exit. Now it is unstable. class Cursor: def __init__ (self, db): self.db = db self.cursor = db.DB_connection.cursor () def __enter__ (self): return self def __exit__ (self, ex_type, ex_value, ex_traceback): if ex_value is not None: # log stuff self.cursor.close () self.cursor = None def __del__ (self): if self.cursor is not None: # log stuff self.cursor.close () def one (self, query, args): self.cursor.execute (query, args) return self.cursor.fetchone () class DB: def __init__ (self, my_stuff): self.DB_connection = connect (...) def get (self): return Cursor (self) and in the application: with DB_connection.get() as db: result = db.one ("SELECT ...", ...) Sometimes this works as before, but sometimes randomly it will fail calling db.one() _mysql_connector.MySQLInterfaceError: Commands out of sync; you can't run this command now this exception is seen in Cursor's __exit__ Googling this error tells me that this means an earlier SELECT on that cursor still has un-fetched results. But this is nonsense since with DB_connection.get() as db creates a new cursor. Also sometimes the process simply exists without printing … -
Django Autocomplete Light: ModelSelect2Multiple height not expanding
I have a forms.models.ModelMultipleChoiceField using an autocomplete.ModelSelect2Multiple widget. This is working well, except that when I add many entries and it spans multiple lines, the box does not expand to accommodate them (see image below). Can anyone please suggest the best way to make the box expand? -
Handling formsets in Django
In my django project, I want to use formsets, but I have a problem with handling the POST requests. I defined my formset this way: strategy_settings = formset_factory(StrategySettings) strategy_formset = strategy_settings(request.POST) Then I tried to loop through all of the forms in a formset if the forms are valid: if strategy_formset.is_valid(): for form in strategy_formset: data = form.cleaned_data["data"] But the thing is, although I fill the forms with proper data, the forms are not valid, I checked this by printing statements in the console. No error appears, when I submit the forms, formset just disappears from a page. Here is my full view: def input_view(request): if request.method =="POST": simulation_form = SimulationSettings(request.POST) # Regular form strategy_settings = formset_factory(StrategySettings) # Formset strategy_formset = strategy_settings(request.POST) # Formset if simulation_form.is_valid() and strategy_formset.is_valid(): print("valid") initial_amount = simulation_form.cleaned_data['initial_amount'] number_of_simulations = simulation_form.cleaned_data['number_of_simulations'] number_of_trades = simulation_form.cleaned_data['number_of_trades'] values_from_all_forms = [] for form in strategy_formset: accuracy = form.cleaned_data['accuracy']/100 take_profit = form.cleaned_data['take_profit'] / 100 stop_loss = form.cleaned_data['stop_loss'] / 100 max_dd_list = [] for simulation in range(0, number_of_simulations): trades = (["W"] * int(number_of_trades*accuracy)) + (["L"] * int(number_of_trades * (1-accuracy))) random.shuffle(trades) current_amount = initial_amount current_amount_list = [] profit_list = [] for trade in trades: if trade == "W": current_amount = current_amount + current_amount*take_profit … -
Issue with Database Queries in Authenticated Django API Calls Despite JWT Verification
Each time an authorized API call is made using a bearer token (specifically a simple JWT), a database query is executed to retrieve user details, even though JWT Authentication is supposed to eliminate the need for database validation. Could someone help me understand the reason behind these database queries and suggest a solution to avoid them while still ensuring proper authentication through JWT? Your insights would be greatly appreciated! When making a request to a Django API with a JWT bearer token, an extra database call is initiated to retrieve user details associated with the user ID specified in the token payload. SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 2 LIMIT 21; args=(2,); alias=default . The execution of this database query is unexpected, and I am unsure about the reason for its occurrence. Can anyone assist me in determining the cause of this DB Query? -
"500 Internal Server Error During Sign-Up"
I am getting error when i tried to signup in my django project, error is given below, enter image description here urls.py views.py templates and all the related files and code are provided below, may you please check it and tell me why i am getting this error? urls.py from django.urls import path from . import views app_name = "users" urlpatterns = [ path('', views.AccountView.as_view(), name="account"), path('profile/', views.profile_view, name="profile"), path('sign-up', views.SignUpView.as_view(), name="sign-up"), path('sign-in', views.SignInView.as_view(), name="sign-in"), path('sign-out', views.sign_out, name="sign-out"), ] views.py from django.shortcuts import render, redirect, reverse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.conf import settings from django.http import JsonResponse from django.views.generic.edit import FormView from django.views.generic.base import TemplateView from django.utils.decorators import method_decorator from django_google_api.mixins import( AjaxFormMixin, reCAPTCHAValidation, FormErrors, RedirectParams, ) from .forms import ( UserForm, UserProfileForm, AuthForm, ) result = "Error" message = "There was an error, please try again" class AccountView(TemplateView): ''' Generic FormView with our mixin to display user account page ''' template_name = "users/account.html" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def profile_view(request): ''' function view to allow users to update their profile ''' user = request.user up = user.userprofile form = UserProfileForm(instance = up) if request.is_ajax(): form … -
After Django update to 4.2.6: The requested resource was not found on this server
I have a funny situation: My site tells me Not Found: The requested resource was not found on this server.. In the logs I see nothing. But: I also have a running django-huey worker (multiple actually) and they run just fine. Even funnier: admin section works without problems. -
using django smart_selectors with django_cities_light not working
I am using django cities_light, but what I want is: Region drop down to be depend on Country and city drop down on region. for achieving this I installed smart_selectors to flirter them using ChainedForeignKey and The Strange thing is, it worked for the first time but when I checked it other day it wont wrok anymore. this is the code I am using from smart_selects.db_fields import ChainedForeignKey from cities_light.models import Country, City, Region Class Address(Models.Model): #i tried this before did not work #country = models.ForeignKey('cities_light.Country', #on_delete=models.SET_NULL, null=True, #blank=True) # Country, City and State country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) region = ChainedForeignKey( Region, chained_field="country", chained_model_field="country", show_all=False, auto_choose=True, null=True ) city = ChainedForeignKey( City, chained_field="state", chained_model_field="region", show_all=False, auto_choose=True, null=True ) I am attaching screenshot and they dont get chained somehow I dont know what I am doing wrong I was expeting them to chained and fliter regions and then cities xD -
I Want To Add Creat Super user By Using Custom User Model
enter image description here My Models Here I Use AbstractUser in My Class class CustomMyUserModel(AbstractUser): username = None phone_number = models.CharField(max_length=100, unique=True) email = models.EmailField(unique=True) user_bio = models.CharField(max_length=50) user_profile_image = models.ImageField(upload_to='upload') USERNAME_FIELD = 'phone_number' REQUIRED_FIELD = [] This Is Code Of Migrations.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): def create_user(self, phone_number, password=None, **extra_fields): if not phone_number: raise ValueError('The Phone Number Is required:') extra_fields['email'] = self.normalize_email(extra_fields['email']) user = self.model(phone_number = phone_number, **extra_fields) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) return self.create_user(phone_number, password, **extra_fields) ^C(overrideuser) hamza@hamza-HP-EliteBook-840-G1:~/PycharmProjects/pythonProject2/OverrideUser$ python manage.py createsuperuser Phone number: 030476701645 Email: hamzabiall@gmail.com Password: Password (again): Traceback (most recent call last): File "/home/hamza/PycharmProjects/pythonProject2/OverrideUser/manage.py", line 22, in main() File "/home/hamza/PycharmProjects/pythonProject2/OverrideUser/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/core/management/init.py", line 442, in execute_from_command_line utility.execute() File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/core/management/init.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 88, in execute return super().execute(*args, **options) File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 233, in handle self.UserModel._default_manager.db_manager(database).create_superuser( TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username' -
django error - InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency userauth.0001_initial
hello i get this error when i run the command below: python manage.py migrate what should I do? I comment the 'django.contrib.admin', but I get another error =) : RuntimeError: Model class django.contrib.admin.models.LogEntry doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. what should I do with this issue? -
Django REST API Error: FOREIGN KEY constraint failed
In my django api, am able to successfully create admin users as well as normal users. This is the code for my models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, phone, password=None, **extra_fields): if not phone: raise ValueError('The phone field must be set') user = self.model(phone=phone, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(phone, password, **extra_fields) class Users(AbstractBaseUser, PermissionsMixin): unique_code = models.TextField() fname = models.TextField() lname = models.TextField() email = models.EmailField(unique=True) phone = models.TextField(unique=True) sex = models.TextField() country = models.TextField() date_of_birth = models.TextField() image = models.TextField(default=None, blank=True, null=True) district = models.TextField() subCounty = models.TextField() village = models.TextField() number_of_dependents = models.TextField() family_information = models.TextField() next_of_kin_name = models.TextField() next_of_kin_has_phone_number = models.IntegerField(default=None, blank=True, null=True) next_of_kin_phone_number = models.TextField(default=None, blank=True, null=True) pwd_type = models.TextField(default=None, blank=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) REQUIRED_FIELDS = ['unique_code', 'fname', 'lname', 'phone'] USERNAME_FIELD = 'email' objects = CustomUserManager() def __str__(self): return self.phone Am using token authentication and this is my code for auth from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.response import … -
Errno 13 Permission denied when uploading files into folder through a Django web app using bitnami and apache
Here's what my permissions look like for inside the apache folder: And for the folder I'm trying to upload the files to: Does my media/images folder need to have the same owner/group as the apache folder for this to work? I'm using the django admin platform to upload files to that folder. -
When I click the button in my form, I expect it to execute this post function in my view, but it doesn't
The form <form action="{% url 'add-coupon' %}" method="post"> {% csrf_token %} <div class="coupon"> <input id="coupon_code" class="input-text" name="coupon" value="" placeholder="ENTER COUPON CODE" type="text"> </div> <button class="tp-btn-h1" type="submit">Apply coupon</button> </form> My Url from django.urls import path from .views import AddToCart, CartItems, AddCoupon urlpatterns = [ path('add-coupon/', AddCoupon.as_view(), name='add-coupon'), ] The Views from django.shortcuts import get_object_or_404, redirect from django.views import generic from django.utils import timezone from datetime import datetime from django.contrib import messages from .carts import Cart from .models import Coupon from app.models import Product class AddCoupon(generic.View): print("I should see two statements below this") def post(self, *args, **kwargs): print("Button Works") print(messages.success(self.request, "Your coupon has been included successfully") When I click the button, I should get all the 3 statements but I only get ( I should see two statements below this ), So the function is not executing and I don't know why. Would appreciate any help. -
What are the primary advantages of using Django's built-in ORM
What are the primary advantages of using Django's built-in ORM (Object-Relational Mapping) compared to writing raw SQL queries in Django web development? Haven't tried anything yet, just asking question. Thanks in advance. -
Import Error: cannot import name 'encodings' from 'psycopg2._psycopg'
I ran into this problem and Google doesn't give an answer... I have: Linux 3.10.0-1160.95.1.el7.x86_64; Django 3.2.6; Python 3.9; psycopg2 2.9.9; nginx/1.14.0; Log: [Wed Nov 15 11:20:13.904181 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] mod_wsgi (pid=63994): Failed to exec Python script file '/home/users/###/###/domains/###/django.wsgi'. [Wed Nov 15 11:20:13.904240 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] mod_wsgi (pid=63994): Exception occurred processing WSGI script '/home/users/###/###/domains/###/django.wsgi'. [Wed Nov 15 11:20:13.906201 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] Traceback (most recent call last): [Wed Nov 15 11:20:13.906243 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] File "/home/users/###/###/###/env/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 25, in <module> [Wed Nov 15 11:20:13.906250 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] import psycopg2 as Database [Wed Nov 15 11:20:13.906261 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] File "/home/users/###/###/###/env/lib/python3.9/site-packages/psycopg2/__init__.py", line 67, in <module> [Wed Nov 15 11:20:13.906267 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] from psycopg2 import extensions as _ext [Wed Nov 15 11:20:13.906276 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] File "/home/users/###/###/###/env/lib/python3.9/site-packages/psycopg2/extensions.py", line 50, in <module> [Wed Nov 15 11:20:13.906281 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] from psycopg2._psycopg import ( # noqa [Wed Nov 15 11:20:13.906301 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] ImportError: cannot import name 'encodings' from 'psycopg2._psycopg' (/home/users/###/###/###/env/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-x86_64-linux-gnu.so) [Wed Nov 15 11:20:13.906315 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] [Wed Nov 15 … -
If the function lacks a print statement, it fails to operate correctly
I am using django channels in which I am creating a function that can get data from the database but the problem is when I am using the function with the decorator (@database_sync_to_async) it does not work until I put a print statement with the output result of query in it. other wise it give the error (You cannot call this from an async context - use a thread or sync_to_async.). I am trying to send message to the user. The code is mentioned in which I have highlited the funstion which does not work without print statement. @database_sync_to_async def get_driver_data(self,data): driver = DriverAdditional.objects.get(user_id=data) return driver @database_sync_to_async def **get_driver_location**(self,data): location = CabLocation.objects.get(driver_id=data) **#print(location)** return location async def send_amount(self, text_data): print("send amount") user = self.scope['user'].id print("user",user) driver = await self.get_driver_data(user) message = json.loads(text_data) data = message.get('data') try: location = await self.get_driver_location(driver) print(location) except Exception as e: print(f'error is {e}') # print(data['rider']) await self.channel_layer.group_send( group=data['rider'], message = { 'type': 'echo.message', 'message_type': 'send_amount', 'data': f"{driver} {data['amount']}", } ) The error without print statement is: Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 218, in get rel_obj … -
UWSGI Why would there be unattended requests . According to the log
I've got the below in my uwsgi log running with Django and Nginx. The req: -/- field i believe is referring to the request count and the total number of requests respectively. They're both incrementing gradually but the gap is not being closed. I'm not sure what this means for my application as it looks like there're unattended requests that will never be attended. I've checked around but still didn't get the right answer to the situation. [pid: 305785|app: 0|req: 418/1873] 99.7.107.127 () {38 vars in 554 bytes} [Tue Nov 14 23:30:43 2023] GET /api/machines/endpoint/ => generated 385 bytes in 10 msecs (HTTP/1.1 200) 7 headers in 215 bytes (1 switches on core 0) [pid: 305785|app: 0|req: 419/1874] 99.7.107.127 () {38 vars in 562 bytes} [Tue Nov 14 23:30:43 2023] GET /api/machines/endpoint/ => generated 545 bytes in 40 msecs (HTTP/1.1 200) 7 headers in 215 bytes (1 switches on core 0) I'm expecting there'd be so little gap between the request count and the total number requests. I should also mention that this persists even after restarting the service itself. Perhaps some explanation on this behavior would clear my confusions .