Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
understanding of urlpatterns in urls.py of Django App
Problem: When we try to add the data to the database. So, the request will always come to this URL starting with the project-level directory, todo_main. So here, we will create a pattern. path('todo/', include('todo.urls')), This path will forward the request to todo. URLs. from django.urls import path from .import views urlpatterns =[ path('addTask/', views.addTask, name='addTask'), ] So whenever we send a request to add a task, then the corresponding views.addTask should run, which will be a task. Questions: I try to understand my best what is the meaning or purpose of addTask. Can we write another word instead of it? -
Django path converter not converting value in path
I have an app that should be able to take a field's value in lower and uppercase. The url below should work http://localhost:8000/app/family=Araceae/ but fail if value is araceae. I followed the official documentation but it's not working. path('app/family=<str:family>/', views.SpeciesDetail_family.as_view(), name='family') I made a converter to convert the value to lower case if it's in uppercase but is returning 404 saying URL does not match the patterns below admin/ app/family=<value:family>/ [name='family'] app/family=<value:family><drf_format_suffix:format> [name='family'] urls.py from django.urls import path, register_converter from rest_framework.urlpatterns import format_suffix_patterns from app import converters, views register_converter(converters.convert_value_to_lowercase, 'value') urlpatterns = [path('app/family=<value:family>/', views.SpeciesDetail_family.as_view(), name='family')] urlpatterns = format_suffix_patterns(urlpatterns) converters.py class convert_value_to_lowercase: regex = '[A-Z]' def to_python(self, value): value = value.lower() return value def to_url(self, value): return value -
Dockerise Django with proxy server NGINX
I have dockerised a django application. And now I try to deploy the app to a live server. So I am using the NGINX reversed proxy server. I have a folder name called proxy within a dockerfile: FROM nginxinc/nginx-unprivileged:1-alpine COPY ./default.conf.tpl /etc/nginx/default.conf.tpl COPY ./uwsgi_params /etc/nginx/uwsgi_params COPY ./run.sh /run.sh ENV LISTEN_PORT=8000 ENV APP_HOST=app ENV APP_PORT=9000 USER root RUN mkdir -p /vol/static && \ chmod 755 /vol/static && \ touch /etc/nginx/conf.d/default.conf && \ chown nginx:nginx /etc/nginx/conf.d/default.conf && \ chmod +x /run.sh VOLUME /vol/static USER nginx CMD ["/run.sh"] and a default.conf.tpl file: server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } And a run.sh script: #!/bin/sh set -e envsubst < /etc/nginx/default.conf.tpl > /etc/nginx/conf.d/default.conf nginx -g 'daemon off;' and docker-compose-deploy.yml looks: version: "3.9" services: app: build: context: . dockerfile: Dockerfile.prod restart: always volumes: - static-data:/vol/web environment: - DJANGO_ALLOWED_HOSTS={DJANGO_ALLOWED_HOSTS} env_file: - ./.env.prod proxy: build: context: ./proxy restart: always depends_on: - app ports: - 8000:8000 volumes: - static-data:/vol/static volumes: static-data: part of my settings.py file looks like: import os import dotenv dotenv.read_dotenv() from pathlib import Path from os import environ import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR … -
How do I enable HTTPS redirect in Mayan EDMS
I have a session of Mayan in docker with traefik for hosting on the local network. I want to use my keycloak with oidc. Following this forum post works, but the redirect_uri is http and not https. As is the case with case django project I have tried setting MAYAN_SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https") which didn't work and reading the documentation and source code haven't let me to any obvious settings. -
DynamoDB in Django 4.2.4
I have a Django project now i want to shif in DynamoDB insted of sqlite3 for database,looking for documentation so i can configure it on my project, specific documentation? configure DynamoDb in Django project that contain multiple app -
The current path, 1/password/, didn’t match any of these
Im trying to access the reset password through the form link. Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form. Traceback Using the URLconf defined in carreview.urls, Django tried these URL patterns, in this order: admin/ [name='home'] car/<int:pk> [name='post-details'] create_post/ [name='create_post'] car/edit/<int:pk> [name='edit_post'] car/<int:pk>/delete [name='delete_post'] like/<int:pk> [name='likes'] signup/ signup/ The current path, 1/password/, didn’t match any of these. blog/urls.py urlpatterns = [ path('', view.as_view(), name='home'), path('car/<int:pk>', PostDetail.as_view(), name='post-details'), path('create_post/', CreatePost.as_view(), name='create_post'), path('car/edit/<int:pk>', EditPost.as_view(), name='edit_post'), path('car/<int:pk>/delete', DeletePost.as_view(), name='delete_post'), path('like/<int:pk>', Likes, name='likes') ] signup/urls.py urlpatterns = [ path('', view.as_view(), name='home'), path('car/<int:pk>', PostDetail.as_view(), name='post-details'), path('create_post/', CreatePost.as_view(), name='create_post'), path('car/edit/<int:pk>', EditPost.as_view(), name='edit_post'), path('car/<int:pk>/delete', DeletePost.as_view(), name='delete_post'), path('like/<int:pk>', Likes, name='likes') ] Edit profile view (signup/views.py) class ProfileEdit(generic.UpdateView): form_class = EditProfile template_name = 'registration/edit_profile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user I believe its something to do with "1/password/" instead of being redirected to "/passwords/" If you need any more files ill add them, thanks :) I'm trying to be redirected to change the password in the edit profile section. -
Modal window doesn't open in django
I'm having a little problem with a modal in django. When I click on the button to open the modal window just nothing happens. I'm a beginner, so don't swear too much at very stupid mistakes. {% extends 'main/layout.html' %} {% block title %} Registration {% endblock %} {% block content %} <div class="features"> <h1> Registration </h1> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Open modal window</button> <div class="modal fade" id="exampleModal" role = "dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"> Form </h5> <button class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p>Something</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <form method = "post"> {% csrf_token %} {{ form.name }}<br> {{ form.mail }}<br> {{ form.phone }}<br> {{ form.password }}<br> <font color="red">{{error}}</font><br> <br> <button class = "btn btn-success" type = "submit">add news</button> </form> </div> {% endblock %} Pattern {% load static %} <!doctype html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>{% block title %} {% endblock %}</title> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/5.2.3/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'main/css/main.css' %}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v6.4.2/css/all.css"> </head> <body> <aside> <img src="{% static 'main/img/1.jpg' %}" alt="Logo"> <span class="logo">Rolex</span> <h3>Навигация</h3> <ul> <a href="{% url 'home' %}"><li><i … -
I have problem to get items from cart model using nested URL
I'm working on multi vendor online store project using django , I'm trying to get items from cart but I get not found response I use nested URL : app_name = "cart" urlpatterns = [ path( "cart_retrieve/<str:pk>/items/", CartItemsRetrieveView.as_view(), name="retrieve-cart-items", ), ] so I have this view to get the items from the cart : class CartItemsRetrieveView(generics.RetrieveAPIView): queryset = Cart.objects.all() serializer_class = CartSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] pagination_class = StandardResultsSetPagination def get_queryset(self): # Assuming the cart is identified by a cart_id in the URL cart_id = self.kwargs.get("pk") try: cart = Cart.objects.get(cart_id=cart_id) return cart.items.all() # Return all items related to the cart except Cart.DoesNotExist: return CartItems.objects.none() the problem is when I commented the get_queryset I can retrieve the cart object : { "cart_id": "75ed487e-445a-437c-aef6-4cf62217e6e7", "created_at": "2023-08-20T12:15:56.360320Z", "items": [ { "cart_items_id": "b2fe23bc-442c-41fb-be8d-65f9f03241ae", "cart": "75ed487e-445a-437c-aef6-4cf62217e6e7", "product": { "product_id": "463d4e16-46a2-4da0-9e25-2a99a494b6f6", "title": "el short el fashe5", "discounted_price": 90.0 }, "quantity": 1, "sub_total": 90.0 }, { "cart_items_id": "8bf66b5b-2b9d-4dd3-8528-cfc693035168", "cart": "75ed487e-445a-437c-aef6-4cf62217e6e7", "product": { "product_id": "5fecf90c-874b-452f-8a8d-adde50ee2f33", "title": "cover lel 2amar", "discounted_price": 50.0 }, "quantity": 2, "sub_total": 100.0 }, { "cart_items_id": "140a0762-17ef-4e65-aa1a-997b79fec14b", "cart": "75ed487e-445a-437c-aef6-4cf62217e6e7", "product": { "product_id": "e6e61a33-82cc-40f7-aef7-f538150bb703", "title": "mouse bs nice", "discounted_price": 33.25 }, "quantity": 3, "sub_total": 99.75 }, { "cart_items_id": "2f569234-bc7d-4d2c-ad49-d4a6bbe9cc4b", "cart": "75ed487e-445a-437c-aef6-4cf62217e6e7", "product": { "product_id": … -
My view display raw data instead of showing the data in Datatables
I have been trying to understand how ajax and Datatables works in Django. But, as the title says, my list of data is being raw displayed in my view. Screenshot: I will put here my code so you can help me understand what's missing, or wrong. My list view: class SampleList(LoginRequiredMixin, ListView): model = Samples def render_to_response(self, context, **response_kwargs): data = list(self.get_queryset().values()) return JsonResponse(data, safe=False) My template: {% extends 'partials/base.html' %} {% load static %} {% block title %}Samples List{% endblock title %} {% block content %} <div class="main-panel"> <div class="content-wrapper"> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <!-- partial --> <h2>Here are all samples: </h2> <h1>Samples</h1> <table id="samples-table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Date</th> </tr> </thead> <tbody> //I don't know if here must be empty </tbody> </table> <script> $(document).ready(function() { // Initialize DataTable $('#samples-table').DataTable({ // Replace "yourmodel-list/" with the URL of your view "ajax": { "url": "{% url 'samples:samplelist' %}", "dataSrc": "data" // Property name that holds the array of records in the JSON response }, "columns": [ {"data": "id"}, // Column for ID {"data": "sample_code"}, // … -
Can't use redis password with special characters in django
I have a redis server with authentication password containing =, and ?. Meanwhile I am using the Location scheme as redis://[:password]@localhost:6397. Config: 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://:6?V4=434#ef4@localhost:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } }, I always get an error TypeError: __init__() got an unexpected keyword argument 'V4'. Somehow the Location scheme string doesnt count for cases where password have =, and ? in certain order, such that it thinks it is separators in the scheme. I tried to escape the special characters : 6\?V4\=434#ef4 but it gave me different error: ValueError: Port could not be cast to integer value as '6\\' Can this be solved without moving password in OPTIONS ? -
django requires libmysqlclient.21.dylib but I have libmysqlclient.22.dylib on MAC OSX
I have this error when using django, it seems to require /opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib However I have /opt/homebrew/opt/mysql/lib/libmysqlclient.22.dylib in my system. I use brew on Mac OSX Venture How can I fix this? Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/MySQLdb/__init__.py", line 17, in <module> from . import _mysql ImportError: dlopen(/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): Library not loaded: /opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib Referenced from: <158921C4-1F3C-3D68-AE0F-402C3D6AF77B> /Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so Reason: tried: '/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/usr/local/lib/libmysqlclient.21.dylib' (no such file), '/usr/lib/libmysqlclient.21.dylib' (no such file, not in dyld cache), '/opt/homebrew/Cellar/mysql/8.1.0/lib/libmysqlclient.21.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/Cellar/mysql/8.1.0/lib/libmysqlclient.21.dylib' (no such file), '/opt/homebrew/Cellar/mysql/8.1.0/lib/libmysqlclient.21.dylib' (no such file), '/usr/local/lib/libmysqlclient.21.dylib' (no such file), '/usr/lib/libmysqlclient.21.dylib' (no such file, not in dyld cache) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.17_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 980, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.17_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/__init__.py", line 24, … -
How to pass Payment Intent Id in Checkout in Stripe?
I am trying stripe in test mode in Django. I am new here. I want to let customer choose the card from their saved cards for checkout. I am storing customer's preferred card (payment method which is pm_xxxxxxx) in selected_card_id. Then I have created Payment Intent. Now I want to pass this payment intent id into checkout. But currently my code is creating two payment intents: (1.) in payment intent which stays INCOMPLETE ue to 3DS authentication (and I can't do anything about it as it is in test mode) (2.) in checkout which is getting COMPLETED but it is using only the last saved card. Here is my code: # For getting id of current logged in user current_user_id = request.user.id user = User.objects.get(id = current_user_id) selected_card_id = request.session.get("selected_card_id") # Create customer id for new user if not user.customer_id: customer = stripe.Customer.create() user.customer_id = customer.id user.save() payment_intent = stripe.PaymentIntent.create( currency='inr', customer = user.customer_id, amount=299900, # Amount in paise payment_method=selected_card_id, confirm = True, ) payment_intent_id = payment_intent["id"] checkout_session = stripe.checkout.Session.create( mode='payment', payment_intent= payment_intent_id, payment_method_types=['card'], line_items=[ { 'quantity': 1, 'price': 'price_1NevYPSIWq54gkyCEytMLqZ1', } ], success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled/', customer=user.customer_id ) My objective can be achieved either if Payment Intent can … -
ModuleNotFoundError: No module named 'attachments.wsgi'
i am trying to deploy my django app on render but i am finding this error attachments is my projectname my code for wsgi is """ WSGI config for attachments project. It exposes the WSGI callable as a module-level variable named application. For more information on this file, see https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'attachments.settings') application = get_wsgi_application() enter image description here i was expecting a sucess message -
Only python file can read a specific file
For a High school projet, I have to use a private key to encrypt file. I changed permission to my pk, only the root user can read this file. I change the owner (to root) and put the uid right to this python file, but when I execute this python file, I can't have access to my pk, for me I have to change the right of python, but I didn't want, (problem of security). Do you have any idea to have access to a file only by a python file? The python file is included on a django project (view.py), I had too the idea to use the pid of the process but it didn't change my problem. I used chown root and chmod with 0777 on my view.py but it said that I can't have access to read this file (has the read for owner root). -
Is there a method for separating a logged in user from a super user in the views.py of a django based website?
I created a blog and users have to create an account to have access to make comment. My question is how do i make logged in users have a different access from to super user who can create a blog posts? I need a way to restrict general logged in users so they don't have similar access from the Super users.enter image description here I tried using using if user.is_superuser in one of the html pages i want to restrict but it is still not workingenter image description here -
How do I fix the scrollbar to always be at the bottom using tailwind css?
I have the following div with a list of divs. These child divs are going to be a message boxes of a chat box. <div class="overflow-auto"> </div> However, obviously I need the scoller to be at the bottom automatically whenever the user enters the page, because I want to show the latest conversation first. How am I able to do that? Thank you, and please leave any comments below. -
401 unauthorized response when doing user registration in Django rest framework using serializers and Api view
A bit of an update. Here is my serializers.py code: class SellerRegistrationSerializer(serializers.ModelSerializer): class Meta: model=Seller fields=['email','password','first_name','last_name','company_name','seller_desc','seller_image','seller_verification'] extra_kwargs={ 'password':{'write_only':True} } #def create should be done since this is a custom User model def create(self,validate_data): return Seller.objects.create_user(**validate_data) and In my views.py I have this code: from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } class SellerRegistrationView(APIView): # def post(self,request,format=None): serializer=SellerRegistrationSerializer(data=request.data) if serializer.is_valid(raise_exception=True): seller=serializer.save() token=get_tokens_for_user(seller) return JsonResponse(serilizer.data,status=status.HTTP_201_CREATED) return JsonResponse(serializer.errors,status=status.HTTP_400_BAD_REQUEST) class SellerLoginView(APIView): def post(self,request,format=None): serializer=SellerLoginSerializer(data=request.data) if serializer.is_valid(raise_exception=True): email=serializer.data.get('email') password=serializer.data.get('password') seller=authenticate_seller.authenticate(request,email=email,password=password) #where i use custom authenticator that uses email of the user and not username if seller is not None: token=get_tokens_for_user(seller) return JsonResponse({'token':str(token)},status=status.HTTP_200_OK) else: return JsonResponse({'errors':{'non_field_errors':['Email or password is not valid']}}, status=status.HTTP_404_NOT_FOUND) #when serializer sends an error, it can send non_field_errors as one of the error response but in frontend we catch that error as errors to get all the errors. so to also obtain the non_field_error, we send it inside errors as an object that we will probably jsonify return JsonResponse(serializer.errors,status=status.HTTP_400_BAD_REQUEST) now with this url:path('sregister/',SellerRegistrationView.as_view(),name='sregister'), when i make the request using thunder client i get this as a response: { "detail": "Authentication credentials were not provided." } with a 401 status . I don't know why this … -
In Django, how to use split() to split a string of dropdown items?
trips in the def trips function returns something like x-y (so team_home-team_away). trips is showing correctly in the second dropdown. I want to separate x and y, creating two variables: x will be variable a, and y will be variable b. will be I tried this, but it doesn't work: a,b = trips.split('-') I don't know if a,b = trips.split('-') is correct in setting up your code. My goal is to select the item in the combobox, then click on the button which starts the def test1 function and displays the text in the textarea (def result). Should I use the split code in the def trips function or elsewhere? Or do I have to create a new function? The render of the split in which HTML page should it be? (in trips.html which is the dropdown or in result.html which is the textarea?) Can you show me how I can fix it? views.py from django.shortcuts import render from .models import Full_Record import random def trip_selector(request): campionati = Full_Record.objects.values(pk=F('campionato__id'), name=F('campionato__name')).distinct() trips = [] return render(request, 'form.html', {'campionati': campionati, 'trips': trips}) def trips(request): if request.GET.get("campionato"): campionato = request.GET.get('campionato') trips = Full_Record.objects.filter(campionato=campionato) elif request.GET.get("trips"): selected_trip_id = int(request.GET.get('trips')) selected_trip = Full_Record.objects.get(id=selected_trip_id) request.session.update({"selected_trip_id": selected_trip_id}) … -
can we build the cordova android application with django as backend and Mysql as database
I am trying to build the cordova application by using django as backend but I do not know how to do that if anyone have been working on that please guide me to build the cordova applcation with the django as backend if anyone having solution that how I can connect the django default server to my cordova app -
Access GAID in Django
Is it possible to retrieve GAID in a Django server? Here is my scenario: I want to create a unique link in my Django project and send it to a user (it's a referral link). When the user click the link it will redirect to my server so then I can log its click and then user will redirect to an app store to download my app. Is it possible for me to get its GAID before installing the app, right after clicking the link? If yes so, then how? I searched already couldn't find anything helpful. I appreciate if anyone can offer me a documentation or something like that. -
Not getting a django's right capture group when url has a "."
I have a url http://localhost/fault/docs/testing/pipelines/dot.filetesting which should return a default html page ie index.html urls.py looks like- re_path(r'(?P<resource>.*)$', csrf_exempt(views.get_docs_from_s3), name='read_docs') view.py - ` @require_GET def get_docs_from_s3(request, resource): mime_type, _ = mimetypes.guess_type(resource) # if not Path(resource).suffix: # resource = resource.rstrip("/") + "/index.html" try: page = get_page_from_s3(resource) return HttpResponse(page, content_type=mime_type or "text/html") except Exception as e: return HttpResponse("Not found", content_type=mime_type or "text/html")` nginx conf - ` location /fault { add_header X-Cache $upstream_cache_status; rewrite ^([^.]*[^/])$ $1 permanent; proxy_set_header Host localhost:8000; proxy_pass http://localhost:8000/bug; proxy_connect_timeout 30s; proxy_read_timeout 86400s; proxy_send_timeout 30s; proxy_http_version 1.1; }` Question for a url like http://localhost/fault/docs/testing/pipelines/normal I am able to render html page since the resource in my views = docs/testing/pipelines/normal/index.html but for urls that have "." in them like mentioned above I don't get index.html appended. Note-> In the code I do not want to add /index.html in my views.py for that doesn't have, if its able to be resolved at nginx and django urls leveel -
Need advice. Forbidden (403) CSRF verification failed. Request aborted. Django error
I am making a website with django and when i login and go back then try to login again i get this error message. Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token from POST incorrect. When i login first it works okay, and after i get the error i go back and the login is successful again. I was just wondering what the problem is with my code. This is the views.py `@csrf_protect def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password ) if user is not None: auth_login(request, user) return redirect('homepage') else: messages.error(request, 'Username OR password is incorrect') context = {} return render(request, 'login.html', context)` This is my settings.py `MIDDLEWARE = [ 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ` This is my login.html `<form method="POST" action=" " > {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> <input type="text" name="username" class="form-control input_user" value="" placeholder="Username"> </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> </div> <input type="password" name="password" class="form-control input_pass" value="" placeholder="Password"> </div> <div class="form-group"> <div class="custom-control custom-checkbox"> </div> </div> <div> {% for message in messages %} <p id="messages">{{message}}</p> {%endfor%} … -
Heroku Django remote: Is the server running locally and accepting connections on that socket? heroku django
So Ive been trying to run my django application on heroku, it works locally fine with the database, so its some issue within my base.py that I havent been yet able to identify. If anyone has encountered a similar problem and have a solution, Ive been looking around for a while no hints :( error message: remote: Verifying deploy... done. remote: Running release command... remote: remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection remote: self.connect() remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner remote: return func(*args, **kwargs) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect remote: self.connection = self.get_new_connection(conn_params) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner remote: return func(*args, **kwargs) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection remote: connection = self.Database.connect(**conn_params) remote: File "/app/.heroku/python/lib/python3.10/site-packages/psycopg2/init.py", line 122, in connect remote: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) remote: psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory remote: Is the server running locally and accepting connections on that socket? base.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the … -
datetime field in django is being displayed differently in the template and not like the saved one in database
The following is a part of my ajax request in my django template <span class='time-left'>${response.chats[key].date}</span></div>`; This is the model field it is refering to... date = models.DateTimeField(auto_now_add=True, null=True, blank=True) Now this is the problem. The datetime is saved correctly in the database to my current timezone. However, when I display it in the template like above, I get a different time for some reason. the USE_TZ=True in my settings, and I don't want to change it. Do you know how I could show the saved value in the database in the template as well? -
Getting "AttributeError: 'ProfileSerializer' object has no attribute '_meta'" when trying to update a model object
In my django project, I'm trying to update a Profile object using patch request. When the code gets to ".save()" method, I'm getting "AttributeError: 'ProfileSerializer' object has no attribute '_meta'". Please try to explain the problem to me rather than only giving me the solution. This is my Model: class Profile(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE, related_name='profile') avatar = models.ImageField(upload_to="avatars/", null=True, blank=True) bio = models.TextField(max_length=500, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): return self.user.name This is my ProfileSerializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' This is my view: @api_view(['PATCH']) @permission_classes([IsAuthenticated]) def edit_profile(request, user_id): user = request.user if not user.id == user_id: return Response({"message": "You can't edit other's profiles."}, status=status.HTTP_401_UNAUTHORIZED) profile = Profile.objects.get(user=user) serializered_prof = ProfileSerializer(profile) update_prof = ProfileSerializer(serializered_prof, request.data, partial=True) update_prof.is_valid(raise_exception=True) update_prof.save() return Response({'message': 'profile Updated.'}) I dont know why this error is raised.