Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket 404 error after deploying to the domain
I setup websockets (chat module) in my Django application, it is working fine on my local machine but when I deployed my app to amazon ec2 instance with containerization it says 404 Not Found while testing via the postman. My ASGI container logs also say the same: WARNING Not Found: /chat/1/ IP:47942 - - [XX:XX:XX] "GET /chat/1/" 404 4479 Note that there is no problem with Docker containers - I tried on containers too on my local machine, and it worked. I have asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cruze_development.settings') application = get_asgi_application() from cruze_development.middleware import JWTAuthMiddleware from cruze_development.consumers import ClubFeedConsumer, RideLocationConsumer application = ProtocolTypeRouter({ "http": application, "websocket": JWTAuthMiddleware( URLRouter([ path('ws/chat/<str:room_name>/', ClubFeedConsumer.as_asgi()), path('ws/location/<str:ride_id>/', RideLocationConsumer.as_asgi()), ]) ), }) wss://mydomain.com/ws/chat/1/ I am trying with both ws and wss Help me solve it, man! -
ODBC Driver 18 Heroku Django connection
I have database (Azure SQL) which I need to interact with on my Django backend and also I do have credentials like client id, client secret, tenant id. So basically I'm connecting via Azure App to this database. I run into a problem when Heroku on its side doesn't have ODBC Driver 18 installed so I followed https://github.com/matt-bertoncello/python-pyodbc-buildpack the buildpack which pre-installs ODBC Driver 17 however I faced another issue with that where my openssl version is 3.0 or something but it requires maximum of 1.1, anyway if this issue is settled I still left with ODBC Driver 17 version which makes impossible to connect via Azure APP credentials, so only ODBC Driver 18 would work for me. My question is simple, does anyone tried to do the same with heroku and Azure SQL, can you just share steps you take to connect to this database, also are you using VPN for backend? Cuz it seems like proxies can't handle the connection for db as well. Lmao, so many questions asked sorry about that, hope to find the answer here. Stackoverflow seems to be almost empty on that sort of questions, read around 10 posts related to this topic none … -
SSL: CERTIFICATE_VERIFY_FAILED when submitting forms in Django run on Windows VPS with Apache web server
I have a Django website hosted on a VPS (OS Windows server 2019). The web server is Apache 2.4 and Python version is 3.12.8. A Digicert SSL certificate successfully installed and the website is working in production under https. However, I get this error when I try to submit a login or signup form from the website in production: URLError at /login-page/ <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)> Here is the complete error traceback: URLError at /login-page/ <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)> Request Method: POST Request URL: https://www.mywebsite.com/login-page/ Django Version: 5.0.6 Exception Type: URLError Exception Value: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)> Exception Location: C:\Python 3.12.8\Lib\urllib\request.py, line 1347, in do_open Raised during: users_authentication.views._wrapped_view Python Executable: C:\Apache24\bin\httpd.exe Python Version: 3.12.8 Python Path: ['C:\\Apache24\\htdocs\\project', 'C:\\Python 3.12.8\\python312.zip', 'C:\\Python 3.12.8\\DLLs', 'C:\\Python 3.12.8\\Lib', 'C:\\Apache24\\bin', 'C:\\Python 3.12.8', 'C:\\Python 3.12.8\\Lib\\site-packages'] C:\Python 3.12.8\Lib\urllib\request.py, line 1344, in do_open h.request(req.get_method(), req.selector, req.data, headers, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … C:\Python 3.12.8\Lib\http\client.py, line 1336, in request self._send_request(method, url, body, headers, encode_chunked) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … C:\Python 3.12.8\Lib\http\client.py, line 1382, in _send_request self.endheaders(body, encode_chunked=encode_chunked) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … C:\Python 3.12.8\Lib\http\client.py, line 1331, in endheaders self._send_output(message_body, … -
Account Merging with Google Login and Normal Registration
In my Django project, I have both normal registration and Google login. If a user registers normally and provides their email, and then tries to log in with Google using the same email, the classic login screen appears. What I want is this: If a user logs in with Google first and then tries to log in with the same email via normal registration, or if they register normally and later try to log in with Google using the same email, I want both methods to lead to the same account. In other words, regardless of whether they log in with Google or normal registration, the user's information should be merged and they should access the same account in both cases. socal login sections in settings.py: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '<722444511487-2i7e9u3urlugcp2cp6slp09jjg7kgdg3.apps.googleusercontent.com>' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '<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>' SOCIALACCOUNT_LOGIN_ON_GET=True ACCOUNT_UNIQUE_EMAIL = True EMAIL_VERIFICATION_METHOD = 'email' # settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 # TLS GENELLİKLE 587 PORTUNU KULLANIR SSL İSE GENELLİKLE 465 PORTUNU KULLANIR EMAIL_USE_TLS = True # TLS SSL'E GÖRE DAHA MODERN VE GÜVENLİDİR EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' views.py: def loginUser(request): if (request.user.is_authenticated): messages.error(request,"Giriş Yapılıyken Giriş Yapamazsın!") return redirect("index") form = LoginForm(request.POST or None) if (form.is_valid()): login(request,form.cleaned_data["user"]) messages.success(request,"Başarıyla Giriş … -
How to move django models to new server
I have two options and not know which is the best: 1 - After coping Django files, delete migration files, so after makemigrations and migrate tables will be created. And after that import dumped database (only data). or 2 - Import dumped database (full), everything (create tables and data). -
I got this error while solving some issues in my project
Traceback (most recent call last): File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024\admin\files.py", line 1, in from rest_framework.authtoken.models import Token File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\rest_framework\authtoken\models.py", line 9, in class Token(models.Model): File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\rest_framework\authtoken\models.py", line 15, in Token settings.AUTH_USER_MODEL, related_name='auth_token', ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\django\conf_init_.py", line 81, in getattr self.setup(name) File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\django\conf_init.py", line 61, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting AUTH_USER_MODEL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
'WSGIRequest' object has no attribute 'get' django 5.1.4
hey guys im new to django and in my first project i trying to save the cart of a visitor in session when i try to add some product in cart of session i have this error says < WSGIRequest object has no attribute 'get' i use a class for cart in my project and in init i check if 'cart' exists in session or no then create a key for 'cart' like this : in class Cart: class Cart: def __init__(self, request): """ Initialize The Cart """ self.request = request self.session = request.session cart = self.session.get('cart') if not cart: cart = self.session['cart'] = {} self.cart = cart # add a product to session cart: def add(self, product, quantity=1): """ Add The Specified Product To The Cart If Exists """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': quantity} else: self.cart[product_id]['quantity'] += quantity self.save() i also use another way for check if 'cart' exists in session: if 'cart' not in request.session: self.cart = self.session['cart'] = {} and still have the same issue... form for using the cart: class AddToCartProductForm(forms.Form): QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 30)] quantity = forms.TypedChoiceField(choices=QUANTITY_CHOICES, coerce=int, label=_('Quantity')) view: def add_to_cart_view(request, product_id): … -
I HAVE SOME QUESTION FOT PYTHON DJANGO ERROR
Django error Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON.How could i solve this error for website development when it return 500 error code. solution of bug for django developing -
How Can a Beginner Web Developer Start Getting Clients Without Prior Experience?
I'm a 16-year-old self-taught web developer. I’ve been learning technologies like UI/UX, Bootstrap, and Django. I want to start earning money by getting clients, but I’m facing some challenges: Lack of Experience: Many freelancing sites require prior experience, but I don’t have any yet. How can I overcome this chicken-and-egg problem? Finding Clients: I don’t know where to look for my first client or how to convince someone to hire me without a portfolio of work. I’ve been trying various freelancing platforms, but I keep running into the same issue: most clients want experienced developers. For those who’ve been in this situation, how did you find your first client? Do you have advice for someone like me who is just starting out? Thank you in advance! -
Unable to Send OTP via Twilio in Django
I'm working on implementing an OTP system in my Django project using Twilio. I've successfully obtained a Twilio phone number, but the OTP message is not being sent to the user's mobile number. Below are the details of my setup: Code Implementation views.py: def send_otp_view(request): if request.method == "POST": data = json.loads(request.body) phone_number = data.get('phone_number') # Generate a random 6-digit OTP otp = random.randint(100000, 999999) # Send OTP via Twilio (or any other SMS provider) try: client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) message = client.messages.create( body=f"Your OTP is {otp}. Please use this to verify your number.", from_=settings.TWILIO_PHONE_NUMBER, to=phone_number ) # Optionally, store the OTP in a session or database request.session['otp'] = otp request.session['phone_number'] = phone_number return JsonResponse({'status': 'success', 'otp': otp}) # Return OTP for validation except Exception as e: return JsonResponse({'status': 'error', 'message': str(e)}) return JsonResponse({'status': 'error', 'message': 'Invalid request'}) def address_view(request): if request.user.is_authenticated: user_addresses = Address.objects.filter(user=request.user) if request.method == "POST": # Get the OTP from the form entered_otp = request.POST.get("otp") # Check if the OTP matches if entered_otp == str(request.session.get('otp')): # Proceed with saving the address if OTP is correct mobile = request.POST.get("mobile") email = request.POST.get("email") pin = request.POST.get("pin") region = request.POST.get("region") address = request.POST.get("address") landmark = request.POST.get("landmark") name = request.POST.get("name") … -
Django or Different Framework?
I currently have a Django application, which is using Datatables. I'm thinking about creating views to load data into the datatable but load different data on the same page (into that same datatable). This way the page doesn't have to keep refreshing for each category. My question is, doing this, I won't have much need for the Django Template other then some basic things. Is this normal to do in Django or should I be using a different framework? -
Inconsistent URL error in Django from following along to Beginner YT tutorial
As you can see in the first screenshot, /products/new isn't showing up as a valid URL although I followed the coding tutorial from YouTube exactly. For some reason there's a blank character before "new" but no blank space in the current path I'm trying to request. I don't know if that's normal or not. I'm using django version 2.1 if that matters The URL does work for products/salt/. What's weird is the URL used to be products/trending/ but I got the same error so I randomly changed the URL to salt and it started working for me. [Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products/new/ Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order: admin/ products/ products/ salt products/ new The current path, products/new/, didn't match any of these.]1 from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') def trending(request): return HttpResponse('Trending Products') def new(request): return HttpResponse('New Products')[2] from django.urls import path from . import views urlpatterns = [ path('', views.index), path('salt', views.trending), path('new', views.new)[3] -
Pylance use Django V4 after Upgrading to Django V5
I have a model like this: class Test(models.Model): a = models.TextField(null=True, blank=True) b = models.TextField(null=True, blank=True) class Meta: constraints = [ models.CheckConstraint( condition=models.Q(a__isnull=False) | models.Q(b__isnull=False), name="not_both_null", ), ] After migrating to Django V5, VS code is reporting: However the check constraint has been updated in Django V5: It feels like Pylance is using "cached" old version somehow. I have tried following ways: Update Python and Pylance extensions to the latest. Restart VS Code/reload window. Restart Pylance server. Set 'python.analysis.extraPaths' to my venv. Reinstall Pylance. Any other ways I can try? -
Make Django parse plus in url as plus
I have an url, that contains a plus: /?a=3+4. Is it possible to make Django to treat plus as plus, not as whitespace? Thank you. Django 5.1.3 -
Multiple file uploead. Getting error file upload Field 'id' expected a number but got <InMemoryUploadedFile: test image.jpg (image/jpeg)>
I have a model that has a manytomany to another model. Its a competition and the other model is sponsor images (sponsor_logo) for the competition. I'm creating a form to create a competition and all of the associated information. I keep getting this error when submitting the from and I can't figure out why. I am creating the sponsor object, assigning the appropriate fields, saving and linking to the competition model. But I get the type error on the ID. Shouldn't that pass between these objects? class Competition(models.Model): name = models.CharField(max_length=255) registration_deadline = models.DateTimeField() allowed_divisions = models.ManyToManyField(Division, related_name='allowed_competitions') allowed_weight_classes = models.ManyToManyField(WeightClass, related_name='allowed_competitions') federation = models.ForeignKey(Federation, on_delete=models.SET_NULL, null=True, blank=True) sponsor_logos = models.ManyToManyField('Sponsor', blank=True) def __str__(self): return self.name class Sponsor(models.Model): name = models.CharField(max_length=255) logo = models.ImageField(upload_to='sponsor_logos/') def __str__(self): return self.name views.py class CompetitionCreateView(LoginRequiredMixin, generic.CreateView): model = Competition form_class = CompetitionForm template_name = 'competitions/competition_form.html' success_url = reverse_lazy('competitions:competition_list') def form_invalid(self, form): print("Form is invalid") print(form.errors) return super().form_invalid(form) def form_valid(self, form): form.instance.organizer = self.request.user competition = form.save(commit=False) try: if self.request.FILES.getlist('sponsor_logos'): competition.save() for logo in self.request.FILES.getlist('sponsor_logos'): sponsor = Sponsor.objects.create( name=logo.name # Or any other suitable name ) sponsor.logo.save(logo.name, logo, save=True) competition.sponsor_logos.add(sponsor) else: competition.save() except Exception as e: return super().form_valid(form)class -
Django throwing a 403 error (CSRF Cookie not set) despite token being passed in request header from React/Vite app
So my situation is that I have a form in a react frontend trying to post some data to a Django backend. When the Django view is CSRF exempt, all functionality is fine. However, when I remove the exemption decorator, Django always throws a 403 error - CSRF cookie not set. I have verified that there is indeed a token being passed in the request header, but for some reason the 403 error is still being thrown. I found a similar thread with a similar issue (Django and React: csrf cookie is not being set in request header), however from what I saw, I was already using the suggested fixes. Firstly, I have a route set up to initially pass the CSRF token to the frontend, as follows: @ensure_csrf_cookie def get_csrf_token(request): csrf_token = get_token(request) return JsonResponse({'csrfToken': csrf_token}) Along with the following JS to request the token: const getCSRFToken = async () => { const apiUrl = import.meta.env.VITE_API_URL; const response = await fetch(`${apiUrl}getCSRFToken/`, { method: "GET", credentials: "include", }); const data = await response.json(); return data.csrfToken; }; useEffect(() => { // Fetch CSRF token on component mount getCSRFToken().then((csrfToken) => { Cookies.set("csrftoken", csrfToken); // Store the token in a cookie }); }, … -
Django SMTP Email Issue: Gmail App Password Not Working + Model Not Updating
I am working on a Django project where I need to send emails using Gmail’s SMTP server. However, even though I have set up the SMTP settings correctly and used the App Password from Google, I’m still encountering issues when trying to send emails. Additionally, the model where I store the review replies isn't updating, even after I attempt to save data to it. Here’s the full setup: What I’ve Tried: 1.SMTP Settings in settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'myapppassword' # Gmail App Password DEFAULT_FROM_EMAIL = 'myemail@gmail.com' Views: In my view, I allow vendors to reply to product reviews. When a vendor replies, the reply is saved in the ProductReview model and an email should be sent to the customer. Here’s the view code: @login_required def product_reviews(request): try: vendor = Vendor.objects.get(user=request.user) except Vendor.DoesNotExist: return render(request, 'vendorpannel/no_vendor.html') all_reviews = ProductReview.objects.filter(vendor=vendor) if request.method == "POST": review_id = request.POST.get('review_id') reply_text = request.POST.get('reply_text') if review_id and reply_text: try: review = ProductReview.objects.get(id=review_id, vendor=vendor) review.reply = reply_text # Save the reply to the model review.save() # Send an email to the customer customer_email = review.user.email subject = "Reply to Your Product Review" message … -
Django Webhook Integration with Aiogram
Overview This project integrates a Telegram bot (using Aiogram) with a Django application via a webhook. However, when running python manage.py migrate, the following error occurs: RuntimeError: Event loop is closed Unclosed client session Issue The error suggests issues with the event loop being closed prematurely and an unclosed aiohttp client session. The webhook handler processes updates from Telegram asynchronously using Aiogram, but the event loop is not managed properly in Django’s synchronous views. Code session = AiohttpSession() bot = Bot(token=settings.BOT_TOKEN, session=session, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) dp = Dispatcher() @csrf_exempt def webhook(request): if request.method == "POST": try: update_data = json.loads(request.body) update = Update(**update_data) async def process_update(): await dp.feed_update(bot=bot, update=update) loop = asyncio.get_event_loop() if loop.is_closed(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(process_update()) return HttpResponse("OK") except Exception as e: logger.error(f"Error: {e}") return HttpResponse("Bad Request", status=400) return HttpResponse("Method not allowed", status=405) ask for ChatGPT but without success. -
Django not authenticating access token
I am using JWT to authenticate users, on hitting login endpoint, I am getting the following output in my Postman { "message": "Login successful", "user_id": 2, "username": "Animesh0764", "tokens": { "refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTczNjU5MTAxNywiaWF0IjoxNzM1Mjk1MDE3LCJqdGkiOiI4YmJhMTczZmZkNDg0OWIzODU3YTZkMDE1MDZlNzM2ZCIsInVzZXJfaWQiOjJ9.-wX6S9yxNgFCjIR8Tu0FRc-Q2ivFDMVJouXkKkjDNtI", "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzM1Mjk1OTE3LCJpYXQiOjE3MzUyOTUwMTcsImp0aSI6IjdhOWU3ZDA0NTllNzQxMzFhNDM1MWVlZjVkOWRiODcyIiwidXNlcl9pZCI6Mn0.LI6afRT66MFWTpomo1E9BHn5JTrRuGoTeX0EEwMRFvQ" } } While using this access token in Bearer for Profile view, it shows: { "detail": "User not found", "code": "user_not_found" } Visited jwt.io and verified my token, everything seems okay, it shows the correct user_id but still won't verify. The views for both are given below #Login user class UserLoginView(APIView): def post(self, req): serializer = UserLoginSerializer(data=req.data) if serializer.is_valid(raise_exception=True): user = serializer.validated_data['user'] return Response({ "message": "Login successful", "user_id": user.id, "username": user.username, "tokens": get_tokens_for_user(user) }, status=HTTP_200_OK) return Response( {"message": "Login failed"}, status=HTTP_400_BAD_REQUEST ) #View user profile class UserProfileView(APIView): permission_classes = [IsAuthenticated] def get(self, req): print(f"Request user: {req.user}") print(f"User authenticated: {req.user.is_authenticated}") if req.user.is_authenticated: user = req.user serializer = UserProfileSerializer(user) return Response(serializer.data, status=HTTP_200_OK) return Response({"message": "Unauthorized"}, status=HTTP_401_UNAUTHORIZED) It should verify the token and then show the response 200 but always shows 401 Unauthorized Even added everything required in settings.py file -
OSError: ctypes.util.find_library() did not manage to locate a library called 'libharfbuzz-0' on MacBook M2 when using WeasyPrint
I'm encountering the following error when trying to use WeasyPrint in a Python project on my MacBook M2: OSError: ctypes.util.find_library() did not manage to locate a library called 'libharfbuzz-0' Here’s what I’ve done so far: I installed harfbuzz using Homebrew: brew install harfbuzz I confirmed that the library exists in the /opt/homebrew/Cellar/harfbuzz/10.1.0/lib/ directory, and the files are present, such as libharfbuzz.0.dylib I tried copying the .dylib files to /usr/local/lib/, but the error still persists I also checked the environment variables and the library path, but WeasyPrint is still unable to locate the required libharfbuzz library Is there a specific configuration or environment variable that I need to set on macOS to make WeasyPrint work properly on a MacBook M2? -
VScode remote debuger exits after change to django code?
I have configured vscode to debug my django application inside a docker container. It works well, but after I change my code, the debugger exits with the following message [error image] The exception message: Exception has occurred: SystemExit (note: full exception trace is shown but execution is paused at: <module>) 3 File "/mnt/gb10/work_projects/albaraka/albaraka_backend/src/manage.py", line 28, in main execute_from_command_line(sys.argv) ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^ File "/mnt/gb10/work_projects/albaraka/albaraka_backend/src/manage.py", line 32, in <module> (Current frame) main() ~~~~^^ SystemExit: 3 Here is my launch.json file { "configurations": [ { "name": "Python Debugger: Remote Attach", "type": "debugpy", "request": "attach", "connect": { "host": "0.0.0.0", "port": 8002 }, "pathMappings": [ { "localRoot": "${workspaceFolder}/src", "remoteRoot": "/code" } ] } ] } Here is my manage.py file import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'albserver.settings') # Debugger from django.conf import settings if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import debugpy debugpy.listen(("0.0.0.0", 8002)) print('Attached!') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() and docker-compose file services: alb-web: container_name: alb-web build: ./src command: python -Xfrozen_modules=off manage.py runserver … -
Is there any benefit to using `URLValidator` on a django `URLField`
Is there any benefit to using URLValidator on a django URLField in models.py or does the URLField already do all the necessary validation? Also is it recommended to use it to enforce https? For example: from django.core.validators import URLValidator class Processor(models.Model): website = models.URLField( max_length=250, blank=True, null=True, validators=[URLValidator(schemes=['https'])] # Enforce HTTPS ) -
Dropdown works with Tailwind CDN but doesn't work with PostCSS
I am trying to integrate TailwindCSS with my Django project using PostCSS. Here are the configurations I’m using: PostCSS Configuration (postcss.config.js) module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, }; Tailwind Configuration (tailwind.config.js) /** @type {import('tailwindcss').Config} */ module.exports = { content: [ // Include all Django HTML and template files "./templates/**/*.html", // Templates at the project level "./**/templates/**/*.html", // Templates inside apps "./static/**/*.js", // JavaScript files in the static folder "./**/static/**/*.js", // JavaScript files in app-level static folders ], theme: { extend: { // Customizations for your design colors: { primary: "#1d4ed8", // Example custom color secondary: "#9333ea", }, fontFamily: { sans: ["Inter", "sans-serif"], // Example custom font }, }, }, plugins: [], }; Tailwind CSS File (static/css/tailwind.css) @tailwind base; @tailwind components; @tailwind utilities; 4. HTML Template Example (index.html) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Add Task - TaskMaster</title> {% comment %} <link rel="stylesheet" href="{% static 'css/output.css' %}"> {% endcomment %} <script src="https://cdn.tailwindcss.com"></script> </head> <body class="font-sans bg-gray-100"> <!-- Content of the page --> <header class="bg-white shadow-md"> <nav class="container mx-auto px-6 py-3"> <div class="flex justify-between items-center"> <a href="index.html" class="text-xl font-bold text-gray-800">Taskify</a> <!-- Other navigation elements --> </div> </nav> </header> <main … -
Can I create a many to many relation using a junction table with a junction table
I want to create a m2m relation between two tables and one of the table is a junction table for m2m relation. So basically, I have 3 tables and 2 can be joined using a m2m. But in order to join three tables, I have two options, one is to create a m2m with the third table and the already created junction table and the other approach is to create a table which has foreign key of all the three tables. Which of the above approach is suitable. The two approaches to implement table with relation to three tables are: CREATE TABLE PromoPrizeScreen ( id SERIAL PRIMARY KEY, prize_cap INTEGER DEFAULT NULL, prize_used INTEGER DEFAULT NULL, promo_prize_id INTEGER NOT NULL, screen_id INTEGER NOT NULL, FOREIGN KEY (promo_prize_id) REFERENCES PromoPrize (id) ON DELETE CASCADE, FOREIGN KEY (screen_id) REFERENCES Screen (id) ON DELETE CASCADE ); CREATE TABLE PromoPrizeScreen2 ( id SERIAL PRIMARY KEY, prize_cap INTEGER DEFAULT NULL, prize_used INTEGER DEFAULT NULL, promo_id INTEGER NOT NULL, prize_id INTEGER NOT NULL, screen_id INTEGER NOT NULL, FOREIGN KEY (promo_id) REFERENCES Promo (id) ON DELETE CASCADE, FOREIGN KEY (prize_id) REFERENCES Prize (id) ON DELETE CASCADE, FOREIGN KEY (screen_id) REFERENCES Screen (id) ON DELETE CASCADE ); I … -
ERROR: Failed building wheel for psycopg2-binary
Using cached psycopg2-binary-2.9.10.tar.gz (385 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: psycopg2-binary Building wheel for psycopg2-binary (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [32 lines of output] running bdist_wheel running build running build_py creating build\lib.win-amd64-cpython-313\psycopg2 copying lib\errorcodes.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\errors.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\extensions.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\extras.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\pool.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\sql.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\tz.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\_ipaddress.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\_json.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\_range.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\__init__.py -> build\lib.win-amd64-cpython-313\psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build\temp.win-amd64-cpython-313\Release\psycopg "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.42.34433\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD "-DPSYCOPG_VERSION=2.9.10 (dt dec pq3 ext lo64)" -DPSYCOPG_DEBUG=1 -DPG_VERSION_NUM=170002 -DHAVE_LO64=1 -DPSYCOPG_DEBUG=1 -IC:\Users\hello\memesite\myenv\include "-IC:\Program Files\Python313\include" "-IC:\Program Files\Python313\Include" -I. -IC:/PROGRA~1/POSTGR~1/17/include -IC:/PROGRA~1/POSTGR~1/17/include/server "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.42.34433\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" /Tcpsycopg\adapter_asis.c /Fobuild\temp.win-amd64-cpython-313\Release\psycopg\adapter_asis.obj adapter_asis.c C:\Program Files\Python313\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and …