Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I resolve the "no-name-in-module" error in Pylint when using Parler's TranslatedFields?
I have the following class in models.py: class Family(models.Model): code = models.CharField(max_length=50, unique=True) translations = TranslatedFields(name=models.CharField(max_length=255)) When I try to import the "FamilyTranslation" model for various purposes from .models import FamilyTranslation Pylint detects the "E0611:no-name-in-module" error. The table with the translations is created, the code works, but Pylint doesn't recognize the model. I have tried some pylint plugins to make Parler's automatic models recognized, but it doesn't work. I have already checked the __init__.py file, and it is correct. If possible, I would prefer not to explicitly declare all the "Translation" models from Parler. -
How to fix a bug after stripe paymant
I have a website with games. I also included stripe as a payment method, and everything works pretty fine! But, after you finish your payment, you get redirected to your home page, and objects that are looped just DISSAPPEAR! They appear again once you travel from one page to another. Views.py def button_to_buy(request): stripe.api_key = settings.STRIPE_SECRET_KEY checkout_session = stripe.checkout.Session.create( payment_method_types=[ 'card', ], line_items=[ { 'price': '', 'quantity': 1, }, ], mode='payment', success_url=request.build_absolute_uri(reverse('success')) ) return redirect(checkout_session.url, code=303) def success_url(request): user = request.user.pk profile = Profile.objects.get(user_id=user) profile.subscription = True profile.save() messages.success(request, 'Оплата прошла успешно') return render(request, 'store/index.html') Urls.py path('checkout/', button_to_buy, name='checkout'), path('success/', success_url, name='success'), Profile.html <div class="justify-content-center py-4 px-2"> {% if not profile.subscription %} <form action="{% url 'checkout' %}" method="POST"> {% csrf_token %} <button class="btn text-light bg-danger mt-4">Buy subscription</button> </form> {% else %} <button class="btn text-light bg-success mt-4">Already paid</button> {% endif %} -
How to speed up celery task which add info into DB
I'm using Django with Celery and PostgreSQL I wrote a celery task which takes json from 3rd party api with more than 10k lines and write them into my database but it takes kinda slow like 30 seconds or more and i'm wondering is there a way to speed up this task? @app.task def create_presence_info(): url = 'http://3rd_party_api.com/api' enter code here response = requests.get(url).json() if len(response) <= 0: print('JSON IS EMPTY') elif len(response) > 0: for item in response: obj_json = json.dumps(item) info_parsed = PresenceInfoListSerializer.parse_raw(obj_json) for counter_list in info_parsed.ListOfCounterparty: presence_list_model = check_presence_list(counter_list) object_list_model = check_object(info_parsed.ObjectGUID) set_of_presence_model = set_of_presence_guid(PresenceListInfo, counter_list) if presence_list_model is None or presence_list_model.GUID not in set_of_presence_model: presence_info = PresenceListInfo.objects.create(GUID=counter_list.DocumentGUID, object_presence=object_list_model) set_of_presence_model.add(presence_info.GUID) deleted = False for info in counter_list.Information: counter_party_model = check_counter_party(info.CounterpartyGUID) if not deleted: PresenceDetailInfo.objects.filter(presence_info=presence_list_model).delete() deleted = True details = PresenceDetailInfo.objects.create(presence_info=presence_list_model, counter_presence=counter_party_model, work_date=counter_list.Date, amount_of_workers=info.Number) for section in info.SectionsGUID: sections = None try: sections = CleanSections.objects.get(GUID=section) except CleanSections.DoesNotExist as sections_error: logger.error(f'{sections_error} update_or_create_presence_info') PresenceSectionList.objects.create(presence_detail=details, presence_sections=sections) ``` -
sqlAlchemy jsonb in Django form
I have a PostgreSQL database and use sqlAlchemy to access the data. In one of the tables, I have a JSONb column. When I load a sqlAlchemy object (an entry from the DB) containing a not empty JSON entry sqlAlchemy will directly transfer it to a Python dict. On default, for Python dicts single quotes are used; therefore, even though JSON uses double quotes, the dict is with single quotes. I then show the JSON in a Django form field so that a user might update the JSON and/or other parameters. When I get the form back with the content of the JSON field as an str, I want to validate that the user sends a valid JSON, so I execute json.loads(json_form_field_content) to verify it. This will raise an error if single quotes are in the JSON string. This is especially bad as this will even happen if the user has not changed the JSON. I googled hard and didn't find a fitting solution for my problem, so I thought hard and came up with an in my option poor solution. I use the following code to transfer the dict to a string where I explicitly set double quotes for … -
AttributeError at /order: module 'groceries_app.views' has no attribute 'usrnme'
I've created two apps in my django project called groceries_app and products_app. When I try to submit a shopping list in my browser, I get this attribute error: module 'groceries_app.views' has no attribute 'usrnme', even though I defined 'usrnme' in my views.py file in groceries_app. How do I fix this so that my order will be confirmed? groceries_app/views.py from django.contrib import messages from django.contrib.auth.mixins import UserPassesTestMixin from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .forms import RegisterForm from .models import RegisteredUser def app_homepage(request): try: if usrnme: userdetails = {'username': usrnme} return render(request, "loggedin.html", userdetails) except NameError: return render(request, 'homepage.html') def about_us(request): try: if usrnme: return render(request, "aboutUs.html") except NameError: return render(request, 'aboutUs.html') def services(request): try: if usrnme: return render(request, "services.html") except NameError: return render(request, 'services.html') def contact_us(request): try: if usrnme: return render(request, "contactUs.html") except NameError: return render(request, 'contactUs.html') def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Account created successfully") return redirect("signin") else: form = RegisterForm() user_info = {'form': form} return render(request, "register.html", user_info) def signin(request): global usrnme if request.method == 'POST': usrnme = request.POST['username'] psswrd = request.POST['pswd'] try: user = RegisteredUser.objects.get(name=usrnme) … -
UnicodeEncodeError at / 'ascii' codec can't encode character '\x92' in position 65: ordinal not in range(128)
This error occurs when django tries to use the send_email function: UnicodeEncodeError at / 'ascii' codec can't encode character '\x92' in position 65: ordinal not in range(128) Request Method: GET Request URL: http://127.0.0.1:8002/ Django Version: 4.2.2 Exception Type: UnicodeEncodeError Exception Value: 'ascii' codec can't encode character '\x92' in position 65: ordinal not in range(128) Exception Location: /usr/lib/python3.11/smtplib.py, line 641, in auth in views.py: from django.core.mail import send_mail EmailMessage def contactView(request): email = EmailMessage( 'encoded_subject', 'Body', 'obidjonova07@mail.ru', ['inspiring.sunset07@gmail.com'], ) email.send() return render(request, "parts/base.html", {'birth_date': age}) I tried using encode function: encoded_subject = subject.encode('utf-8') and passed it to the function, tried to use the function for the message as well, but it did not help -
How to filter multiple tags with django-taggit in admin view?
I'm reading through the documentation for any example, alas without success. Can anybody point me to an example about filtering for e.g. "green" and "blue" in django admin view? -
Use IntegrityError exception (in Django) to check if username is taken?
I wanted to create a signup form in Django and throw an error if the username already exists. I have seen people have used User.DoesNotExist() method to check that, but can you use IntegrityError exception as follows for that purpose? I have read the definition of IntegrityError but honestly do not quite understand this: This exception is raised when the relational integrity of the data is affected. def signup(request): if request.method == 'GET': return render(request, 'signup.html', {'form': UserCreationForm}) else: if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return redirect('home') except IntegrityError: return render(request, 'signup.html', {'form': UserCreationForm, 'error': 'Username already exists'}) else: return render(request, 'signup.html', {'form': UserCreationForm, 'error': 'Passwords do not match'}) I have seen this code in a Django project. I would appreciate your feedback. -
Django FileField - how to save files to different directories
I have two similar forms for upload files, but I want to save files in different directories depending on the form. Let me explain, for example: if User uploaded file from Form_1 -> file should be save in media/folder_file_1/file.csv if User uploaded file from Form_2 -> file should be save in media/folder_file_2/file.csv Regarding models.py, forms.py, views.py, urls.py I just used examples from Django docs. index.html: <!DOCTYPE html> {% load static %} <body> <div class="page_secondblock secondblock"> <div class="secondblock__container _container"> <h1 class="secondblock__title"> The file you want to update: </h1> <h2 class="secondblock__title"> The file from which you want to get information: </h2> </div> </div> <div class="page_thirdblock thirdblock"> <div class="thirdblock__container _container"> <form method="POST" enctype="multipart/form-data" class="upload1" id="upload_container"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> <form method="POST" enctype="multipart/form-data" class="upload2" id="upload_container"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> </div> </div> </body> models.py: from django.db import models class UploadFile(models.Model): file = models.FileField(upload_to='working/') forms.py: from django import forms from .models import UploadFile class UploadFileForm(forms.ModelForm): class Meta: model = UploadFile fields = ['file'] views.py: from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import UploadFileForm def index(request): return render(request, "index.html") def tools(request): return render(request, "index.html") def login(request): return render(request, "index.html") def upload_file(request): if request.method == 'POST': … -
How to configure SSL certificate inside my docker container?
I have a django application that running inside a docker container. However, while the application works perfectly fine inside my local PC when running inside the container it is unable to make any requests such as calling certain APIs or even pip install. All of these actions will throw an error like [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992). Only way I got pip install working is to do RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host=files.pythonhosted.org --no-cache-dir -r requirements.txt Solutions tried: Copying my local rootCA.pem file to /usr/local/share/ca-certificates/ in the container RUN update-ca-certification Tried different python providers (alpine, buster, slim-buster) There are many more I couldn't remember I don't want to just turn verify off as it is bad practice so I'm trying to keep verification on. I have included my Dockerfile below. Dockerfile: FROM python:3.11.2-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /app RUN apt-get update && apt-get install -y ca-certificates COPY certs/rootCA.pem /usr/local/share/ca-certificates/ RUN update-ca-certificates COPY requirements.txt requirements.txt RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host=files.pythonhosted.org --no-cache-dir -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] -
GET request to ListAPIView doesn't recognize query parameter in Django Rest Framework test case
I am encountering an issue with my Django Rest Framework test case where a GET request to a ListAPIView doesn't seem to recognize a query parameter. The same request works correctly when sent through Postman, but fails when executed within the test case. Here's an overview of the problem: I have a ListAPIView that represents a collection of model instances. The view works fine when tested manually through Postman, and it expects a query parameter called 'project' to filter the collection based on a specific project. However, when I try to send a GET request to the same ListAPIView within my test case, the query parameter 'project' is not recognized, resulting in an error response indicating that the project field is required. Here's a simplified version of the relevant code in my test case: class ShiftListTests(APITestCase): def setUp(self): self.user = User.objects.create_user(username='testuser', password='testpassword') self.client.force_authenticate(user=self.user) self.project = Project.objects.create(owner=self.user, task='Test Task', technical_requirement='Test Requirement', start='2023-05-01', hourly_rate=10.0) self.shift1 = Shift.objects.create(project=self.project, start_time=timezone.make_aware(timezone.datetime(2023, 5, 1, 9, 0, 0)), end_time=timezone.make_aware(timezone.datetime(2023, 5, 1, 17, 0, 0))) self.shift2 = Shift.objects.create(project=self.project, start_time=timezone.make_aware(timezone.datetime(2023, 5, 2, 9, 0, 0)), end_time=timezone.make_aware(timezone.datetime(2023, 5, 2, 17, 0, 0))) def test_get_shift_list(self): url = reverse('shift list') payload = {'project': self.project.id} response = self.client.get(url, data=payload, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) # … -
Django admin upload Image not serving in Html page
i am creating page which serves django admin upload images in page.. ---- this is my file structure in AWS EC2: enter image description here ------ this is what i got when try to find URL of image enter image description here --- This is collectstatic output: enter image description here i think -- i am not able to find the mistake i have done this is the output of the page: the images are not loading into AWS ec2 webpage Please help me out about this issue. as i mentioned above.. i tried max suggestions in stack-overflow and other references too.. i am expecting to serve images in html page which are in the path and not in the html page. ---- this is the inspect element screenshot of page. enter image description here ---- this is database image location : enter image description here please help. -
独自ドメインをEC2インスタンスのpublic IPに紐付けたが、そのドメインにブラウザからアクセスできない
実現したいこと: EC2インスタンスのpublic IPアドレスに紐づけた独自ドメイン(= example.com)にアクセスし、GunicornでサーブされているDjangoアプリからの応答を、Nginx as a reverse proxyを通じて、ブラウザに表示したいです。 問題点: public IPアドレスにアクセスすると、Djangoアプリからの応答を確認できます。 example.comにアクセスすると、「このサイトにアクセスできません」となります。 以上より、ドメインの紐付けに失敗していると予測するも、「example.com/admin」にはアクセスできるため、紐付け自体には問題がなさそうです。 やってきたこと: 1, Route53にて独自ドメインとEC2インスタンスのpublic IPを、Aレコード及びネームサーバーの設定を通じて、紐づけました。 2, HTTPアクセスを受けられるように、セキュリティグループでポート80を開け、ソースを0.0.0.0と設定した。 3, EC2インスタンス内で、Gunicorn/Django、Nginx、PostgreSQLのコンテナたちを、以下のdocker-compose.yml & default.confを用いて作成しました。 version: "3.9" services: web: # コンテナ名をwebに指定 container_name: web # NginxのDockerfileをビルドする build: # ビルドコンテキストはカレントディレクトリ context: . dockerfile: ./nginx/Dockerfile # ボリュームを指定 # ローカルの/staticをコンテナの/staticにマウントする volumes: - ./static:/static - ./nginx/conf.d:/etc/nginx/conf.d - ./etc/letsencrypt:/etc/letsencrypt - ./var/www/html:/var/www/html ports: - "80:80" depends_on: - api certbot: # 後のHTTPS化に使います image: certbot/certbot:v1.7.0 volumes: - /etc/letsencrypt:/etc/letsencrypt - /var/www/html:/var/www/html command: ["--version"] api: build: ./api command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 environment: - OPENAI_API_KEY=${OPENAI_API_KEY} - SECRET_KEY=${SECRET_KEY} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - DB_HOST=${DB_HOST} - DB_PORT=${DB_PORT} volumes: - ./api:/app ports: - "8000" depends_on: - db db: image: postgres:13 environment: POSTGRES_DB: ${DB_NAME} POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASS} volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: upstream django { # サーバにDjangoのコンテナ名を指定。今回はapp # ポートはDjangoのコンテナの8000番ポート server api:8000; } server { # HTTPの80番ポートを指定 listen 80; server_name example.com; # プロキシ設定 # 実際はNginxのコンテナにアクセスしてるのをDjangoにアクセスしてるかのようにみせる location / { proxy_pass http://django; } } どうかアドバイス宜しくお願いいたします! -
object has no attribute 'META' when filtering Query in Django
It's my first time encountered this problem, the error says 'TevList' object has no attribute 'META' I tried putting .first() after filter but the error retains views.py @csrf_exempt def tevemployee(request): tev_id = request.POST.get('tev_id') qs_list = TevList.objects.filter(id=tev_id).first() return JsonResponse({'data': list(qs_list)}) ajax $('.item-details').click(function (event) { let id = $(this).attr("id"); $.ajax({ type: "POST", url: "{% url 'tev-employee' %}", data:{ tev_id : id } }).done(function(data){ }); models.py class TevList(models.Model): employee_name = models.CharField(max_length=128,blank=True, null=True) original_amount = models.FloatField(null=True, blank=True, default=0) status = models.CharField(default="On-going",max_length=128,blank=True, null=True) incoming_remarks = models.CharField(max_length=255, blank=True, null=True) correctness_remarks = models.CharField(max_length=255, blank=True, null=True) date_in = models.DateTimeField(default=datetime.now,blank=True, null=True) date_out = models.DateTimeField(blank=True, null=True) deleted_at = models.DateTimeField(blank=True, null=True) user_id = models.BigIntegerField(blank=True, null=True) class Meta: managed = True db_table = 'tev_list' -
DJANGO: database dependent combobox remains empty. No items appear
I would like to create a combobox and display data from a database table (names of cities) inside it. The page is app1/home.html. I created the files and migrated the database, but the combobox remains empty. I don't know what I did wrong. I'm new to Django, sorry. I have read many tutorials and questions, but I have not solved. How can I create the combobox and display City_Name in it? models.py from django.db import models class Select_City(models.Model): Select_City= models.IntegerField() def __str__(self): return self.Select_City forms.py from .models import Select_City class TestForm(forms.Form): some_input = forms.CharField(max_length=100) city = forms.ModelChoiceField(queryset=Select_City.objects.all()) class Meta: model = Select_City fields = ('City_Name',) views.py def combobox(request): query_results = Select_City.objects.all() if request.method =="POST": form = TestForm(request.POST) context = {'form': form, 'query_results': query_results} return render(request, 'app1/home.html', context) home.html <form method="post" novalidate> {% csrf_token %} <select id="sel_city" name="cities"> <option value="{{ query_results }}">Select</option> {% for item in query_results %} {% endfor %} </select> </form> -
AP Scheduler skips logging of the job execution - How to resolve?
This is how my scheduler configuration and the registered job looks like ` from django.core.management import call_command def start(): from django_apscheduler.jobstores import register_events, DjangoJobStore, register_job from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), 'djangojobstore') print("Idhar aagya mein") try: @register_job(scheduler, 'interval', minutes=1, name="daily_bakcup", misfire_grace_time = 300, max_instances=3) def backup(): call_command('DB_Backup') except Exception as e: print("Error" , e) register_events(scheduler) scheduler.start() ` Here is the explanation on what the job does and where the error come. So, the job is to take backup of the database using Django's python manage.py dumpdata > file.json command, then upload it to Azure container. The thing I wanted to achieve is to perform the job and log the execution in the Job Execution tables (which is expected to happen implicitly when jobstores are used.) in the Database. Hence, it performs the job but doesn't log the execution in the tables, instead i get the below in the console. Job 'user_accounts.backup.backup' no longer exists! Skipping logging of job execution... Any suggestions and solution would help a lot. Thanks! -
There is an error of page not found ;Request method get method
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/signup Raised by: django.contrib.admin.sites.catch_all_view You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I tried on stackoverflow but it gives me the post method to solve the error -
In Django, after creating models.py, how to create a combobox and populate me with database?
In the app1/home.html page, i would like to create a combobox and display data from a database table (city names) inside. A simple combobox with city names. I created the models.py file and migrated the database. How can I create the combobox and display City_Name in it? Thank you models.py from django.db import models class Select_City(models.Model): City_Name= models.IntegerField() def __str__(self): return self.City_Name -
Azure App Service web app: Django + Microsoft login redirect HTTPS issue
Azure App registration web redirect URL (it's HTTPS) as below: Using Azure App Service deployed the Django web app successfully: the above deploying result shows http://, but in Azure web app web it shows https://, also could open the web app using https successfully with valid as below: But when the web app redirected to Microsoft site to login, it uses http:// again which doesn't match the https:// configured in App registration: The MS authentication and redirection is handled by package ms_identity_web, code provided from https://github.com/Azure-Samples/ms-identity-python-django-tutorial/tree/main/1-Authentication/sign-in In development environment there is no issue since I use http://localhost:8000/auth/redirect as web redirect url in App registration. My issue could be the same as this one: link, but it covered the URL details so not sure if it was the same http/https mismatching issue. -
postgresql ERROR: duplicate key value violates unique constraint "django_apscheduler_djangojob_pkey"
(https://i.stack.imgur.com/rPvSI.png) when i build django(+django-apscheduler),postgresql,nginx i got error above this. django=4.2.2 python=3.8.10 postgresql=14.5 django-apscheduler=0.6.2 apscheduler=3.10.1 so i try to solve this error, search on google : modify postgres db : because "django_apscheduler_djangojob_id_seq" doesnt exist, so i created table("django_apscheduler_djangojobexecution_id_seq" is exist) CREATE SEQUENCE django_apscheduler_djangojob_id_seq INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 1 CACHE 1 NO CYCLE; CREATE SEQUENCE SELECT setval('django_apscheduler_djangojob_id_seq',(SELECT MAX(id) FROM django_apscheduler_djangojob)); But it doenst work... comment out "Djangojobstore" : it works but i want to use djangojobstore in my operator.py : logger = logging.getLogger(__name__) def delete_dormant_user(): dormant_user = User.objects.filter(is_active=False) dormant_user.delete() @util.close_old_connections def delete_old_job_executions(max_age=604_800): DjangoJobExecution.objects.delete_old_job_executions(max_age) class Command(BaseCommand): help = "Runs delete_dormant_user." def start(self, *args, **options): scheduler = BackgroundScheduler( timezone=settings.TIME_ZONE ) #scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( delete_dormant_user, trigger=CronTrigger(minute="*/3"), id="delete_dormant_user", max_instances=1, replace_existing=True, ) logger.info("Added job 'delete_dormant_user'.") scheduler.add_job( update_ingredient_links, trigger=CronTrigger(day_of_week="0-6", hour="04", minute="00"), id="update_ingredient_links", max_instances=1, replace_existing=True, ) logger.info("Added job 'update_ingredient_links'.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger( day_of_week="mon", hour="05", minute="00" ), id="delete_old_job_executions", max_instances=1, replace_existing=True, ) logger.info("Added weekly job: 'delete_old_job_executions'.") try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!") in my apps.py : class UsersConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "users" def ready(self): if settings.SCHEDULER_DEFAULT: from .operator import Command Command.start(self) please give me some wisdoms!! ps. since Mar 6 2022, django-apscheduler hasn't been updated... it can … -
Not recognizing components when using django-split-settings
Never used this app; first time using it. I have a problem with recognizing the components from one of my settings files. Here is my directory structure: survey/settings/ ├── components │ ├── common.py │ ├── directory_manipulation.py │ ├── django_allauth.py │ ├── django_crispy_forms.py │ ├── django_tailwind.py │ └── __init__.py ├── enviroments │ └── __init__.py ├── __init__.py └── __pycache__ └── __init__.cpython-311.pyc Here is my settings/__init__.py file: """ This is a django-split-settings main file. For more information read this: https://github.com/sobolevn/django-split-settings Default environment is `developement`. To change settings file: `DJANGO_ENV=production python manage.py runserver` """ from split_settings.tools import optional, include base_settings = [ # You can even use glob: 'components/*.py' ] # Include settings: include(*base_settings) Here is my settings/django_allauth.py AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] from components.base import INSTALLED_APPS INSTALLED_APPS += ( 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.sites', ) SITE_ID = 1 Here is my settings/common.py """ Django settings for survey project. Generated by 'django-admin startproject' using Django 4.1.9. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path # Build … -
Django : DoesNotExist Error raised in post_signal handler
Trying to delete a Task instance with its subtasks, I encounter DoesNotExist: Task matching query does not exist. The following is the error message: Traceback (most recent call last): File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/related_descriptors.py", line 218, in __get__ rel_obj = self.field.get_cached_value(instance) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^ KeyError: 'supertask' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/crackers/views.py", line 73, in delete print(task.delete()) ^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/base.py", line 1132, in delete return collector.delete() ^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/deletion.py", line 512, in delete signals.post_delete.send( File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/dispatch/dispatcher.py", line 176, in send return [ ^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/dispatch/dispatcher.py", line 177, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/crackers/signals.py", line 10, in reassess_achievement if instance.supertask is not None and instance.supertask.completed == False: ^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/related_descriptors.py", line 236, in __get__ rel_obj = self.get_object(instance) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/related_descriptors.py", line 199, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/query.py", line 637, in get raise self.model.DoesNotExist( crackers.models.Task.DoesNotExist: Task matching query does not exist. So far, I have figured out that the error is related to signal handler, since the same error does not … -
django channels app is blocking when handle many requests
i have a DRF project, using django channels, i have a endpoint that handles thousands requests for each 5seconds, sometimes this endpoint is blocking my app, what would be the best way to handle it? some posts adivises to use raise StopComsumer() in the disconect method, but not resolve this is my consumer class ChargerSessionConsumer(AsyncJsonWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.client_id = None self.group_name = None async def connect(self): self.group_name = 'room' self.client_id = self.scope["url_route"]["kwargs"]["client_id"] await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.channel_layer.group_add( self.client_id, self.channel_name ) await self.accept() async def websocket_disconnect(self, message): await self.channel_layer.group_discard( self.group_name, self.channel_name ) await self.channel_layer.group_discard( self.client_id, self.channel_name ) raise StopConsumer() -
Add Django super user token in http request
I use Django (as backend and frontend) for a website. I want to create http request with the condition (of use) to be Django super user. But I don't know how to add in the headers the token (or the proof that the user that uses the request is a super user). I tried this with the csrf token : First I use the {% csrf_token %} in the template. <form action="#" id="admin-add-event" method="POST"> {% csrf_token %} ... <button type="submit" id="admin-submit">Add event</button> </form> const url = `${window.BASE_URL}events/`; const form = document.getElementById('admin-add-event'); const data = { ... } let xhr = new XMLHttpRequest(); xhr.open('POST', url , true); xhr.setRequestHeader('X-CSRFToken', form.elements.csrfmiddlewaretoken.value); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onload = function () { ... } xhr.send(JSON.stringify(data)); And in the Django view of the endpoint : @api_view(['GET', 'POST']) def all_events(request): if request.method == 'POST': if not request.user.is_superuser: return Response(status=status.HTTP_401_UNAUTHORIZED) # etc ... But the check of super user fails always I precise that I don't want to implemente a user system. I want to use the system of super user of Django. Thanks in advance ! -
How to use Django ImageField to upload to Google Cloud Storage instead of local
I want to use Django's ImageField on a model so people can upload a logo. I found the ImageField however reading from the docs it says Django stores files locally, using the MEDIAROOT***andMEDIAURL** settings.py I'm wondering how I can change the *upload_to= behavior to upload to a gcp bucket instead? If it's possible when I call .save what is saved to the database, the gcp bucket url? From reading the docs it doesn't say one way or the other if this is possible or if all images should be stored locally where the service is being ran. I have thought of saving the binary images directly to the db but that seems inefficient.