Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'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 … -
Django serializer depth doesn't serialize nested models
I use django and react and I want to make some workspaces where they have inside channel instances. Models.py class Workspace(models.Model): channels = models.ManyToManyField('Channel', related_name='channels', blank=True) Serializers.py class WorkspaceSerializer(serializers.ModelSerializer): class Meta: model = Workspace fields = '__all__' depth = 2 Views.py @api_view(['POST']) def getworkspace(request): if request.method == 'POST': workspace = Workspace.objects.filter(id=request.POST['id']).first() serializer = WorkspaceSerializer(workspace, many=False) return Response(serializer.data) Then I use axios to fetch the data axios.post('http://127.0.0.1:8000/getworkspace/', formData, {headers: {'Content-type': 'multipart/form-data'}}).then(res=>{ setWorkspace(res?.data) }) console.log(workspace) What I was expecting was for workspace channel to be serialized and me be able to access it but instead I get this {id, 1, channels: [1]} What can I do, I have changed the depth to even 10 but it still doesn't work. If I use shell and serialize it from there like this: from main.models import * from main.serializers import * workspace = Workspace.objects.filter(id=1).first() serializer = WorkspaceSerializer(workspace, many=False) print(serializer.data) It works perfectly. I believe the problem starts from the view because when I print print(serializer.data) from there channels isn't being serialized. -
Can't serve static files Django + Gunicorn + Nginx + Docker
I have the following structure on my project: -> api_solar_django --> manage.py --> api_app (where are the view.py model.py, etc) --> api_solar (where are settings.py, etc) In my docker-compose file I have the following: services: django: build: context: ./api_solar_django container_name: django-app restart: unless-stopped ports: - "8090:8090" volumes: - ./api_solar_django:/app - static_volume:/app/static environment: - DJANGO_SETTINGS_MODULE=api_solar.settings - ENC_KEY=key depends_on: - db networks: - app-network nginx: image: nginx:alpine container_name: nginx restart: unless-stopped ports: - "80:80" volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro - static_volume:/static depends_on: - django - frontend networks: - app-network networks: app-network: driver: bridge volumes: postgres_data: static_volume: The static files, inside each container is located as: Django container: /app folder, same as manage.py Nginx container: root folder My nginx.conf file is configured as: user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; # Incluindo o servidor configurado server { listen 80; # Serve arquivos estáticos do Django location /static/ { alias /static/; } # Proxy para o backend (Django) location /api/ { proxy_pass http://django-app:8090/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # Proxy para o frontend (Vue.js) location / { proxy_pass http://vue-app:5173; proxy_set_header Host … -
How to pass UNICODE characters in a url?
I am attempting my first steps in web dev with Django. Can anybody help me modify somehow the paths so that <slug:slug> works for Unicode characters, not only ASCII? from django.urls import path from . import views urlpatterns = [ path('book/<slug:slug>/', views.view_book, name='book'), path('genres/', views.view_all_genres, name='genres'), path('genres/<slug:slug>/', views.preview_genre, name='preview_genre'), ] I tried to play around with some regex but still I couldn't solve my problem -
Django Field 'id' expected a number but got <django.db
Github of the "project": https://github.com/Doomsizer/why Django test project keeps crushing when I'm trying to add email functionalityerror I tried changing many things(in forms, models, html and views) in past couple days, nothing seems to work. I genuinely have no idea how to fix it. -
Django Rest Framework: validate_username and update methods not called during PUT request
I am working on a Django Rest Framework (DRF) project, where I need to validate a username field and handle custom update logic in a serializer. My model has a username field with unique=True. Here's the relevant setup: Model: from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass Serializer: class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = models.CustomUser fields = ["id", "username", "first_name", "last_name"] read_only_field = ["id"] extra_kwargs = { "password": {"write_only": True}, } def validate_username(self, value): print('here.......') user_model = get_user_model() request = self.context.get('request') if request and request.method in ['PUT', 'PATCH']: if user_model.objects.filter(username=value).exclude(id=self.instance.id).exists(): raise serializers.ValidationError('User with this username already exists.') else: if user_model.objects.filter(username=value).exists(): raise serializers.ValidationError('User with this username already exists.') return value class CustomUserProfileSerializer(serializers.ModelSerializer): user = CustomUserSerializer() roles = ProfileRolesSerializer(many=True) department = DepartmentSerializer() gender = GenderSerializer() Views: class CustomUpdateView(APIView): def put(self, request, *args, **kwargs): serializer = CustomUserProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) When I send a PUT request to update a user profile, the validate_username and update methods in the serializer are not executed. Instead, I get a response error: { "user": { "username": [ "User with this username already exists." ] } } I suspect that the default unique=True constraint on the username field is bypassing the serializer-level … -
How to pull up Django model data based on ALREADY filled out form fields for other ForeignKeys
I have a form in which there are several fields with foreign keys. For example, the table "Entrance" (3 entries -> 1st entrance, 2nd entrance, 3rd entrance), "Apartment" (30 entries, 10 for each entrance (No.1-10, No. 11-20 and No. 21-30), "Owner" (also 30 entries of surnames). In turn, the "Owner" has an external key to the apartment, and the "Apartment" has an external key to the entrance. here's the question, if I selected entrance No. 2 in the form, then in the other two fields (Apartment and Owner) I need to display ONLY related records (that is, apartments from 11 to 20 rooms, and the owners who live in these apartments) how to implement it??? here is the code in forms.py(naturally, it gives out an error, I just pointed out where, logically, I wanted to get involved.) ` id_entr = ModelChoiceField(queryset=Bs_entrance.objects.all(), widget=Select( attrs={'class': 'form-select', 'placeholder': 'выберите подъезд'})) id_apart = ModelChoiceField(queryset=Bs_entrance.objects.filter(id_entrance=**id_entr**), widget=Select( attrs={'class': 'form-select', 'placeholder': 'выберите квартиру'})) id_owner = ModelChoiceField(queryset=Bs_apartment.objects.filter(id_apartment=**id_apart**), widget=Select( attrs={'class': 'form-select', 'placeholder': 'выберите собственника'})) ` enter image description here Here is an example of the form (the example is not on apartments)There are all kinds of fault groups, although there should have been only two, since the ballast was …