Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python: Auto-update a field in database
I want the database to automatically update the status field when the date already passed. For example the date for the event was yesterday, and I don't want to update the status myself. Is it possible for database to automatically change the status? models.py class Events(models.Model): id = models.AutoField(db_column='id', primary_key=True) title = models.CharField(max_length=45, blank=True, null=True) venue = models.CharField(max_length=45, blank=True, null=True) date = models.DateTimeField(max_length=45, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) image = models.ImageField(upload_to=eventpath, blank=True, null=True) date_posted = models.CharField(max_length=45, blank=True, null=True) status = models.CharField(max_length=45, blank=True, null=True) -
How I can run django cronjob function on windows?
I'm developing a Django application which fetches an external API and stores information from that API to a local Django model so I have set a cronjob to automatically fetch and store data within some period of time. but the problem is this that cronjobs don't work on windows. So is there any way I can test my function that it will work on production on linux server. (I'm not using windows task scheduler because I'll have to host it on linux based server.) Any help will be appreciated! -
Django : ValueError at / The 'avatar' attribute has no file associated with it
Django sends me the following error: ValueError at / The 'avatar' attribute has no file associated with it. enter image description here The message appears just after I log in, even though I uploaded an avatar when I registered a dummy profile. I can't even find the avatar in the configured path: media/avatars. Could you help find where I got this wrong please? Bellow is my code. **models.py: ** from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): (some code) avatar = models.ImageField(upload_to='avatars/',blank=True, null=True) **forms.py: ** class RegisterForm(UserCreationForm): (some code) avatar = forms.ImageField( required=False, widget=forms.ClearableFileInput( attrs={ "class": "form-control" } ) ) class Meta: model = User fields = ['username','first_name','last_name','email','avatar','password1','password2','user_type'] **settings.py: ** STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_DIR = BASE_DIR / 'media' STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / 'media' I added this in urls.py of the main project directory: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And finally, the path of where I want the avatars to be uploaded: mainProject ├── media │ ├── avatars Thank you very much for any help I tried to make all the uploaded avatars go to media/avatars. I even made conditions where there is a placeholder image in case the user … -
Could not find module 'C:\OSGeo4W\bin\gdal308.dll' (or one of its dependencies)
I'm trying to use GeoDjango + gdal + PostGis in order to create a map application. OSGeo4W is completelly installed, and all the dll files are there When I run this command: python3 manage.py check I get the following result: ^^^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: Could not find module 'C:\OSGeo4W\bin\gdal308.dll' (or one of its dependencies). Try using the full path with constructor syntax. However the files are correctly existing in the location. Here is how my settings file looks like, for the gdal part: if os.name == 'nt': OSGEO4W = r"C:\\OSGeo4W" # if '64' in platform.architecture()[0]: # OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\\share\\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\\share\\proj" os.environ['PATH'] = OSGEO4W + r"\\bin;" + os.environ['PATH'] GDAL_LIBRARY_PATH = OSGEO4W + r"\\bin\\gdal308.dll" Could someone who has gone through this please help me shed some light over it? -
View in django not running
I have a Django project where I'm trying to activate a user's account when they reset their password. I've created a custom view ActivateUserPasswordResetConfirmView that inherits from PasswordResetConfirmView and overrides the form_valid method to set user.is_active = True. However, the form_valid method in my custom view does not seem to be called when a user resets their password. I've checked my URL configurations and they seem to be correct. Here are the relevant parts of my code: views.py: from django.contrib.auth.views import PasswordResetConfirmView class ActivateUserPasswordResetConfirmView(PasswordResetConfirmView): def form_valid(self, form): user = form.save() user.is_active = True user.save() return super().form_valid(form) myapp/urls.py: from django.urls import path from .views import ActivateUserPasswordResetConfirmView urlpatterns = [ path('reset/<uidb64>/<token>/', ActivateUserPasswordResetConfirmView.as_view(), name='password_reset_confirm'), # other urls... ] project/urls.py: from django.urls import include, path urlpatterns = [ path('', include('myapp.urls')), path('accounts/', include('django.contrib.auth.urls')), # other urls... ] I have also added logging in the form_valid method, but I don't see any log messages when testing the password reset flow, which suggests that the method is not being executed. Any ideas on why the form_valid method is not being called or how I can debug this issue further? -
Technical question: Building API using python in real time connection + authentication
I need to build an API that will be called from Android, iOS and desktop clients using framework like flutter The problem i am facing is that i need to build an APIs that relies on HTTPS request/response that uses JSON format using python and offer some features like authentication, authorization, database storing, static files storing like.png and .pdf and some parts should work in real time connection for chat system but i don't know what should i use. Because i am stacked in multiple options like Django, RESTful and channels frameworks So my questions are Is there a way to combine all those technologies or should i choose one of them and work with them? Is there a better way to do the listed features up? -
SMTPSenderRefused Error Django: (501, b'<settings.EMAIL_HOST_USER>: sender address must contain a domain', 'settings.EMAIL_HOST_USER')
I am working on a Django project. I have a contact form. What I want when someone fills up the form my info@mydomain.com should send my gmail a notification like "Someone filled up your form". When i go to contact form and submit it, there is an error page that says: SMTPSenderRefused at /contact/ (501, b'<settings.EMAIL_HOST_USER>: sender address must contain a domain', 'settings.EMAIL_HOST_USER') Django Version: 5.0.2 Exception Type: SMTPSenderRefused Exception Value: (501, b'<settings.EMAIL_HOST_USER>: sender address must contain a domain', 'settings.EMAIL_HOST_USER') Exception Location: C:\Users\Bedirhandd\AppData\Local\Programs\Python\Python311\Lib\smtplib.py, line 887, in sendmail And here is my codes: Settings.py # EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_BACKEND = 'backend.email.EmailBackend' EMAIL_HOST = 'mail.info@mydomain.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'info@mydomain.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'Mydomain <info@mydomain.com>' backend.email file: (I created the email_backend.py file to avoid "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain" error. I found the code here import ssl from django.core.mail.backends.smtp import EmailBackend as SMTPBackend from django.utils.functional import cached_property class EmailBackend(SMTPBackend): @cached_property def ssl_context(self): if self.ssl_certfile or self.ssl_keyfile: ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) ssl_context.load_cert_chain(self.ssl_certfile, self.ssl_keyfile) return ssl_context else: ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE return ssl_context And lastly here is my views.py: from django.shortcuts import render from portfolio.models import Portfolio from … -
Can anybody help me find a work remotely? [closed]
Hi hope you all doing well and you don't meet bugs indeed Im quite good at django i can say that im a full-stack with a solid python & JavaScript background. Please get in touch if you have any collaborative opportunities. Peace ✌️. Post. On LinkedIn and other platforms that offers remotes jobs ? -
Dynamic routing not working as expected in Nextjs
I am trying to create a dynamic route in nextjs but I am getting page not found error The page loads only when I give the url with the exact pathname of the page I have a Django Backend server set up I just call The RestApis Here is the error Error Screen here is the page when I pass the exact url enter image description here This is how I created the route in the app directory app/something/[id] And this is the screen I want to render page.tsx I am expecting to a dynamic url from where i can extract the id through params -
Need some advice on Phusion/Passenger setup
Okay, so.. I've never used this set of programs, so please be nice. I help a guy out with his hosted application on dreamhost. I mostly edit some HTML and python. However, it's pretty legacy and it's running phusion/passenger. It's a django site, but I don't think it's "deployed correctly" with django. Typically, I copy everything locally, make edits and run the application manually with something like: python manage.py runserver 0.0.0.0:8000 --verbosity 3 I then just copy over the changes.. However, some of the python modules are REALLY old. I wanted to try and update them. When I update django in my dev environment the application works fine. However, when I update django on the dreamhost environment the application bombs. (I do not have the exception handy) So, I want to more accurately reproduce this environment. I've built a docker container with apache, passenger, etc. I'd like to figure out how to put this application into the passanger environment so I can reproduce the environment. But I simple don't know how - and the amount of Googling i've done has not helped. -
Django: Set initial value of dropdown in form based on value in model
I am working on a ticketing web application using Django as a university. In there, assignees (tutors) need to be able to asign another tutor and change the status of the ticket ("Open", "In progress", ...). The current tutor and the current status is saved in the Ticket model: class Ticket(models.Model): creator = models.ForeignKey( Student, null=True, on_delete=models.SET_NULL ) assignee = models.ForeignKey( Tutor, on_delete=models.SET_NULL, blank=True, null=True ) current_status = models.CharField( max_length=2, choices=KorrekturstatusEnum.choices, default=KorrekturstatusEnum.OFFEN, ) description = models.TextField( default="Please provide as much detail as possibile." ) The life cycle of a ticket is saved in the Messages model: class Messages(models.Model): class ChangeTypeENUM(models.TextChoices): OPEN = "01", "Open" ASIGNMENT = "02", "Asignment" STATUS_CHANGE = "03", "Status change" MESSAGE = "04", "Message" class SenderENUM(models.TextChoices): TUTOR = "01", "Tutor" STUDENT = "02", "Student" student = models.ForeignKey( Student, on_delete=models.SET_NULL, null=True, related_name="student_messages", ) tutor = models.ForeignKey( Tutor, on_delete=models.SET_NULL, related_name="tutor_messages", null=True, blank=True, ) ticket = models.ForeignKey( ticket, on_delete=models.CASCADE, related_name="korrektur_messages" ) text = models.TextField(null=True, blank=True) created_at = models.DateTimeField(default=timezone.now) sender = models.CharField( max_length=2, choices=SenderENUM.choices, default=SenderENUM.STUDENT ) status = models.CharField( max_length=2, choices=KorrekturstatusEnum.choices, default=KorrekturstatusEnum.OFFEN, ) change_type = models.CharField( max_length=2, choices=ChangeTypeENUM.choices, default=ChangeTypeENUM.EROEFFNUNG, ) Changes to a ticket, including messages/comments are done by a from, I'm using a model form here. I am trying to … -
Add dynamic fields through django admin
I've looked around the stack but I cant find any answers. So I have a model like this: class DynamicModel(models.Model): config = models.JSONField() def __str__(self): return self.config what I want to do here now is to show the json field key-value pairs as standalone fields and also be able to edit them in the same way, like if they were each one a different field. This was the best way I could come up to create dynamic fields. So if I have a jsonfield like this: { "age": 23, "name": "John Doe", "gender": "Male" } I would have an `Age` field where I can edit the value or even remove the field alotgether. The changes would then reflect to the `JSONField`. My approach is like this: # forms.py from django import forms from .models import DynamicModel class DynamicModelForm(forms.ModelForm): class Meta: model = DynamicModel fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Check if 'config' is in the fields if 'config' in self.fields: # Extract JSON data from the instance or initialize an empty dictionary json_data = self.instance.config if self.instance and 'config' in self.instance else {} # Loop through the JSON data and add individual fields for key, value … -
AttributeError: type object 'Token' has no attribute 'objects'!, How to solve it?
I am trying to create a custom user blog API using class based views and token authentication. But both my register view and login view are not working properly. when I try to register user it throws an Attribute error and when I try to login it says "Method Not Allowed: /register/ [15/Feb/2024 22:36:47] "GET /register/ HTTP/1.1" 405 13614" I think I have made some mistakes on my views file but it seems like I am stuck and cant move ahead with this error. I also tried chatgpt but it was of no use, please help. this my github link for the repo https://github.com/Rohit10jr/cbv_blog_token_auth this is my register and login views class RegistrationAPIView(generics.CreateAPIView): queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer permission_classes = [AllowAny] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = self.perform_create(serializer) token, created = Token.objects.get_or_create(user=user) headers = self.get_success_headers(serializer.data) return Response({'token': token.key, 'user': serializer.data}, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): return serializer.save() # return super().perform_create(serializer) # return super().perform_create(serializer) class LoginAPIView(generics.CreateAPIView): serializer_class = CustomUserSerializer permission_classes = [AllowAny] allowed_methods = ['POST'] # Allow both POST and GET requests def create(self, request, *args, **kwargs): email = request.data.get('email') password = request.data.get('password') user = authenticate(request, email=email, password=password) if user: login(request, user) serializer = self.get_serializer(user) … -
Why is my Filter not filtering the table?
In my views.py I am using class based views to show a table along with a filter and form(TO ADD new data). My previous pages have been working when I did not define any methods but for this page I need methods to work with . Please let me know why my filter is not working. Creating a new form also leads to a "'ChamberLogView' object has no attribute 'object_list'" error. If you have any idea on that please let me know. Thank You class ChamberLogView(SingleTableMixin, CreateView, FilterView): template_name = 'html/ChamberLog.html' model = ChamberLog table_class = ChamberLogTable form_class = ChamberLogForm filterset_class = ChamberLogFilter def get_table_data(self, *args, **kwargs): return ChamberLog.objects.filter(log_id = self.kwargs.get('pk')) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['ChamberLogInfo'] = ChamberLogInfo.objects.filter(pk = self.kwargs.get('pk')) return context def get_success_url(self): #print(self.pk) return HttpResponseRedirect(reverse('ChamberLog', kwargs={'pk': self.pk})) -
How do I get django to interact with html
So, I have the following question, I need to create a way for the object inserted within the field to be transferred to a within a single page but with different functions, and I managed to do this but in a way that In my opinion, it shouldn't be the best, that is, my goal is to optimize this if possible. Below is the code for the views, urls, forms, html. And detail, I don't intend to use Java, but if this is the only or best way, I'm willing to understand. #urls from django.urls import path from FrontEndProject import views urlpatterns = [ path('', views.RenderHomePage), path('test/', views.PostInfoHomePage, name='PostInfoHomePage') ] #views from django.shortcuts import render from .forms import * def RenderHomePage(request): return render(request, 'HomePageBody.html') def PostInfoHomePage(request): Info = '' if request.method == 'POST': form = FormInfo(request.POST) if form.is_valid(): Info = form.cleaned_data['PostInfo'] else: form = FormInfo() return render(request, 'HomePageBody.html', {'form': form, 'Info': Info}) #forms from django import forms class FormInfo(forms.Form): PostInfo = forms.CharField() #html <!DOCTYPE html> <html> <head> <title> Home page </title> </head> <body> <div> <form method="post" action="{% url 'PostInfoHomePage' %}"> {% csrf_token %} <input name="PostInfo" value="{{ form.PostInfo.value|default:'' }}"> <button>Take info</button> </form> <p>Information: {{ Info }} </p> </div> </body> </html> -
Saving django generated zip files
In a django project, I allow user to download multiple files as a zip file. But how do I limit the regeneration same zip content again and again? Is it bad practice to regenerate repeatedly? -
Problem when connecting Django and Flutter websockets
I'm trying to establish a connection with my Django backend and Flutter code using WebSockets, but unfortunately I'm unable to do so, went through many articles and videos and everyone is basically doing the same without receiving an error.. Please give a little push to, I'm kinda new into this. First of all I created a new django app called 'chat_app' (added it into settings.py), where I created a new model of my Messages: class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) sender = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content Then I made my consumers.py (here I'm a little bit confused, isn't it better to refer to my room unique_id instead of name, since the ID is unique and not the name in my case? Decided to stick with the tutorial.) class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group self.channel_layer.group_add( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group self.channel_layer.group_discard( self.room_group_name, self.channel_name ) Done the routing.py # The WebSocket URL pattern for chat rooms is defined by this code websocket_urlpatterns = [ re_path(r'ws/chat_app/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()), ] Then added it into my project URLs: urlpatterns = [ path('admin/', … -
CSRF Token missing when it's there
I have a form, containing different form objects inside from the forms.py. However, when I try to submit the form, it says, "csrf verification failed" Here is the full template (sorry for the mess I'll structure the js later before launch) <!DOCTYPE html> {% load static %} {% load widget_tweaks %} <html lang="en"> <head> <head> <title>{{app.name}}</title> <!-- Meta Tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="author" content="Webestica.com"> <meta name="description" content="Bootstrap 5 based Social Media Network and Community Theme"> <!-- Dark mode --> <script> const storedTheme = localStorage.getItem('theme') const getPreferredTheme = () => { if (storedTheme) { return storedTheme } return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'light' } const setTheme = function (theme) { if (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) { document.documentElement.setAttribute('data-bs-theme', 'dark') } else { document.documentElement.setAttribute('data-bs-theme', theme) } } setTheme(getPreferredTheme()) window.addEventListener('DOMContentLoaded', () => { var el = document.querySelector('.theme-icon-active'); if(el != 'undefined' && el != null) { const showActiveTheme = theme => { const activeThemeIcon = document.querySelector('.theme-icon-active use') const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`) const svgOfActiveBtn = btnToActive.querySelector('.mode-switch use').getAttribute('href') document.querySelectorAll('[data-bs-theme-value]').forEach(element => { element.classList.remove('active') }) btnToActive.classList.add('active') activeThemeIcon.setAttribute('href', svgOfActiveBtn) } window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (storedTheme !== 'light' || storedTheme !== 'dark') { setTheme(getPreferredTheme()) } }) showActiveTheme(getPreferredTheme()) document.querySelectorAll('[data-bs-theme-value]') .forEach(toggle => … -
Django not appening "/" on urls in a production server
I have a website written in Django. The website for production or development is deployed in a docker container. It is served over nginx that is also deployed in a docker container. On a development computer when the website is deployed and an address is input without a trailing "/" it is automatically appended and then redirected to the correct page. In a production server, this isn't happening. No redirection commences and the server returns 404. The only difference between development and production is that the production instance is run with SSL and a domain name. Here are my NGINX configs for both situations. Development: upstream django { server django_gunicorn:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { alias /static/; } } Production: upstream django { server django_gunicorn:8000; } server { listen 443 ssl; ssl_certificate /ssl/live/fullchain.pem; ssl_certificate_key /ssl/live/privkey.pem; server_name website.mydomain.com; location / { proxy_pass http://django; } location /static/ { alias /static/; } } What is the issue, why production server is not redirecting? -
Django: static file serve does not work only when the url is "static/"
I have the following urls.py - urlpatterns = [ path('admin/', include("admin.urls")), path('accounts/', include("accounts.urls")), path('blogs/', include("blogs.urls")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In the settings.py I have - STATIC_URL = 'static/' STATIC_ROOT = 'static/' Here my static files in the static folder are showing a "Page Not Found (404)" error. But ifI change settings.STATIC_URL to anything else, it works. For example, if I do - static("anything/", document_root=settings.STATIC_ROOT), then it works, only the strings that start with 'static' does not work. Can anyone shed some light on this behaviour? -
JavaScript does not work when running Django on the local network. In 2024
My project ( https://github.com/Aleksandr-P/django-audio-recorder2024 ) works well on a local computer under Windows 10. If I run python manage.py runserver . After making changes: ..\web_project\settings.py ALLOWED_HOSTS = [] on the: ALLOWED_HOSTS = ['*'] And python manage.py runserver on python manage.py runserver 0.0.0.0:80 JavaScript stops working. How to fix it? I checked in the browser, the file audio_recorder\static\audio_recorder\recorder.js available. But it doesn't work. -
Python social auth and drf social oauth
I need help of community. In my Django project with django-rest-framework, we use JWT authentication and want to implement the social login by google. So, I installed and configured drf-social-oauth2 with backend google-oath2 in the project as shown in docs. settings.py INSTALLED_APPS = [ ... "social_django", "oauth2_provider", "drf_social_oauth2", ... ] ... TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ... ], }, } ] REST_FRAMEWORK = { ... 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "drf_social_oauth2.authentication.SocialAuthentication", ), } AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "drf_social_oauth2.backends.DjangoOAuth2", "social_core.backends.google.GoogleOAuth2", ) SOCIAL_AUTH_REQUIRE_POST = True ACTIVATE_JWT = True SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ] SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = env( "SOCIAL_AUTH_GOOGLE_OAUTH2_KEY", default="SOCIAL_AUTH_GOOGLE_OAUTH2_KEY" ) SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = env( "SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET", default="SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET" ) urls.py urlpatterns = [ ... path("", include("social_django.urls", namespace="social")), path("auth/", include("drf_social_oauth2.urls", namespace="drf")), ] And now the question itself. How to implement redirection with the necessary data after user authorization on an external resource? I have a user's entry point with a redirect to google authorization path( "sign_in/google", views.AuthViewSet.as_view({"post": "sign_in_google"}), name="sign_in_google", ), method @extend_schema(request=None, responses={302: None}) def sign_in_google(self, request, *args, **kwargs): strategy = load_strategy(request) backend = load_backend( strategy=strategy, name="google-oauth2", redirect_uri=f"{self.request.scheme}://{self.request.get_host()}/complete/google-oauth2/", ) return do_auth(backend, REDIRECT_FIELD_NAME) And if I follow as per our requirements we need the user to redirect to google-oauth2 page and … -
Django App fails to deploy on AWS ElasticBeanstalk with pywin32==306
I am stuck here since 2 days. Someone please help. Django App works fine locally but fails to deploy on AWS ElasticBeanstalk with pywin32==306. Platform: Python 3.11 running on 64bit Amazon Linux 2023/4.0.8. I am using windows 11. Python Version : 3.12.2. PIP version : 23.3.2. Please find below requirements.txt: asgiref==3.7.2 awsebcli==3.20.10 beautifulsoup4==4.12.3 botocore==1.31.85 cement==2.8.2 certifi==2024.2.2 charset-normalizer==3.3.2 colorama==0.4.3 distlib==0.3.8 Django==4.2.10 django-bootstrap-v5==1.0.11 filelock==3.13.1 idna==3.6 jmespath==1.0.1 pathspec==0.10.1 platformdirs==4.2.0 psycopg-binary==3.1.17 psycopg2-binary==2.9.9 pypiwin32==223 python-dateutil==2.8.2 pywin32==306 PyYAML==6.0.1 requests==2.31.0 semantic-version==2.8.5 setuptools==69.0.3 six==1.16.0 soupsieve==2.5 sqlparse==0.4.4 termcolor==1.1.0 tzdata==2023.3 urllib3==1.26.18 virtualenv==20.25.0 wcwidth==0.1.9 whitenoise==6.6.0 Getting the following error: 2024/02/15 13:12:10.274129 [ERROR] An error occurred during execution of command [self-startup] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 1. Stderr:ERROR: Could not find a version that satisfies the requirement pywin32==306 (from versions: none) ERROR: No matching distribution found for pywin32==306 Complete AWS Log : https://drive.google.com/file/d/1ZbS3aVnHS2fg8-e9QDihnhzuHxB_CPDf/view?usp=sharing I upgraded the PIP and also tried pywin32==306;platform_system == "Windows" but in vain. -
How works super().get_queryset() in Django?
I am trying to get a queryset of questions that have publication date before today's date, but I am getting an error in get_queryset raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: IndexView is missing a QuerySet. Define IndexView.model, IndexView.queryset, or override IndexView.get_queryset(). My code: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return super().get_queryset().filter(pub_date__lte=timezone.now()) But this code works: def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) What I am doing wrong? Thanks in advance -
django-tailwindcss integration image not displayed
I already have a Django project with template file index.html but my image is not displaying I try everything including {% load static %} but still it is not working may be because i used {% load tailwind_tags %} and {% tailwind_css %} and i also created file as mentioned in Django official website for static file but still it is not working.