Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google social login with Django + allauth + dj_rest_auth + Expo fails with "Error retrieving access token"
We are using Django with a combination of allauth and dj_rest_auth as backend and Expo for building mobile frontend. We are currently facing an issue after logging in with Google Social Login. After setting up the google console for IOS and adding the corresponding provider in django, we can retrieve the credentials from google such as access_token, id_token and code. We have an endpoint in our backend where we should send the code property. This endpoint calls the view that inherits from SocialLoginView (from dj_rest_auth). When we are calling this endpoint with the corresponding code we are facing an issue that tells us: allauth.socialaccount.providers.oauth2.client.OAuth2Error: Error retrieving access token: '{ "error": "invalid_request", "error_description": "You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy for keeping apps secure. You can let the app developer know that this app doesn't comply with one or more Google validation rules."}' Traceback (most recent call last): File "/Users/.../backend/venv/lib/python3.10/site-packages/allauth/socialaccount/providers/oauth2/client.py", line 93, in get_access_token raise OAuth2Error("Error retrieving access token: %s" % resp.content) After some researches we saw that apparently the issue could come from a bad redirect_uri. Since there is no way to set redirect URI in the google cloud console (in … -
Django PWA serviceworker.js code is showing on home page
When I go to home page of my website, I'm met with code of my serviceworker.js which looks like this: var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '/base_layout' ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('/base_layout')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); This is a code from this tutorial. After every "hard refresh" (CTRL + F5 or CTRL + R) it shows my regular home page and the link doesn't change at all. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PWA_SERVICE_WORKER_PATH = os.path.join(BASE_DIR, 'static/scripts', 'serviceworker.js') ... PWA_APP_NAME = 'Timetable Ease' PWA_APP_DESCRIPTION = "Timetable Ease PWA" PWA_APP_THEME_COLOR = '#3D36FF' PWA_APP_BACKGROUND_COLOR = '#aaaadd' PWA_APP_DISPLAY = 'standalone' PWA_APP_SCOPE = '/' PWA_APP_ORIENTATION = 'any' PWA_APP_START_URL = '/' PWA_APP_STATUS_BAR_COLOR = 'default' PWA_APP_ICONS = [ { 'src': 'static/images/logo.png', 'sizes': '160x160' } ] PWA_APP_ICONS_APPLE = [ { 'src': 'static/images/logo.png', 'sizes': '160x160' } ] PWA_APP_SPLASH_SCREEN = [ { 'src': 'static/images/logo.png', 'media': '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)' } ] PWA_APP_DIR = 'ltr' PWA_APP_LANG = 'en-US' PWA_APP_DEBUG_MODE = False project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ … -
Proper way of creating a video streaming server
I am working with the Django framework and I need to create a video streaming server, this is when one user records a video and we broadcast it to thousands of other users through the server. At one moment there can be many broadcasts at once, which will be on different URLs. I'm not sure that Django is the right tool for this kind of work, so I'm leaning towards the socket library in the Python programming language, as it can use the UDP protocol and I can implement everything asynchronously and connect to the project Django-ORM. Another option is Fast API, it is asynchronous, but if I'm not mistaken it works only with TCP, which is not the best option for streaming. I will have only a few days to implement the project, and it will be necessary to start soon, unfortunately, I will not have time for experiments. Can anybody tell me if I am moving in the right direction? Or should I use other tools for this? -
PyShark+Django : Unable to make async call when pyshark is used in a Django view
I am using pyshark module in a Django view to get the ports breakdown from an uploaded PCAP file. views.py class ProtocolAnalysisView(APIView): parser_classes = (MultiPartParser,) def analyze_pcap(self, pcap_file): res = {} capture = pyshark.FileCapture( pcap_file.temporary_file_path(), keep_packets=True) hl_dict = {} tl_dict = {} try: i = 0 while True: hl = capture[i].highest_layer tl = capture[i].transport_layer if hl not in hl_dict: hl_dict[hl] = 0 if tl not in tl_dict: tl_dict[tl] = 0 hl_dict[hl] += 1 tl_dict[tl] += 1 i += 1 except KeyError: capture.close() res["tcp_packet_counts"] = tl_dict.get("TCP", 0) res["udp_packet_counts"] = tl_dict.get("UDP", 0) res["transport_layer_breakdown"] = [ {"transport_layer_protocol": key, "count": value} for key, value in tl_dict.items() ] res["protocol_breakdown"] = [ {"highest_layer_protocol": key, "count": value} for key, value in hl_dict.items() ] return res def post(self, request, *args, **kwargs): serializer = PcapFileSerializer(data=request.data) if serializer.is_valid(): pcap_file = serializer.validated_data['pcap_file'] res = self.analyze_pcap(pcap_file) return Response({"data": res}, status=200) else: return Response(serializer.errors, status=400) The serializer used here: class PcapFileSerializer(serializers.Serializer): pcap_file = serializers.FileField( allow_empty_file=False, allow_null=False, help_text="Upload a pcap file.") When I POST the a using form-data, Django throws the below exception: Exception Value: There is no current event loop in thread 'Thread-1 (process_request_thread)'. Using library like scapy and dpkt is not an option for me. So I dig deep anf got to … -
django how to use index counter on django template
i try using this put output will be empty i wont to show the pic and date from api calling to django template --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -
Celery in Django: celery beat doesn't work
settings.py: #CELERY CELERY_BROKER_URL = 'redis://localhost:6379' # URL для Redis брокера CELERY_RESULT_BACKEND = 'redis://localhost:6379' # URL для Redis бэкенда результатов # Настройки для Celery Beat (периодические задачи) CELERY_BEAT_SCHEDULE = { 'execute_daily_task': { 'task': 'your_app.tasks.execute_daily_task', # Путь к вашей задаче 'schedule': crontab(minute=47, hour=18), # Запускать в полночь каждый день }, } root init.py: # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) celery.py in root directory: # celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # Установка переменной окружения DJANGO_SETTINGS_MODULE для работы с Django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sites.settings') # Создание экземпляра Celery app = Celery('sites') # Загрузка конфигурации Celery из настроек Django app.config_from_object('django.conf:settings', namespace='CELERY') # Автоматическое обнаружение и регистрация задач в приложениях Django app.autodiscover_tasks() tasks.py in users app: from celery import shared_task from django.core.mail import send_mail from datetime import date from .models import Company @shared_task def execute_daily_task(): print('celery is working') ran beat, worker, django-runserver in 3 powershells: celery -A sites worker --loglevel=info -------------- celery@LAPTOP-2554OM7H v5.3.3 (emerald-rush) --- ***** ----- -- ******* ---- Windows-10-10.0.22621-SP0 2023-09-01 18:45:29 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: … -
request = self.context.get('request') , give me'NoneType' object has no attribute 'data'
I'm trying to exclude certain fields from being displayed in the list view of my serializer. To achieve this, I have overridden the to_representation method. However, when I attempt to access the 'request' object using request = self.context.get('request'), I encountered an error stating "'NoneType' object has no attribute 'data'. this is serializer.py from rest_framework import serializers from todo.models import Task class TodoSerializer(serializers.ModelSerializer): short_content=serializers.ReadOnlyField(source='get_short_content') author = serializers.CharField(source="author.username", read_only=True) class Meta: model = Task fields =['id','title', 'author' ,'details' ,'short_content','isCompleted','created_date','updated_date'] read_only_fields=['author'] def to_representation(self,instance): request=self.context.get('request') rep =super().to_representation(instance) print(request.data) if request.parser_context.get('kwargs').get('pk'): rep.pop('short_content',None) else: rep.pop('details',None) return rep Any insights into why I might be receiving this error and how to resolve it would be greatly appreciated. Thank you! -
Transaction affects time of computation?
Consider: with transaction.atomic(): job = Job.objects.select_for_update().get(id=job_id) texts = pickle.loads(job.job_body) timer = Timer() print("Computing embedding for:", texts, flush=True) job.started = ms_now() result = get_embeddings_raw(texts) # no database communication. job.finished = ms_now() print("Done computing embedding for:", texts, timer.stop(), flush=True) job.result = pickle.dumps(result) job.save() The computation within the transaction does not communicate with the database. Nonetheless, when I do not use concurrency, this computation takes ~70ms, but when there are up to ten simultaneous workers, it takes ~4,000ms. Can transaction cause this slowing down in any way? -
Redirection in Class Based Views Doesn't Completly Work
views.py: class LoveLetterCreateView(LoginRequiredMixin, CreateView): model = LoveLetter fields = '__all__' success_url = reverse_lazy('login') # NOT WORKING class SignUpView(CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') # WORKING template_name = 'love_letters/signup.html' Why it would work in one CreateView but not in the other? I tried: def get_success_url(self): - NOT WORKING. -
I have restarted My Django for Other Project But it's still trying to load Previous project files
I have worked on Django Project where I create applications hello, newyear, and tasks. Now, I have to work on a different Project I got it's file from CMD I opened it in visual studio and then created a virtual environment and installed Django in it, but When I have run the server it's showing this output: in the image enter image description here it's trying to open the previous project files instead this project. However, the ip address given by django was same for both projects. Please help, I am new to programing. thank you very much I am trying to create django server for the project file I download online from a course cs50web So, I can run that project. -
How to execute programs/commands in .net core webapp (like Django's manage.py)
I have been a Django developer for over 5 years now and am looking for creating new projects in .net. I have created a few hobby projects in .net and the experience was quite good. But I have a question, to which I haven't found the answer. To give an example: Django has built in management commands and options to write your own. One of the options is createsuperuser. For example, when you setup your django project, you can call python manage.py createsuperuser and it will create a superuser for you. You can create custom commands, which can be run locally and in production servers. How can I do this in .net if I have a webapp? How can I run commands/programs locally or on production server/kubernetes pod? Is this even possible? I know you can create multiple projects inside the solution beside webapp project. -
Django Parametrize Test
I have a simple model factory: class SubjectFactory(factory.django.DjangoModelFactory): class Meta: model = Subject title = 'Mathematics' slug = 'mathematics' When I want to test the instance creation, my parametrization does not override default title and slug. It remains Mathematics. If I remove the line, I get an AttributeError: AttributeError: type object 'SubjectFactory' has no attribute 'title' Here is the instance test: import pytest from courses.models import Subject @pytest.mark.parametrize( 'title, slug, validity', [ ('Algebra', 'algebra', True), ('', '', False), ], ) def test_subject_instance(db, subject_factory, title, slug, validity): test = subject_factory( title=title, slug=slug ) item = Subject.objects.all().count() assert item == validity How can I run the test with these custom params? -
How to use Django Messages field wise in template like Laravel's error in blade template
In Laravel I have a much finer control to show error related to each form field like we can write below in the blade template below respective fields <input name='username' placeholder='User Name' type='text' /> @error('username') <input name='email' placeholder='Email' type='text' /> @error('email') where within quotes are the form input field name. Now if there is a validation error, you can show error below that input field. And error contents are also out of the box basis the validation check of those fields in PHP Code Whereas in Django, it is more like all errors together in the Django Message Framework. Is there a way, from messages one can get errors by field. At least from the documentation I couldn't figure out. -
A changed object is not reflecting in the database
Consider: jobs = Job.objects.bulk_create(jobs) ids = [job.id for job in jobs] # Wait for results (computed by another process) not_done = set(ids) while not_done: complete_jobs = Job.objects.filter( id__in=not_done, result__isnull=False) for job in complete_jobs: job.complete = ms_now() # the current timestamp in ms job.save() print(f"Removing from not_done: {job.id}", flush=True) not_done.remove(job.id) time.sleep(0.1) When the computation is finished, some jobs still have null in the complete attribute. When I look at the output, the line beginning with "Removing from not_done: appears for these jobs. Somehow, job.save() does not result in the new value of job.complete reflecting in the database. Why could this be happening and how do I fix it? -
nginx django static files 403 forbidden error permission denied
ngnix.conf server_name _; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/megasoft/bots/hisoblovchibot/backend/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } 2023/09/01 10:41:20 [error] 11593#11593: *1 open() "/home/megasoft/bots/hisoblovchibot/backend/static/admin/js/core.js" failed (13: Permission denied), client: 192.168.1.30, server: _, request: "GET /static/admin/js/core.js HTTP/1.1", host: "195.158.26.12:9938" -
Django save() with specified psycopg connection
I have made a class called Database that I use to manage a connection to a Postgres database via psycopg3. This enables me to do things like: db = Database(postgres_connection_data) class_one_instance.insert(insert_data, db) class_two_instance.insert(insert_data, db) db.commit() The exception handling in the insert methods is such that we only get to db.commit() if both inserts have worked, which is exactly what I want. I am exploring Django as an option in our stack and I would like to replace the implementation of class two's insert() with save() from models.Model. How can I use my Database object with save()? def insert(self, insert_data, db): self.save() -
Django, gunicorn workers, scaling on Kubernetes
Kind of related to this post, we're in a similar position where we have a django application using gunicorn WSGI running on a Kubernetes cluster. I have read the official docs on how to configure num of workers (see design), but I still don't understand how this converts to a kubernetes pod running on a cluster utilising shared CPU? I have done various load tests on our test environment and the following is an idea of metrics I get and the resources in use: Django deployment containing 3 pods minimum but can scale to 20 Each pod has 1 CPU in Kubernetes config Each pod runs 3 gunicorn WSGI workers currently Pods run across Kubernetes nodes, each node has 4 CPUs Simple load testing suggests, we reach about 20-25rps maximum and then workers begin to restart, which seems quite bad! Scaling kicks in but its a lot slower than I'd like, despite optimisations, although we are slowed down a little by the istio-proxy side containers which have to start first before the app container Does anyone have any similar issues when it comes to scaling django apps? I know there can be a lot of differences depending on code, API … -
Image Upload Django with Ckeditor Failed Undefined
I'm trying to create a blog page with Django. I'm using CKEditor to add text. When I upload images locally, I don't have any issues, but I encounter a problem when I deploy the project to the server. When I go to the image upload section in CKEditor and click "Send to Server," I receive an "undefined" error in the popup that appears. failed but I don't get this error when I start the project in my local. Ckeditor -v = django-ckeditor==6.7.0 Django -v = Django==4.2.4 CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_STORAGE_BACKEND = 'django.core.files.storage.FileSystemStorage' FILEBROWSER_REMOVE_DIALOG_TABS = 'image:Upload' CKEDITOR_CONFIGS = { 'default': { 'filebrowserUploadUrl': '/ckeditor/upload/', 'filebrowserBrowseUrl': '/ckeditor/browse/', 'toolbar': 'Full', # Toolbar ayarları düzeltildi 'toolbar_Full': [ ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['NumberedList', 'BulletedList'], ['Indent', 'Outdent'], ['Maximize'], {'name': 'about', 'items': ['CodeSnippet']}, {'name': 'tools', 'items': ['Maximize', 'ShowBlocks']}, ], 'tabSpaces': 4, 'fillEmptyBlocks': False, 'extraPlugins': 'justify,liststyle,indent,codesnippet,devtools,uploadimage', # Resim eklentisi eklendi 'uploadUrl': '/ckeditor/upload/', # Resim yükleme URL'si eklendi }, } Have you encountered this problem? I would like your comments on the topic. enjoy your work I didn't expect to run into a problem here. It is interesting that … -
Sending email with Celery and Redis cloud
I am trying to send an email using celery queue @shared_task as below: # removed imports for clarity # For debugging @shared_task(bind=True, name="send_email", max_retries=3, default_retry_delay=10) def send_email(self, subject, message, from_email, to_email, **kwargs): """Send an email""" try: send_mail(subject, message, from_email, [to_email], **kwargs) except Exception as e: logger.error(e) # configured logger class Command(BaseCommand): help = "Send test email" def handle(self, *args, **options): try: send_email.delay( "Test email", "This is a test email", settings.EMAIL_HOST_USER, "validemail@examle.com", fail_silently=False, ) self.stdout.write(self.style.SUCCESS("Email queued successfully")) except Exception as e: raise CommandError(e) And I get ...celery stack trace raise SMTPRecipientsRefused(senderrs) smtplib.SMTPRecipientsRefused: {'validemail@example.com': (550, b'Please turn on SMTP Authentication in your mail client. 333.kpservers.com\n(altar56.supremepanel56.com) [cpanel_server_ip]:43036 is not permitted to\nrelay through this server without authentication.')} However when I use direct send_mail without shared_task it is successful (so it doesn't seem to be a server error) How do I resolve this error? I am using redis database redis://default:*******@********.cloud.redislabs.com:13122 -
Django anon cart system not working on first visit to site
I wanted to implement an anonymous cart system to my django site. I saw on internet that I can achieve with the following javascript code: function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } let device = getCookie('device') if (device == null || device == undefined){ device = uuidv4() } document.cookie ='device=' + device + ";domain=;path=/" Which is embedded at the end of 'base.html' which is a template every other html uses. like this: <script src="{% static 'js/cookies.js'%}"></script> Followed by this home page code: class HomeView(ListView): template_name = "index.html" def get(self, *args, **kwargs): context = get_base_lists(self.request) ... return render(self.request, self.template_name, context) ... def get_base_lists(request): ... cart, created = … -
Updating objects in queryset computed with filter clears the query
I have: jobs = Job.objects.filter(detected__isnull=True).order_by('submitted') print(f"Detected {len(jobs)} jobs") jobs.update(detected=ms_now()) try: print(jobs[0].id) except: print("No objects!") Output: Detected 865 jobs No objects! It seems like the filter is re-computed due to the update, but why does this happen? -
correct response code for role management
I’ve a user model and have some roles through other models (admin , doctor , patient, manager models ... etc) . I’ve one login endpoint for all . the patient, doctor only login with mobile number (didn’t handle it yet “means if he has email can login too”). patient only uses mobile application ... doctors on the web. all endpoints of each role are guarded with it’s related model , Like all users can login successfully as long as they’ve a User model , But when they try to access the admin , doctor… etc, they must have a related relation of the role … like if a user need to access the doctor endpoints , he must have a doctor instance . A user can have many roles (can register as many roles). What’s the best response code for this case if a user tried to access doctor endpoints without having a doctor instance ? 404 (user not found ) or 403 (unauthorized) and why please give a detailed response . Thanks I've implemented the response as a 403 , but "considering the doctor can be a patient" when he (doctor) logins through mobile (as patient) while he doesn't … -
I am trying to make website where users can see user specific data, but I can get the user's data in my in order to pass it my template
On my photo album website each user should see only the images that he uploaded, however when I specify user in my get_context_data method my context object becomes empty. I tried various methods that I found in the internet, but nothing works -
How to show the video with mediapipe in html in django?
my html and views.py are refer to https://roytuts.com/upload-and-play-video-using-django/, but i want to change the display video to video with mediapipe,what should i do or change in my code? mediapipe code in views.py: def process_video(filename): input_video_path = filename output_video_path = f"processed_{filename}" cap = cv2.VideoCapture(input_video_path) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fourcc = cv2.VideoWriter_fourcc(*'MP4V') out = cv2.VideoWriter(output_video_path, fourcc, 20.0, (width, height)) while cap.isOpened(): ret, frame = cap.read() if not ret: break image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) results = holistic.process(image) # Draw landmarks and connections mp_drawing = mp.solutions.drawing_utils mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(121, 22, 76), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(121, 44, 250), thickness=2, circle_radius=2)) mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(80, 22, 10), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(80, 44, 121), thickness=2, circle_radius=2)) mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS, mp_drawing.DrawingSpec(color=(245, 117, 66), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(245, 66, 230), thickness=2, circle_radius=2)) out.write(image) cap.release() out.release() cv2.destroyAllWindows() -
Can I be full stack with django in backend [closed]
everyone knows that in order to be a full stack, you need to have a frontend and a backend, in the backend you usually use php, java, c # and others. The question is can I be a full stack with Django read up read up read up