Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can't Open AI read from my site and yet it has no issues crawling other sites? It doesn't seem to know that my site exists
I made a site where people can get to upload documents and Open AI can view and summarise them for them, or perform other operations on them. However, for some reason, in the Playground, Open AI can't read from my site but can read from other sites with no problem. I thought it was an issue with my server so I even hosted the site on two different ones, and still, it won't work. The site is at heroku and pythonanywhere I used simple 'bot friendly code' if there is such a thing... but Open AI still can't see the document. Is there a way that I can mitigate this problem? Maybe it has something to do with the servers? Or DNS? I really don't know. -
Django: how to connect customizable url to GET method
I want to implement a search method that takes as filters properties selected by user from front-end side. The URL I want to create would be something like: urls.py: urlpatterns = [ path('', views.get_data), path(r'^find/<property>/<filter>/<value>', views.filter_view) ] Where is the value (1-9) selected from: <div class="dropdown-wrapper" style="padding-left: 0px"> <select class="dropdown" id="select-properties-dropdown"> <option class="property" value="0">Select property</option> <option class="property" value="1">GID</option> <option class="property" value="2">Type</option> <option class="property" value="3">Province</option> <option class="property" value="4">Street</option> <option class="property" value="5">House number</option> <option class="property" value="6">Postcode</option> <option class="property" value="7">City</option> <option class="property" value="8">Municipality</option> </select> </div> is the value from: <div class="dropdown-wrapper" > <select class="dropdown"> <option class="property" value="0">Contains</option> <option class="property" value="1">Equal to</option> <option class="property" value="2">Ends with</option> <option class="property" value="3">Starts with</option> </select> </div> and is the taken from the searchbar: <div class="dropdown-wrapper"> <form action="find" method="GET"> <input class="input searchbar" type="text" aria-autocomplete="list" aria-expanded="false" id="searchBar" style="height: 28.5px" > <button type="submit"><i class="fa fa-search"></i> </button> </form> </div> -
Django - How to save an image from a blob URL
I have a blob URL stored in a Django model field and I want to convert it to an image and save it to an ImageField. Here is my code in models.py : class Message(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) room = models.CharField(max_length = 255) content = models.TextField() date_added = models.DateTimeField(null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to='message_images') image_url = models.URLField(max_length=255, unique=True) class Meta: ordering = ('date_added', ) def save(self, *args, **kwargs): super().save(*args, **kwargs) #Trying to save the image here img = Image.open(self.image_url) img.save(self.image.path) Question: How can I convert the blob to an image and save it? -
Running a Django application from a cloned repository that has environment variables
I'm trying to run a Django application from a cloned repository and I noticed that it has environment variables stored in the settings.py file(namely: the SECRET_KEY and DEBUG). When running the application, it gives me the following error: django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable I understand that Django cannot run without it but I have the following doubts regarding this problem. Should I provide my own SECRET_KEY and declare it inside a .env file. Also, is it necessary to have the same SECRET_KEY as the original project file did? -
Nginx not serving static files /Django
When I deploy my project to server using Nginx and Gunicorn static files are not loading. This is how my website looks after deploying nginx.service is as follows user nginx; worker_processes auto; error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; server { listen 8081; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root home/zp_dashboard_testing_python/zp_main/staticfiles; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/run/gunicorn.sock; } } } settings.py BOOTSTRAP4 = { 'include_jquery': True, } STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I have run collectstatic command and it gives some warnings file already found at destination path, but its just a warning and not an error. nginx error logs are as follows 2022/05/01 19:27:49 [error] 77154#77154: *5 open() "/etc/nginx/home/zp_dashboard_testing_python/zp_main/staticfiles/static/assets/libs/datatables.net-buttons/js/buttons.html5.min.js" failed (2: No such file or directory), client: 10.81.234.6, server: 0.0.0.0, request: "GET /static/assets/libs/datatables.net-buttons/js/buttons.html5.min.js HTTP/1.1", host: "10.10.89.25:8081", referrer: "http://10.10.89.25:8081/dashboard/" 2022/05/01 19:27:49 [error] 77154#77154: *7 open() "/etc/nginx/home/zp_dashboard_testing_python/zp_main/staticfiles/static/assets/libs/datatables.net-buttons/js/buttons.print.min.js" … -
Django multiple relations in one model
I have been trying to create a model that could represent the form as it is, tried creating an EntryForm model which is linked to EntryFormTable where then each column in the table is a model class all linked to the table, but then this proved to be a long way and one that doesn't even work, maybe there's a short or even a working method to represent this in django models, -
AttributeError: module 'typing' has no attribute '_ClassVar'
I've completed the deployment of the Django project on Azure Web App. However, if I attempt to launch my program, this error is recorded in the log. I have absolutely no idea what is going on. Even I am confused as to why the dataclasses are being constructed. Anyone who can assist me would be much appreciated; I need assistance with this difficulty. 2022-05-01T13:49:50.189019473Z 2022-05-01T13:49:50.189048674Z _____ 2022-05-01T13:49:50.189060474Z / _ \ __________ _________ ____ 2022-05-01T13:49:50.189064774Z / /_\ \___ / | \_ __ \_/ __ \ 2022-05-01T13:49:50.189068474Z / | \/ /| | /| | \/\ ___/ 2022-05-01T13:49:50.189072174Z \____|__ /_____ \____/ |__| \___ > 2022-05-01T13:49:50.189075874Z \/ \/ \/ 2022-05-01T13:49:50.189079574Z 2022-05-01T13:49:50.189083074Z A P P S E R V I C E O N L I N U X 2022-05-01T13:49:50.189087974Z 2022-05-01T13:49:50.189091474Z Documentation: http://aka.ms/webapp-linux 2022-05-01T13:49:50.189094974Z Python 3.9.7 2022-05-01T13:49:50.189098374Z Note: Any data outside '/home' is not persisted 2022-05-01T13:49:50.465258799Z Starting OpenBSD Secure Shell server: sshd. 2022-05-01T13:49:50.566940080Z App Command Line not configured, will attempt auto-detect 2022-05-01T13:49:50.574021984Z Launching oryx with: create-script -appPath /home/site/wwwroot -output /opt/startup/startup.sh -virtualEnvName antenv -defaultApp /opt/defaultsite 2022-05-01T13:49:50.606042350Z Found build manifest file at '/home/site/wwwroot/oryx-manifest.toml'. Deserializing it... 2022-05-01T13:49:50.607452471Z Build Operation ID: |Y2+7faeVpcs=.7771bea2_ 2022-05-01T13:49:50.608042879Z Oryx Version: 0.2.20211207.1, Commit: 46633df49cc8fbe9718772a3c894df221273b2af, ReleaseTagName: 20211207.1 2022-05-01T13:49:50.608069580Z Output is compressed. Extracting it... 2022-05-01T13:49:50.624718722Z Extracting '/home/site/wwwroot/output.tar.gz' … -
django admin popups are broken when using 'collect static', what might be the problem?
When I try to press + on a many-to-many or foreign-key or any field like that, it usually gives me a popup window. Now it's just redirecting me to URL.../model/add/?_to_field=id&_popup=1 which complicates everything. I read and tried these posts, but none of them helped: Django admin add related object doesn't open popup window? https://github.com/sehmaschine/django-grappelli/issues/600 Django admin popup links are broken After experimenting with Django, I found out that only happens when you use python manage.py collectstatic When you delete everything from the static folder, it gets fixed. What might be the problem? I'm not using any special thing, I made a fresh boilerplate Django application, added 2 models, and ran collect static, and it still happened. Django version: 4.0.3 Python version: 3.10.2 Pip version: 22.0.4 -
How to query data with datetime month paramenter?
I have filter function to query data based on month. I use Calendar. Here is my code : def ListAll(request): list_month = list(calendar.month_name)[1:] list_year = Year.objects.all() objects = Rental.objects.filter(is_terminate = True).order_by('-created') year_query = request.GET.get("year") month_query = request.GET.get("month") if month_query : month_number = list(calendar.month_name).index(month_query) month_number = int(month_number) objects = Rental.objects.filter(is_terminate=True, created__month=month_number, created__year=year_query).order_by('-created') context = { 'objects':objects, 'list_month': list_month, 'list_year': list_year } return render(request, 'report_rental/all.html', context) In my model, field created: models.DateTimeField(auto_now_add=True) My problem is, i got Empty data with query using month with this objects = Rental.objects.filter(is_terminate=True, created__month=month_number, created__year=year_query).order_by('-created') Does anyone can help me? Thank you -
How to using loop to show all images in my web page- HTML, django, Boostrap?
My views: def home (request): user = request.user Movies_obj = models.Movies.objects.all() return render(request, 'home.html', {'user': user, 'movies1': Movies_obj[:4], 'movies2': Movies_obj[4:8], 'movies3': Movies_obj[8:12]}) My HTML: <div class="carousel-inner"> <div class="carousel-item active"> <div class="row"> {% for mv1 in movies1 %} <div class="col"> <img class="img-thumbnail" src="{{mv1.image.url}}" alt="First Slide" width="100%"> </div> {% endfor %} </div> </div> <div class="carousel-item"> <div class="row"> {% for mv2 in movies2 %} <div class="col"> <img class="img-thumbnail" src="{{mv2.image.url}}" alt="First Slide" width="100%"> </div> {% endfor %} </div> </div> <div class="carousel-item"> <div class="row"> {% for mv3 in movies3 %} <div class="col"> <img class="img-thumbnail" src="{{mv3.image.url}}" alt="First Slide" width="100%"> </div> {% endfor %} </div> </div> Previous Next -
Chart js and django for long data
On my django app , i need to create a line visualization using chart js exemple of one value : 0;-0.0110227457430789;-0.0117428254241928;-0.0125132024365239;-0.0120122425942302;-0.0121398995885254;-0.0127606573714123;-0.0123882233559148;-0.0126683380476791;-0.0125534489771807;-0.0114614833910938;-0.0139670311717919;-0.0117059991385652;-0.0127469146854689 is it possible to use chart js with this size of data ? <canvas id="myChart" width="400" height="400"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for s in data%} {{s.sampleID}} {%endfor%} ], datasets: [{ label: '# of Votes', data: [{% for s in data%} {{s.absorbance}} {%endfor%} ], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> -
Customize Form with Django FORM API
I am currently creating an register/login form with the Django framework, since I am new to this framework, I don't know much about the FORM API. I am not using the FORM API, since I don't know if I can customize it. Is there any way to use my styling with the FORM API? As the state of now, I am just creating my own one, without using the API, but since the FORM API is more secure and much faster to set up for user creation, I would like to use it. Can I just implement the API into my html code, without putting out my classes and styling? Here is my HTML form: {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <div class="limiter"> <div class="container-login100" style="background:black;"> <div class="wrap-login100"> <form class="login100-form validate-form" method='POST' action="{% url 'users:register' %}" > {% csrf_token %} <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Register </span> <div class="wrap-input100 validate-input" data-validate = "Enter username"> <input class="input100" type="text" name="username" placeholder="Username" required> <span class="focus-input100" data-placeholder="&#xf207;"></span> </div> <div class="wrap-input100 validate-input" data-validate="Enter password"> <input class="input100" … -
Database relationship between a match and its players
I'm trying to design a database that would save matches and players in a 3v3 game. So far my models look like this : class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) player_tag = models.CharField(max_length=9, unique=True) player_name = models.CharField(max_length=50) trophy_count = models.IntegerField(default=0) club = models.ForeignKey('Club', on_delete=models.SET_NULL, null=True) total_club_war_trophy_count = models.IntegerField(default=0) class Club(models.Model): club_name = models.CharField(max_length=50) club_tag = models.CharField(max_length=9, unique=True) class Match(models.Model): # Matches are 3v3 player_1 = models.ForeignKey(Player, on_delete=models.CASCADE) player_2 = models.ForeignKey(Player, on_delete=models.CASCADE) player_3 = models.ForeignKey(Player, on_delete=models.CASCADE) player_4 = models.ForeignKey(Player, on_delete=models.CASCADE) player_5 = models.ForeignKey(Player, on_delete=models.CASCADE) player_6 = models.ForeignKey(Player, on_delete=models.CASCADE) # Brawlball, Gem grab, Knockout ... mode = models.CharField(max_length=20) # Power match or normal match battle_type = models.CharField(max_length=20) trophies_won = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) However the repetition of "player_<int>" is itching me, I don't think this is the proper way to do it. What if the number of player changes at some point, or how to I find if a player participated in a match ? I think it's a clunky approach at best. How could I approach this better ? I was thinking about maybe a list of players, but I don't know how to characterize this kind of relationship. -
Django on Elastic Beanstalk
I zipped my Django project and dropped it in the AWS Elastic Beanstalk service. My plan is to leverage IAM to deliver fine grained access to the SQL database populated via my Django app and otherwise from client device data (via MS ActiveDirectory, ) and patient files downloaded from obsolete devices. Am curious whether experts recommend populating my templates with AWS CLI code (to implement the IAM infrastructure programmatically) before I move the zipped files to EB or whether I can make adjustments to the Django templates sitting in EB already (perhaps from cloud9 or thru updates). First problem to address tho: my EB app status is "severe." Still troubleshooting the "severe" status issue. -
{% url ... %} templatetag in Django included template not seeing variable
I'm experiencing strange behaviour in an included template which I can't figure out. parent_template.html {% for item in items %} Parent: {{ item.pk }} {% include 'child_template.html' %} {% endfor %} child_template.html Child: {{ item.pk }} URL: {% url 'some_named_url' item.pk %} I get a reverse error: Reverse for '/test/url/<int:pk>/' with arguments '('',)' not found. 1 pattern(s) tried: ['test/url/(?P<pk>[0-9]+)/\\Z'] If however I remove the {% url ... %} template tag, it renders correctly and shows: Parent: 1 Child: 1 So it's clear that item is in the context, but for some reason it isn't being passed to the templatetag. I have also tried variations like: {% for item in items %} {% with new_item=item %} {% include 'child_template.html' %} {% endwith %} {% endfor %} Any ideas? I am using Django 3.2.12 -
Translate WKT geometry from database into GeoJSON using Django
I have a database with schools that have as attributes geometry in this format: 01040000000100000001010000000CC47A46B78BF64038FB9CC22D731A41 I was wondering how can I translate this geometry into latitude and longitude using django. views.py: from django.http import JsonResponse from django.shortcuts import render from rest_framework.decorators import api_view from base.models import RSchools as School from definitions import ROOT_DIR from .serializers import SchoolSerializer @api_view(['GET']) def get_data(request): schools = School.objects.all() for school in schools: #PREPROCESS EACH SCHOOL GEOMETRY HERE INTO LATITUDE AND LONGITUDE pass return render(request, f'{ROOT_DIR}/templates/tst/index.html', {'schools': schools}) models.py: from django.db import models # Create your models here. class RSchools(models.Model): gid = models.AutoField(primary_key=True) schooltype = models.CharField(max_length=254, blank=True, null=True) provincie = models.CharField(max_length=254, blank=True, null=True) straatnaam = models.CharField(max_length=254, blank=True, null=True) huisnummer = models.CharField(max_length=254, blank=True, null=True) postcode = models.CharField(max_length=254, blank=True, null=True) plaatsnaam = models.CharField(max_length=254, blank=True, null=True) gemeentena = models.CharField(max_length=254, blank=True, null=True) geom = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: # managed = False db_table = 'r_schools' -
Foreignkey relationship returning an AttributeError when queried in Django
Hy please am new to Django,I have a childmodel(relationship) referencing a parent model(Profile) through a foreign key. I want to get the relationship status of a particular profile, like querying it from backwards. Here's the code. from django.db import models from django.contrib.auth.models import User #Create your models here. class Profile(models.Model): user = models.OneToOneField (User, on_delete= models.CASCADE) prof_pics = models.ImageField (null = True, blank = True, upload_to = 'images/') friends = models.ManyToManyField (User, blank=True, related_name="friend" ) bio = models.TextField(blank=True) def__str__(self): return str(self.user) STATUS CHOICES = ( ("accept", "accept"), ("send","send"), ) def ___str__(self): return str(self.user) class Relationship(models.Model): sender = models.Foreignkey(Profile, on_delete = models.CASCADE, null=True, related_name = "senders") date_created = models.DateTimeField(auto_now_add= True) receiver = models.ForeignKey(Profile, on_delete= models.CASCADE, null= True, related_name= 'receivers') status = models.Charfield(max_length=10, choices= STATUS_CHOICES) def_str_(self): return f"{self.sender}-{self.receiver}-{self.status}" The query I ran in my view to get the relationship of a particular profile as I saw a tutorial that did same thing with similar models. #imported necessary dependencies def relationship_view(request): idd = request.user.id profiles =Profile.objects.get(id=idd) rel=profiles.relationship_set.all() Print(rel) return render(request, "profiles/relationship_query.html", {}) A screenshot from the tutorial The error I get when I run my own view File "C:\Users\semper\djangotry\twitterclone\profiles\views.py", line 96, in Relationship_view rel = profiles.relationship_set.all() AttributeError: 'Profile object has no attribute 'relationship_set" -
Django ckeditor_uploader is not working what is the issue in my code
settings.py file enter image description here urls. py enter image description here models. py enter image description here -
Error: (admin.E035) The value of 'readonly_fields[0]' is not a callable
Summarize the problem <class 'news.admin.NewsAdmin'>: (admin.E035) The value of 'readonly_fields[0]' is not a callable, an attribut e of 'NewsAdmin', or an attribute of 'news.News'. This all code error. I learn Django, and write code how in author. But write this error :( Describe what you`ve tried I immediately insert problem in search, but not found decision I read this question, but it not finished This question elementary, author question not correct write variable Show some code admin.py from django.contrib import admin from .models import News, Category class NewsAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'category', 'create_at', 'updated_at', 'is_published') list_display_links = ('id', 'title',) # what be links in model search_fields = ('title', 'content',) list_editable = ('is_published',) # redact is published in menu list_filter = ('is_published', 'category',) # create table, what in be setting sorted fields = ('title', 'category', 'content', 'photo', 'get_photo', 'is_published', 'views', 'create_at', 'updated_at') readonly_fields = ('get_photo', 'views', 'create_at', 'updated_at') class CategoryAdmin(admin.ModelAdmin): list_display = ('id', 'title') # displays list_display_links = ('id', 'title') # links search_fields = ('title',) admin.site.register(News, NewsAdmin) admin.site.register(Category, CategoryAdmin) models.py from django.db import models from django.urls import reverse class News(models.Model): title = models.CharField(max_length=150) content = models.TextField(blank=True) create_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) is_published = models.BooleanField(default=True) category … -
Filter Django model based on other model
I have two models Wellinfo and LOGRD_RPT class Wellinfo (models.Model): WellID = models.CharField(max_length=15,unique=True) Perimeter = models.CharField(max_length=50) class LOGRD_RPT(models.Model): WellID = models.CharField(max_length=15, validators= [validate_textComptn]) I need to get a list of WellID (ListaWells) from the first model Wellinfo based on two conditions: 1- Perimeter. 2- if the WellID exists in the second model LOGRD_RPT So the First step is to get all wells that belong to a Field='FD1' in the Wellinfo model ListaWells= Wellinfo.objects.filter(Perimeter=Field) then I need to exclude the wells that don't exist in the 2nd model LOGRD_RPT. -
Even Gunicorn works well in locally, I face with Internal Server Error
This is my first deploy in Django for production. I tested whether it can serve my Django application by running the following command and there is no problem I can reach my site by my server ip adress. gunicorn hello.wsgi:application --bind 0.0.0.0:8000 application --bind 0.0.0.0:8000 [2022-05-01 11:00:46 +0000] [26484] [INFO] Starting gunicorn 20.1.0 [2022-05-01 11:00:46 +0000] [26484] [INFO] Listening at: http://0.0.0.0:8000 (26484) [2022-05-01 11:00:46 +0000] [26484] [INFO] Using worker: sync [2022-05-01 11:00:46 +0000] [26486] [INFO] Booting worker with pid: 26486 /home/scknylmz35/PersonelBlog/home/views.py:24: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'home.models.Blog'> QuerySet. Then I followed following commands: sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=baris Group=www-data WorkingDirectory=/home/baris/eventhub ExecStart=/home/baris/eventhub/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/baris/eventhub/eventhub.sock eventhub.wsgi:application [Install] WantedBy=multi-user.target sudo systemctl start gunicorn sudo systemctl enable gunicorn And I tested gunicorn >> sudo systemctl status gunicorn Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor pres> Active: active (running) since Sun 2022-05-01 08:01:47 UTC; 2h 19min ago Main PID: 23885 (gunicorn) Tasks: 4 (limit: 1132) Memory: 136.3M CGroup: /system.slice/gunicorn.service ├─23885 /home/scknylmz35/PersonelBlog/venv/bin/python /home/scknyl> ├─23897 /home/scknylmz35/PersonelBlog/venv/bin/python /home/scknyl> ├─23898 /home/scknylmz35/PersonelBlog/venv/bin/python /home/scknyl> └─23899 /home/scknylmz35/PersonelBlog/venv/bin/python /home/scknyl> It seems working good. But when I try to reach my site as mysite.me I face with "Internal Server Error" Also when … -
Why picture don't move Django
I can't do anything with my pic. It is be displayed, but my CSS-file don't work properly. Grid-class too HTML: {% extends 'main/base.html' %} {% load static %} {% block title %} {{title}} {% endblock %} {% block content %} <link rel = 'stylesheet' href = "{% static 'main/css/main.css' %}"> <body> <div class="grid-wrapper"> <header class="grid-header"> <img class="circles" width="1400px" height="249px" src="{% static 'main/img/main2.jpg' %}"> </header> <div class="grid-content"> Контент </div> </div> <body> {% endblock %} css: .cicles { display: block; margin-left: auto; margin-right: auto; } I try work with pic through .grid-header and .grid-wrapper. It didn't work -
"subprocess.run() wait for command to complete, then return a CompletedProcess instance", but I am getting the desired output late
I am learning django and I am stuck with this problem. I am using subprocess.run() but the output file generated by it is late. Here is the code snippet. run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {video_name}_audio_stripped.mp4 -i {audio_name} -c:v copy -c:a aac {final_tutorial}"], cwd="media/") #for i in range(1000000000): # continue run(["gnome-terminal", "--", "sh", "-c", f"ffmpeg -i {final_tutorial} -vcodec libx265 -crf 28 reduce_{final_tutorial}"], cwd="media/") As you can see that the second run() uses the first run() output as input but although the first run() executes and returns a CompletedProcess instance the file generated by it is generated late. Please note that the file has to be generated completely for the second run() to work, so although the first run() generates the file it does not generate it completely, I mean it does generate it but its too late so the second run() doesn't get the complete file and does not produce any output. I am unable to understand this ambiguous behaviour because according to python documentation subprocess.run run the command described by args. Wait for command to complete, then return a CompletedProcess instance. If I do uncomment the for loop in order to add a time delay it works but I … -
How to upload images in Django
I want to upload thumbnail into media/thumbnails folder, however my images uploads to media/thumbnails/thumbnails folder. How can I fix this? All my code models.py class Post(models.Model): title = models.CharField(max_length=100) content = RichTextField(null=True,blank=True) date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) thumbnail = models.ImageField(default='default.jpg',upload_to='thumbnails/') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) new_image = self.crop_max_square(Image.open(self.thumbnail.path)).resize((300, 300), Image.LANCZOS) new_image_io = BytesIO() new_image.save(new_image_io, format='JPEG') temp_name = self.thumbnail.name self.thumbnail.delete(save=False) self.thumbnail.save( temp_name, content=ContentFile(new_image_io.getvalue()), save=False ) settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' -
What is the best way to restrict login page for authenticated users
I have the following middleware: class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response self.login_path = '/login/' self.home_path = '/' def __call__(self, request): if request.user.is_authenticated and request.path == self.login_path: return redirect(self.home_path) response = self.get_response(request) return response It is a good idea to redirect any already authed users to home page if they try to reach login page? Thanks in advance!