Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app cannot find base.html located inside the project's templates - Django 3.2
I am new to Django even though I have done web development using ASP.NET before. I created a Django project to perform User Management following this tutorial - https://realpython.com/django-user-management/. I created an app called users inside the project lipreading_website using the command - python manage.py startapp users. I then created the templates folder inside this app - users/templates and placed a base.html file in users/templates and created the rest of the HTML files in users/templates/users/. I then referenced the base.html from inside the HTML files created inside users/templates/users using {% extends "base.html" %}. I then followed this tutorial - https://www.youtube.com/watch?v=vXXfXRf2S4M&t=2s&ab_channel=Pyplane to add a few more apps - quizzes, results, questions and adding a new base.html file in the project's template -> lipreading_website/templates/base.html. I made the following changes to the settings.py file - TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and proceeded to extend this file instead from one of the application's HTML files defined in quizzes/templates/quizzes/main.html. I want to extend the base.html in the project root templates folder, but it's still referencing the base.html created inside the users/templates/ folder. -
Override Django model field get_prep_value method
When getting a ValueError from a ForeignKey field in Django, the exception returns the response "Field ... expected a a number but got ..." using the field name. I'd like to change this exception to use the verbose_name if it exists, and the field name if it does not. How can I override this exception for all ForeignKey fields? Line 1818 in https://github.com/django/django/blob/main/django/db/models/fields/__init__.py def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return int(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e -
Best way to struct data to Plot a chart in Django
In order to plot a chart with Highcharts I have to structure a queryset in a list of dictionaries that have to look like the following: [{ name: 'Europe', data: [{ name: 'Germany', value: 767.1 }, { name: "Cyprus", value: 7.2 }] }, { name: 'Africa', data: [{ name: "Senegal", value: 8.2 }, { name: "Ghana", value: 14.1 }] }] The following code is the way I tried. The data is structured as requested and the graph is plotted good, but the final list (listsocios) is missing some values and repeating another ones. I guess it is memory issue. Whats your thoughs? Whats would be the more effecient way to struct? class GraphSociosProvinciasView(TemplateView): template_name = 'socios/socios_prov_graph.html' def get_context_data(self,*args, **kwargs): context = super(GraphSociosProvinciasView, self).get_context_data(*args,**kwargs) listsocios=[] listsocprov=[] #Por cada provincia guardo los socios for n in range(1,25): sociosp=Socios.objects.all().filter(provincia=n) TotalSocios=sociosp.count() listsocprov.clear() if TotalSocios!=0: for socp in sociosp: listsocprov.append({'name': socp.apellido,'value': socp.numero_socio},) nombre_provincia=socp.get_provincia_display() listsocios.append({'name':nombre_provincia,'data':listsocprov}) print(listsocios) context={ 'sociosprov': listsocios, } return context -
Deploying django 2.2 app on ubuntu 20.04 LTS
I wrote my app using python 3.6 before. Now I want deploy it on ubuntu 20.04 and default python is 3.8. After creating virtual environment when I run pip install -r requirments.txt I get errors for specific packages in terminal. Here is errors for those packages: Building wheel for cffi (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/pouya795/www/marketpine-backend/venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-2h487j4r/cffi_5a23efe094aa4c5dbccb0ae69bfca883/setup.py'"'"'; __file__='"'"'/tmp/pip-install-2h487j4r/cffi_5a23efe094aa4c5dbccb0ae69bfca883/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-2i6w3ayj cwd: /tmp/pip-install-2h487j4r/cffi_5a23efe094aa4c5dbccb0ae69bfca883/ Complete output (36 lines): running build_ext building '_cffi_backend' extension creating build/temp.linux-x86_64-3.8 creating build/temp.linux-x86_64-3.8/c x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/home/pouya795/www/marketpine-backend/venv/include -I/usr/include/python3.8 -c c/_cffi_backend.c -o build/temp.linux-x86_64-3.8/c/_cffi_backend.o c/_cffi_backend.c:15:10: fatal error: ffi.h: No such file or directory 15 | #include <ffi.h> | ^~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- ERROR: Failed building wheel for cffi Running setup.py clean for cffi Building wheel for Pillow (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/pouya795/www/marketpine-backend/venv/bin/python -u -c 'import … -
Creating a serializer that only list objects related to user
I want to make a serializer that only list Groups that the user is related to. My User model have a group field with manytomany relations to the Group model. And I want the GroupSerializer to only list the groups that the user is related to. This is my serializer now. class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name', 'description') read_only_fields = ('id',) Anyone know how I can do this? -
How to pass values using ajax post method. Values are passed into Views. But template doesn't have values through context
//I try to post my form values using a JQuery function. Calling my View and passed the values in context. Passing the context into a template and context doesn't have any value. //This is the JQuery function bookstay() { $.ajax({ type:'POST', url:'{% url 'book' %}', headers: {'X-CSRFToken': '{{ csrf_token }}'}, data:{ stay1: $('#stay1').val(), checkin1: $('#checkin1').val(), checkout1: $('#checkout1').val(), nights1: $('#nights1').val() }, success: function (data) { alert('Data passed successfully'); window.location.href = "stay/book"; }, }) } //This is the View. def book(request): cities = City.objects.all() context = {'cities': cities} if request.method == 'POST': stay1 = request.POST['stay1'] checkin1 = request.POST['checkin1'] checkout1 = request.POST['checkout1'] nights1 = request.POST['nights1'] print(stay1, checkin1) context = {'cities': cities, 'stay1': stay1, 'checkin1': checkin1, 'checkout1': checkout1, 'nights1': nights1} return render(request, 'stay/bookstay.html', context) return render(request, 'stay/bookstay.html', context) //This is the template <div> <h1>checkin1={{checkin1}}</h1> </div> -
I get the error. NoReverseMatch at /delete_mat/11/ in one of the apps in Django
Hail Devs. I created a second app in an existing Django project. The urls.py routes in the app work fine, but the views edit_mat, update_mat and delete_mat, which access the database despite performing the action do not reload the index page. The views that I don't access the database work perfectly. No idea what else to do. Can you help? erro: NoReverseMatch at /delete_mat/11/ Reverse for 'material' not found. 'material' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/delete_mat/11/ Django Version: 3.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'material' not found. 'material' is not a valid view function or pattern name. Exception Location: C:\webcq\venv\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\webcq\venv\Scripts\python.exe Python Version: 3.8.6 Python Path: ['C:\\webcq', 'C:\\Users\\Lewis\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', 'C:\\Users\\Lewis\\\AppData\\Local\\Programs\\Python\\Python38\\DLLs', 'C:\\Users\\Lewis\\\AppData\\Local\\Programs\\Python\\Python38\\lib', 'C:\\Users\\Lewis\\\AppData\\Local\\Programs\\Python\\Python38', 'C:\\webcq\\venv', 'C:\\webcq\\venv\\lib\\site-packages'] Server time: Mon, 17 May 2021 21:27:15 +0000 Traceback Switch to copy-and-paste view C:\webcq\venv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\webcq\venv\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\webcq\materiais\views.py, line 49, in delete_mat return redirect('material') … ▶ Local vars view.py app from django.shortcuts import render, redirect from materiais.models import EspecComponentes, Componente, Codigo, EspecMaterial from materiais.forms import EspecComponentesForm # Create … -
Why Celery 5 require djcelery?
I was implementing what the celery documentation says. celery.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') broker = 'sqla+postgresql://user:pass@localhost/db' app = Celery('proj', broker=broker) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') Error that I am facing. [2021-05-18 03:21:29,974: CRITICAL/MainProcess] Unrecoverable error: ModuleNotFoundError("No module named 'djcelery'") Traceback (most recent call last): File "/Users/proj/venv/lib/python3.9/site-packages/celery/app/base.py", line 1211, in backend return self._local.backend AttributeError: '_thread._local' object has no attribute 'backend' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/proj/venv/lib/python3.9/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/Users/proj/venv/lib/python3.9/site-packages/celery/bootsteps.py", line 112, in start self.on_start() File "/Users/proj/venv/lib/python3.9/site-packages/celery/apps/worker.py", line 136, in on_start self.emit_banner() File "/Users/proj/venv/lib/python3.9/site-packages/celery/apps/worker.py", line 170, in emit_banner ' \n', self.startup_info(artlines=not use_image))), File "/Users/proj/venv/lib/python3.9/site-packages/celery/apps/worker.py", line 232, in startup_info results=self.app.backend.as_uri(), File "/Users/proj/venv/lib/python3.9/site-packages/celery/app/base.py", line 1213, in backend self._local.backend = new_backend = self._get_backend() File "/Users/proj/venv/lib/python3.9/site-packages/celery/app/base.py", line 916, in _get_backend backend, url = backends.by_url( File "/Users/proj/venv/lib/python3.9/site-packages/celery/app/backends.py", line 70, in by_url return … -
Anonymous user for settings.AUTH_USER_MODEL in django model
Both registered and anonymous users can upload files. The UserFile model has an owner attribute connected to the AUTH_USER_MODEL. Thus, for registered users, when creating a new UserFile object, the owner attribute references self.request.user. Ideally, each file upload by an anonymous user would be accessible only by that anonymous user, and only for the length of time that the anonymous user's browser session is active. How can the owner attribute of UserFile be set such that the anonymous user can be referenced with it later? model: class UserFile(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.CASCADE, blank = False, null = False) file = models.FileField( upload_to = 'uploads/', validators = [ FileExtensionValidator(allowed_extensions = ['txt', 'doc', 'odt']) ] ) For example (pseudocode): UserFile.objects.filter(owner__exact = <anonymous user tied to browser session XYZ>) As an aside, in the future, ideally the anonymous user could login or register, at which point the owner attribute on any UserFile they own would be set to that registered user. -
GET endpoint with comma separated UUIDs Django
I am new to Django. I am trying to add endpoint which gives user details back, with provided user ids. The endpoint url should look like /users/?id=user1_id,user2_id... I already have a url and viewset for /users/. However I want to add a new one. I am able to write a code in viewset with get_queryset() which give me expected result. But I am not sure how do I add a url pattern for /users/?id=user1_id,user2_id... request, which should call the new viewset. Can anynone help me with understand what can I use here? -
Error with Django application on Cloud Run using Cloud SQL PostgreSQL DB - cannot connect to database
I have this Django project on Google Cloud on Cloud Run. It is supposed to connect to the Cloud SQL PostgreSQL database and work, but it doesn't. Here is the database part of settings.py (I have removed the private data): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': 'user', 'PASSWORD': 'password', 'HOST': '/cloudsql/project:europe-west4:instance', 'PORT': '5432', } } However, when I try to do anything database-related (for example, log in), it throws the error OperationalError at /accounts/login/ could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/cloudsql/*project*:europe-west4:*instance*/.s.PGSQL.5432"? If I remove the /cloudsql/ from HOST it gives the error OperationalError at /accounts/login/ could not translate host name "*project*:europe-west4:*instance*" to address: Name or service not known When I use the Cloud SQL proxy exe to test on my local computer it works. However, when I deploy it to Cloud Run it doesn't. -
Django show me an incorrect date due to time zone
I have a model in django that stores datetime fields: class Trip(models.Model): departureDate=models.DateTimeField() arrivalDate=models.DateTimeField() duration=models.IntegerField() #in seconds price=models.FloatField() I have introduced this datetime: 2021-05-18 12:29:00+02:00 2021-05-18 13:19:00+02:00. When I show it in the view, I see hour and minute 11:19. I have this in settings: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I need to show hour and minute 13:19, but I don`t want to put UTC=False. Thank you. -
where to find graphql graphene django api tutorial for basic
I have Django jwt script which is for graphene and when I write this installed backend creates user but I don't understand how to make registration form to fill field and send like this any small explained or documentation cant find ? thanks mutation { register( email: "email", username: "user", password1: "1234f56super", password2: "1234f56super", ) { success, errors, token, refreshToken } } -
Django Pillow Shrink Image AWS ignore Jpeg
This is an image shrinker from django import forms from .models import Card from django.core.files.storage import default_storage as storage from PIL import Image class CardForm(forms.ModelForm): class Meta: model = CARD fields = ('photo1',......) def save(self, *args, **kwargs): card = super(cardForm, self).save() image = Image.open(card.photo1) storage_path = storage.open(card.photo1.name, "wb") image.save(storage_path, "jpeg", quality=10, optimize=True) # set to png or aws ignores the code storage_path.close() return card It seems AWS does not accept jpeg in the above code, it is ignored in AWS(eg file size and quality won't change), But works locally, It's so weird, Why? And if i change it to storage_path, "png", then it works, But if i set it to png, Pillow would double the size of that png file, Which is also weird since i'm building a size shrinker and set only a 10th of it's original quality, I also prefer not to crop the image, what are my opinions? -
I'm getting an odd error when testing models
I have two models I am trying to write some tests around but getting an error ONLY when the 2nd test stub is added. Error Creating test database for alias 'default'... System check identified no issues (0 silenced). ..E ====================================================================== ERROR: test_project_details (projects.tests.ModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/chriscummings/Desktop/avenue/projects/tests.py", line 27, in test_project_details project = Project.objects.get(pk=1) File "/Users/chriscummings/.local/share/virtualenvs/avenue-5F5WKxqz/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/chriscummings/.local/share/virtualenvs/avenue-5F5WKxqz/lib/python3.8/site-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( projects.models.Project.DoesNotExist: Project matching query does not exist. ---------------------------------------------------------------------- Ran 3 tests in 0.292s Tests from django.test import TestCase from .models import Project, Parcel class ModelTest(TestCase): def setUp(self): self.project_details = { 'code': 'P0023213', 'state': 'SC', 'county': 'Lexington/Richland', 'description': 'A road widening.' } self.project = Project(**self.project_details) self.project.save() self.parcel_details = { 'code': '00342-34-244', 'owner': 'John Smith Inc.', 'site_address': '123 Main St', 'mailing_address': 'P.O. Box 42353' } self.parcel = Parcel(**self.parcel_details) self.parcel.save() def test_project_details(self): project = Project.objects.get(pk=1) self.assertEqual(project.code, self.project_details['code']) self.assertEqual(project.state, self.project_details['state']) self.assertEqual(project.county, self.project_details['county']) self.assertEqual(project.description, self.project_details['description']) print(project.description) # Prints fine if I comment out the next test. def test_parcel_details(self): # Commenting this out makes error go away. self.assertEqual(0,0) Models from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse class Project(models.Model): code = models.CharField(max_length=50) state = models.CharField(max_length=4) county … -
DJango mysite/urls.py not including correctly
I am currently trying to write my first DJango following this tutorial: https://docs.djangoproject.com/en/3.2/intro/tutorial01/ I ran into an issue where I get a page not found at /. My mysite/urls.py is the following: urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] And polls.urls.py: urlpatterns = [ path('', views.index, name='index'), ] However, if I change this in settings.py ROOT_URLCONF = 'mysite.urls' to ROOT_URLCONF = 'polls.urls' It works. What am I doing wrong, I am literally following the tutorial. -
Saving and Updating data in Django
I have a form. The form has many text fields and those text fields hold some data that is stored in the database. This means that every time that form is opened, all the fields have the previous data. In the form, a user can edit the old text fields, create new text fields and delete the existing text fields. When the form submits, all the data in the form is saved to the database. As of now, to save the data to the database, I'm first deleting the old data and then saving the new data to the database. I know that this approach is not optimal because deleting all the data for a minor change and then saving the whole data again doesn't make any sense. Possible events User might edit some existing fields User might create some new fields User might delete some existing fields User might not make any changes and still submit the form So, how can I handle the saving efficiently? Model from django.db import models from django.contrib.auth.models import User class Sentence(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) sentence = models.CharField(max_length = 250) Current Solution - from .models import Sentence def index(request): if request.method … -
div dropdown not showing
I am attempting to create a dropdown for a user. The problem is that it doesn't show up at all. <div class="account-wrap"> <div class="inside-account trade-sell-div"> <a class = "trade-sell-button" href="{% url 'product' %}">Trade/Sell</a> </div> {% if user.is_authenticated %} <div class = "inside-account chat-box-dropdown"> <a class="imgs-signed-in"><img style="height:45px !important;" src = "{% static "imgs/chat-box.png" %}" alt="Chat Box"></a> </div> <div class="inside-account user-dropdown"> <a class="imgs-signed-in user-icon-dropdown"><img src="{% static "imgs/user-icon.png" %}" alt="User"></a> <div class="dropdown-frame"> <div id="triangle"></div> <div class="dropdown-wrapper"> <hr> </div> </div> </div> {% else %} <div class="inside-account"> <a href="{% url 'login' %}">Login</a> </div> {% endif %} </div> css dropdown-frame{ position: absolute; height: 40rem; width: 10rem; outline: 1px solid black; } #triangle { width: 0; height: 0; content: ''; border-left: 20px solid transparent; border-right: 20px solid transparent; border-bottom: 20px solid white; } .dropdown-wrapper { right: 0; height: 40rem; width: 10rem; top: 56px; border: 1px solid red; z-index: 122; } Basically the triangle shows up on the nav bar but the part under the triangle does not show up at all. When I move the div elements outside the nav, it actually shows up. Does anyone have any explanation as to why my div dropdown-wrapper does not show up? -
Get user's last message django-postman & Rest API
I've been install Django-Postman user to user messaging package. I'm trying to get user's last message with Rest API. You can check django-postman package on here: https://pypi.org/project/django-postman/ A part of models.py class Message(models.Model): """ A message between a User and another User or an AnonymousUser. """ SUBJECT_MAX_LENGTH = 120 subject = models.CharField(_("subject"), max_length=SUBJECT_MAX_LENGTH) body = models.TextField(_("body"), blank=True) sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sent_messages', null=True, blank=True, verbose_name=_("sender")) recipient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='received_messages', null=True, blank=True, verbose_name=_("recipient")) sent_at = models.DateTimeField(_("sent at"), default=now) objects = MessageManager() Views.py class InboxLastMessagesViewSet(viewsets.ModelViewSet): serializer_class = InboxLastMessagesSerializer authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user return Message.objects.filter(Q(sender=user) | Q(recipient=user)).order_by('sender') Serializers.py class InboxLastMessagesSerializer(serializers.ModelSerializer): senderusername = serializers.CharField(source='sender.username', read_only=True) reciusername = serializers.CharField(source='recipient.username', read_only=True) sonmesaj = serializers.SerializerMethodField() def get_lastmessage(self, obj): /// I'M TRYING TO CREATE A FUNCTION ON HERE FOR GET SENDER'S LAST MESSAGE //// lastmsg = obj.latest('sent_at') return dict(body=lastmsg) class Meta: model = Message fields = ('senderusername', 'reciusername', 'body', 'sent_at', 'lastmessage') I want to an output like this: { "senderusername": "user", "reciusername": "user2", "body": "Actually that is not last message", "sent_at": "2019-01-19T23:08:54Z", "lastmessage": { "body": "That's conversation's last message!" } }, { "senderusername": "user", "reciusername": "user2", "body": "I said that is not last message", "sent_at": "2021-05-10T23:09:42Z", "lastmessage": { "body": "That's … -
How to add id (instead of object) in ManyToManyField of Django model?
models.py : class Employee(models.Model): name = models.CharField(max_length=100) class Department(models.Model): name = models.CharField(max_length=100) employee = models.ManyToManyField(Employee, null=True, blank=True) I need to save employee id (instead of employee object) in 'employee' ManyToManyField of 'Department' model. How to do that? views.py: dept = Department(name=name) dept.save() employee_id = 1 -
Problem with installing Pillow required version=7.1.2 with python 3.9 version
Collecting Pillow==7.1.2 Using cached Pillow-7.1.2.tar.gz (38.9 MB) Using legacy 'setup.py install' for Pillow, since package 'wheel' is not installed. Installing collected packages: Pillow Running setup.py install for Pillow: started Running setup.py install for Pillow: finished with status 'error' ERROR: Command errored out with exit status 1: command: 'C:\Users\HARSHA\PycharmProjects\car-rental-with-Django-master\venv\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\HARSHA\\AppData\\Local\\Temp\\pip-install-ws324_km\\pillow_826cf519630e4aa283b7d2ea50fb4d3c\\setup.py'"'"'; __file__='"'"'C:\\Users\\HARSHA\\AppData\\Local\\Temp\\pip-install-ws324_km\\pillow_826cf519630e4aa283b7d2ea50fb4d3c\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\HARSHA\AppData\Local\Temp\pip-record-1yvbsy4q\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\HARSHA\PycharmProjects\car-rental-with-Django-master\venv\include\site\python3.9\Pillow' cwd: C:\Users\HARSHA\AppData\Local\Temp\pip-install-ws324_km\pillow_826cf519630e4aa283b7d2ea50fb4d3c\ Complete output (179 lines): C:\Users\HARSHA\AppData\Local\Temp\pip-install-ws324_km\pillow_826cf519630e4aa283b7d2ea50fb4d3c\setup.py:42: RuntimeWarning: Pillow 7.1.2 does not support Python 3.9 and does not provide prebuilt Windows binaries. We do not recommend building from source on Windows. warnings.warn( running install running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\PIL copying src\PIL\BdfFontFile.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\ContainerIO.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\CurImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\ExifTags.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\features.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\FitsStubImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\FliImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\FontFile.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.win-amd64-3.9\PIL copying src\PIL\GdImageFile.py -> build\lib.win-amd64-3.9\PIL … -
Sending authtoken to react app from django app
I have a multi-page Django application that uses React for one part of the application. The react app gathers data and then sends a post request back to Django to store the data in the db. I am trying to implement authentication with auth-tokens so only users with specific permissions can send API requests. But since the rest of the front-end is built with Django templates including the login, I need to securely send the auth token to the react app so that the user can make api requests if they are logged in. I'm not really sure how to go about doing this without doing something really insecure (like sending the token through the URL). Does anyone know of an approach that would work for this? -
How to make a separate withdrawal of the rating sum from the button in js?
The problem arose in ignorance of js. Please help me to display the counter separately so that it updates when pressed, as it is now, but was not inside the button tag. <button class="btn-like up" data-id="{{ post.id }}" type="button" data-type="f" data-action="rate_up"> <i class="bi bi-chevron-up"></i> <div id="spinner" class="d-none"> <i class="bi bi-arrow-repeat"></i> </div> </button> <span data-count="total_rating"> {{ post.total_rating }} </span> When it is alone, it does not update the rating digit when clicked. $('.btn-like.up').submit('click', function(e) { e.preventDefault() let ratingBox = $(this).data('id') let postType = ratingBox.data('type') let postId = ratingBox.data('id') let totalRating = ratingBox.find('[data-count="total_rating"]')#only works internally. If you do it through the getelementarybyid, it doesn't work, even on the whole page. $.ajax({ type: 'POST', url: '/system/' + postType + '/' + postId + '/rate_up/', data: { 'post_id': postId, 'csrfmiddlewaretoken': csrftoken }, success: function(response) { totalRating.text(response.total_rating); }, error: function(error) { console.log(error); }, }) }) -
Cannot SSH into EC2 Instance
I've been running a Django app on an EC2 instance and have been able to SSH into it for the past few weeks. Last week I had an incident where I wasn't able to connect to the instance. I took all the steps I knew of (i.e. verifying my inbound rules for a TCP at Port 22, checking VPC for a 0.0.0.0/0 destination in my route table). The remedy I found was to reboot my instance and I didn't have a problem until last night. Since last night, I have been locked out of my instance -- I tried rebooting the instance and stopping it for several hours. Even when I go to the session manager it says that it could not establish a connection. What should I do? I have not set up anything like firewalls because I'm still only in development so the problem shouldn't be something with UFW configuration. -
Django Admin Model List Render
I have this Django App that has been working pretty well, but lately, when I login into the admin area and click on any model, it takes me to the same model list page but the rendering seems pretty awkward. Example: This is the admin page where all models are listed The normal way is f I click any model it should take me to the list of records. But thhis is what really happens if I click any model. I can't see anything wrong on the code and logs. Hope you can help me.