Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
download not working and image not showing
I want to create a download link using the anchor tag but it is not working and the image is not showing either <td><img src="{{book.book_image}}" alt="{{book.name}}" width="60px" height="50p"></td> <td>{{book.book_name}}</td> <td>{{book.author_name}}</td> <td>{{book.subject}}</td> <td><a href="{{book.file}}" download>Download</a></td> models.py class Book(models.Model): book_image = models.ImageField(upload_to="images/", blank="") book_name = models.CharField(max_length=150) author_name = models.CharField(max_length=200) quantity = models.IntegerField(default=1) file = models.FileField(upload_to="files/", null=True, verbose_name='file ') subject = models.CharField(max_length=2000) book_add_time = models.TimeField(default=timezone.now()) book_add_date = models.DateField(default=date.today()) -
postgres connection test always succeeds
I was making TDD tests for my django projects to test the PostgresQL connection the i realized connections tests alwayse sucseeds even when the database is not available. Could anybody tell what the problem is? Here's my project repository: https://github.com/PeymaanEsi/alone/tree/dev (Database configuration in docker compose is commented) ~/Desktop/alone$ docker compose up [+] Running 2/0 ✔ Container db Created 0.0s ✔ Container alone Created 0.0s Attaching to alone, db db | db | PostgreSQL Database directory appears to contain a database; Skipping initialization db | db | db | 2023-09-01 20:03:03.391 UTC [1] LOG: starting PostgreSQL 15.4 on x86_64-pc-linux-musl, compiled by gcc (Alpine 12.2.1_git20220924-r10) 12.2.1 20220924, 64-bit db | 2023-09-01 20:03:03.391 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db | 2023-09-01 20:03:03.391 UTC [1] LOG: listening on IPv6 address "::", port 5432 db | 2023-09-01 20:03:03.394 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db | 2023-09-01 20:03:03.399 UTC [24] LOG: database system was interrupted; last known up at 2023-09-01 16:14:25 UTC db | 2023-09-01 20:03:03.435 UTC [24] LOG: database system was not properly shut down; automatic recovery in progress db | 2023-09-01 20:03:03.438 UTC [24] LOG: redo starts at 0/4138D08 db | 2023-09-01 20:03:03.438 UTC [24] WARNING: … -
How to create self-signed SSL certificate in pure python? (Without any additional installation like openssl or mkcert)
There are similar questions like this which did not have any good answer, or linked to scripts that were very old. I have an open-source web app made using django that people can install on their local networks. I want to implement a quick, automated set up of the web app, with minimal technical know-how. One of the tasks involved is generating self-signed SSL certificates. However, since I do not know in advance what OS they would be using, I wish the certificate stuff to be done exclusively using python, to ensure platform independence. Common methods like using OpenSSL includes OS-specific installation of those libraries, which I do not want. How can I make secure self-signed ssl certificates exclusively through python and no additional installations like OpenSSL or mkcert? -
Django CRSF across different origins for login request
I have been struggling and doing research for couple of days. I am currently use Django with Django rest_framework and django-allauth to build backend APIs and the authentication workflow. Everything runs prefect by hosting everything onto the same origin VM(A). Now due to requirement, I need to separate frontend login and backend API into two different origin. (A & B) APIs are behind the proxy. Instead of using django-allauth default server rendered login page(which auto set the csrf in {% csrf_token %}) I have made a simple login.html and put it into host A under apache /var/www/html/: <form class="login" method="POST" action="https://B.com/accounts/login/"> <input id="csrf" type="hidden" name="csrfmiddlewaretoken"> <p> <label for="id_login">Login:</label> <input type="text" name="login" placeholder="Username or e-mail" autocomplete="email" required="" id="id_login"> </p> <p> <label for="id_password">Password:</label> <input type="password" name="password" placeholder="Password" autocomplete="current-password" required="" id="id_password"> </p> <button type="submit">Sign In</button> </form> <script type="text/javascript"> window.onload = function(){ // Get csrf from B and set into cookie 'getToken' API is defined below $.ajax({ url: "https://B.com/getToken", type: 'GET', dataType: 'json', success: function(res) { console.log(res); $('#csrf').val(res.token); document.cookie = 'csrftoken=' + res.token; } }) }; </script> When the login.html is rendering it will make a GET request to the backend(B) API (/getToken) to fetch the csrftoken and save into the cookie and csrfmiddlewaretoken … -
Why does pydoc work for some Django folders and not others? How to debug it?
I am using Django 4.2, and after setting DJANGO_SETTINGS_MODULE appropriately, I ran python -m pydoc -b When I visit the pydoc page, a lot of it produces pydoc, even within the modules of my Django project and application. However, occasionally it says: ErrorDuringImport: problem in myapp.mymodule - AppRegistryNotReady: Apps aren't loaded yet. It says this, for example, in the admin module (i.e. admin.py). Why would it work some times and not other times? I imagine it's some particular import? How do I figure out which one? -
How can I efficiently retrieve a users feed in a social media app with Django
I am new to programming and new to Django and I am trying to design my first social media app. I wanted to see if theres an efficient way of retrieving a users feed that would result in quick retrieval of the users feed without being intensive on the database. I want to learn what the best practices are to follow to construct efficient API views. Provided below are my current User model, Follow model, and API view to retrieve a users feed. I was wondering what improvements I could make to my current implementation so I could learn more about Django and how to construct an efficient app. Currently, my API view retrieves all of the users the requesting user is following and then retrieves Posts made by those users. However if the user is following a lot of people, the query to get a list of all the users the requesting user is following might be inefficient, at least I think so. Would there be a better implementation to perform so I can get the users feed that would not be intensive in terms of database retrieval? I have the following User model: class User(AbstractUser): # Additional fields … -
AWS EC2 Instance get slow but sometimes it works fine
I have a basic blog application made in Django and Python is hosted on AWS EC2 t2.micro using NGINX. It used PostgreSQL as database. The website loads fine most of the time but sometimes it takes too much time to load. Sometimes even the Django admin panel takes more time to load. I checked the monitor section of my EC2 instance and it all seems to be fine. Here is an screenshot. I also checked the memory and storage using free -m and top command but all seems to be fine. I am not sure what wrong in here. If anyone have faced this similar issue or know how to debug such things please let me know. Thanks in advance -
How to modify an image before saving it in the database in Django?
I took an image as the input by the user via a form, I increased its brightness using Pillow, and now wish to save the image in the database. I am having trouble trying to modify the form with the new image so that I can save it. Please help me out. if form.is_valid(): input = form.save(commit=False) input.owner = request.user image = Image.open(input.image) # Enhance Brightness curr_bri = ImageEnhance.Brightness(image) new_bri = 2.5 # Brightness enhanced by a factor of 2.5 img_brightened = curr_bri.enhance(new_bri) image_file = ImageFile(img_brightened, name=None) form_image = ImageClient(image=image_file) input.image = form_image input.save() return redirect('profile') -
UnicodeDecodeError when runvsever Django
Have a problem when starting local django server. When trying to run: python manage.py runserver or python manage.py runserver 127.0.0.1:8080 an error occurs: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc2 in position 55: invalid continuation byte Full error log: (my_env) D:\mysite\>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified some issues: WARNINGS: ?: (2_0.W001) Your URL pattern '^article/(?P<pk>\d+)/bookmark/$' [name='article_bookmark'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). System check identified 9 issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 136, in inner_run self.check_migrations() File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 574, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, … -
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()