Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting a 403 Forbidden message in a Django 4.2 POST request even after including the CSRF token
I am trying to perform a language toggle feature in a website and I am using Django 4.2 and using Django's i18n library in the root level urls.py file. urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += i18n_patterns( path('',apiView.WebsiteHomepageTemplate.as_view(),name="url_homepage_template"), ) In the template file , I am performing the language switch like this : <ul class="dropdown-menu" role="menu" id="language-list"> <li class="" id="language-switcher"> <form action="{% url 'set_language' %}" method="post" name="lang_form"> {% csrf_token %} <input name="next" type="hidden" value="/" /> <select class="selectpicker" id="select_pickr" name="language"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected="selected" {%endif %} data-content='{{ language.code }}}'> {% if language.code == 'en' %} English {% else %} हिंदी {% endif %} </option> {% endfor %} </select> </form> </li> </ul> When I perform the toggle, I get a 403 forbidden message. When I inspect using the dev tools I can see only 2 cookies being used , csrftoken & theme (for changing light and dark mode) till this moment So if I perform the toggle again while being on my custom 403 error page, I am able to toggle to the other … -
How to resolve [Errno -2] Name or service not known error?
I've hosted my Django application on cpanel, and when I try to send notifications to users via email, I receive this problem [Errno -2]. The name or service was unknown, but it worked properly using localhost. Any advice would be greatly appreciated. enter image description here This is my code to send mail to users. I have configured all the details in settings as well. -
How do I resolve HTTPSConnectionPool error, Max retries exceeded with url in python?
requests didn't work as expected def post(self, request): base_url = os.environ.get('AUTH_URL', 'http://localhost') # Make a POST request to the authentication endpoint with the payload headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", 'accept': 'application/json', 'Content-Type': 'application/json', } json_data = { 'username': os.environ.get("GARAJ_USERNAME", "admin"), 'password': os.environ.get("GARAJ_PASSWORD", "admin123"), } response = requests.post(base_url + '/api/token/', json=json_data, headers=headers) # Check the response status code if response.status_code == 200: data = response.json() # Extract the JWT token from the response jwt_token_access = data['access'] # Use the JWT token for subsequent API requests headers['Authorization'] = f'Bearer {jwt_token_access}' auth_url = base_url + '/api/boshqarma/avto/' response = requests.get(auth_url, headers=headers) for x in response.json()['results']: if x["davlat_raqami"] == request.data['avto_raqami']: boshqarma = x["boshqarma"] response = requests.get(base_url + f'/api/boshqarma/boshqarma/{boshqarma}/', headers=headers) tuman = response.json()['tuman'] response = requests.get(base_url + f'/api/boshqarma/bolim/{tuman}/', headers=headers) tuman = response.json()['tuman'] tuman = Tuman.objects.get(tuman_nomi=tuman) data = {'tuman_id': tuman.id} response = Response(data) return response else: return Response("Xato avto raqam") # Make additional API requests with the headers containing the JWT token else: return Response(response) This code block works on using localhost but did't work when it is on server,but returns below error.I manage both servers client and host server too. ConnectionError at /api/check-car/ HTTPSConnectionPool(host='example.uz', … -
success_url working on local but does not on production
I have a django website which uses stripe for payment. Everything seems to work fine on my local terminal and production server. However, my success page on the deployed website returns a Bad Request(400). I'll show the code below. The method that calls the success_url def charges(request, order_id): try: cart_items = CartItem.objects.filter(user=request.user) domain = settings.DOMAIN_NAME if settings.DEBUG: domain = "http://127.0.0.1:8000/" session = stripe.checkout.Session.create( customer_email=request.user.email, payment_method_types=['card'], line_items=[{ 'price_data': { 'product_data': { 'name': cart_item.product.product_name, }, 'unit_amount_decimal': cart_item.product.price*100, 'currency': 'usd', }, 'quantity': cart_item.quantity, 'tax_rates': [tax_rate.id], } for cart_item in cart_items], metadata={ "orderID": order_id }, mode='payment', success_url=domain + 'orders/order_complete?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain + 'orders/order_incomplete?session_id={CHECKOUT_SESSION_ID}', ) # Pass the session ID to the template return JsonResponse({ "id": session.id }) except stripe.error.InvalidRequestError as e: # Handle the specific InvalidRequestError exception print(f"Invalid request error: {e.param}") except stripe.error.StripeError as e: # Handle other Stripe-related errors print(f"Stripe error: {e}") except stripe.error.ValueError as e: print(f"Stripe error: {e}") except Exception as e: # Handle other general exceptions return JsonResponse({'error': str(e)}) The method that renders the success page def order_complete(request): session_id = request.GET.get('session_id') session = stripe.checkout.Session.retrieve(session_id) order_number = session["metadata"]["orderID"] transID = session["id"] try: order = Order.objects.get(order_number=order_number, is_ordered=True) ordered_products = OrderProduct.objects.filter(order_id=order.id) payment = Payment.objects.get(payment_id=transID) context = { 'order': order, 'ordered_products': ordered_products, 'order_number': order.order_number, 'transID': payment.payment_id, … -
How to reply comment using django and javascript
Please, I need help with my code, I have been unable to figure out my mistake for two days. I have a comment system that work properly but I want user to be able to reply comments. My issue now is that the reply comment is not submitting as I keep having the error: This page isn’t working right now. If the problem continues, contact the site owner. HTTP ERROR 405 Below is my view.py associated with it class BlogDetailsView(DetailView): model = models.BlogPost template_name = 'home/blog_details.html' def get_context_data(self, *args, **kwargs): get_likes = get_object_or_404(models.BlogPost, id=self.kwargs['pk']) context = super().get_context_data(*args, **kwargs) post = self.get_object() context['comments'] = post.comments.filter(status=True) context['comment_form'] = NewCommentForm() total_likes = get_likes.total_likes() liked = False if get_likes.likes.filter(id=self.request.user.id).exists(): liked = True context['total_likes'] = total_likes context['liked'] = liked return context def add_comment(request, pk): post = get_object_or_404(models.BlogPost, pk=pk) comments = post.comments.filter(status=True) if request.method == "POST": comment_form = NewCommentForm(request.POST) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.post = post user_comment.save() return redirect('index:blog_details', pk=pk) else: comment_form = NewCommentForm() return redirect('index:blog_details', pk=pk) Below is urls.py app_name = 'index' urlpatterns = [ path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('images/favicon.ico'))), path('', views.home, name = 'home'), path('blog/', BlogHomeView.as_view(), name="blog_list"), path('blog/<int:pk>/', BlogDetailsView.as_view(), name='blog_details'), path('add_post/', AddPostView.as_view(), name='add_post'), path('blog/edit/<int:pk>', EditPostView.as_view(), name='edit_post' ), path('blog/<int:pk>/delete', DeletePostView.as_view(), name='delete_post' ), path('like/<int:pk>', views.LikeView, name='like_post'), path('job/', JobHomeView.as_view(), … -
How to auto add value from ForeignKey to ManyToManyField?
So I need auto add author to coworkers. class Board(models.Model): """Model definition for Board.""" author = models.ForeignKey( to=User, on_delete=models.CASCADE, related_name="author", ) name = models.CharField(max_length=24, blank=False) coworkers = models.ManyToManyField( to=User, blank=True, ) For now I use serializer and view solution. Is it possible do with model? -
Override Django Admin 'add' form template and form processing
Summary: I want to change the 'add' template in Django admin. I want to display an HTML form, which I want to processes and save some data into the database. This form and the data I'll save aren't directly rows in a model. I can override the template with add_form_template, but can't figure out how to use a Django Form object within that. I have a self-referential model, where several rows may link to a single row. This linkage is to be performed by a human. For example, we might say "Select all the fruits", and list apples, oranges, bananas and cashew nuts. The next "row" of the form would say "Select all the cars", with a list of "Mini", "Jazz", "Fiesta" and "F150". We'd maybe show 10 such rows on the form, the human would select all the fruits, and cars, and do the same thing on the other 8 rows, and press submit. We'd then read the form data, and set the 'link' for all the fruits to the "All Fruit" row's ID (and same for the cars and other things). This workflow doesn't follow the usual 'add a row' (or 'many to many') style that Django admin … -
MIME type error with npm libraries in ReactJS
I am currently creating a Django + React application. I am currently using React 18.2.0 and Django 4.2. I have my application completed when Debug=True in Django. However, once I perform the operation: DEBUG = False ALLOWED_HOSTS = ["*"] The website breaks once I change these lines of code. When I look into the console in the website it displays the error: Refused to execute script from 'http://localhost:8000/static/js/main.94957794.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. I got three of these errors each depending on if it was a stylesheet or javascript. After a few hours of tinkering around I manage to figure out that the problem was with some libraries that I am using from npm (react-animation, Animate.css and countries-list). React Animation is an out-of-date library and had to downgrade to React 16.8.0. (Idk if that is a possible reason). How would I solve these errors? I am just very confused as the website works when DEBUG = True but not when DEBUG = False. My main problem is that the website just doesn't work altogether when I set DEBUG = False. Does anyone have a solution to this? I have tried … -
I configured setting.py file in Django but it displays CORS ERROR
My frontend is React and Backend is Django. In postman, Django has not CORS error and it works well. But when I send API(post) in React, It displays CORS error. I configured settings.py file as follow. ALLOWED_HOSTS = ["*"] CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:5173' ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] But it displays CORS error You can see the CORS error here. How can I fix the CORS error? I am new in Django and am going to learn about it. -
My django views/login form are not working properly
I am doing a final project for a programming certificate (Python programming). I have stumbled upon a problem when it came to my views. My MySQL database is connected to django, and I have made an account (through MySQL), yet when I try logging in with these account credentials, it sends the error that these credentials are not valid, or that they don't exist. When I add a print function to the code, it prints the user as "None." However, if I add print to username and password - it prints out the inputted credentials. Thank you in advance... from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Discount, Store from django.contrib.auth import authenticate, login as auth_login from django.contrib.auth.decorators import login_required from .forms import DiscountForm from django.contrib.auth.models import User # Create your views here. def user_login(request): if request.method == 'POST': username = request.POST.get('username') print(username) password = request.POST.get('password') print(password) user = authenticate(request, username=username, password=password) print(user) if user is not None: auth_login(request, user) # Use auth_login instead of login return redirect('discountList') else: return render(request, 'index.html', {'error': 'Invalid credentials'}) return render(request, 'index.html') -
Django rest api and axios post request doesn't work
I am trying to make a simple api where a user writes something in an input, presses a button and a new instance is added in a database. To do this I am using react and django rest framework. App.js const [name,setName] = useState('') const handleChange = (e) => { setName(e.target.value) } function handleClick(e) { e.preventDefault() axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" axios.post('http://127.0.0.1:8000/post/', { headers: { "Content-Type": "application/x-www-form-urlencoded", 'X-CSRFToken': 'csrftoken' }, data:{ title: name, name: name } }) } return ( <> <form> <input type='text' value={name} onChange={handleChange} /> <button onClick={handleClick}>OK</button> </form> </> ); views.py @api_view(['POST']) def home2(request): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response() But when I press the button I get manifest.json:1 GET http://127.0.0.1:8000/manifest.json 404 (Not Found) and manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. in javascript. In django I get "POST /post/ HTTP/1.1" 200 0 Also I am using npm run build for javascript and manifest.json is in public folder. React is inside django and the structure looks like this: mysite frontend main mysite db.sqlite3 manage.py -
Video encoding task not working with Django Celery Redis FFMPEG and GraphQL
I'm having a hard time trying to understand how is this FFMPEG encoding works while using Django, Celery, Redis, GraphQL and Docker too. I have this video / courses platform project and want I'm trying to do using FFMPEG, Celery and Redis is to create different video resolutions so I can display them the way Youtube does inside the videoplayer ( the videoplayer is handled in frontend by Nextjs and Apollo Client ), now on the backend I've just learned that in order to use properly the FFMPEG to resize the oridinal video size, I need to use Celery and Redis to perform asyncronus tasks. I've found a few older posts here on stackoverflow and google, but is not quite enough info for someone who is using the ffmpeg and clery and redis for the first time ( I've started already step by step and created that example that adds two numbers together with celery, that works well ). Now I'm not sure what is wrong with my code, because first of all I'm not really sure where should I trigger the task from, I mean from which file, because at the end of the task I want to send … -
Prometheus cannot find Django /metrics
Im using the prometheus client library for Django. I am not running prometheus in a Docker container. The Djanog application is bound to Unix domain sockets, so I think that is part of my issue but idk how to resolve. NGINX is listening on port 80 and re-routes traffic with the proxy_pass header. I dont understand how my node_exporter (server metrics) works fine with the local host target, but my application will not. Even from a browser I can access "/metrics" endpoint. I've tried localhost, 127.0.0.1, and even the server IP and nothing works. Also, IPtables has nothing related to port 80, yet I've created a "denied" log record and Im getting "... src=127.0.0.1 dst=127.0.0.1 dpt=80 [...]" NGINX erver { server_name hotname www.hostname ip; [...] location /metrics{ proxy_pass http://<unix_domain>; } location / { proxy_pass http://unix:<location_of_domain_socket>; } prometheus <default prom config> [...] static_configs: - targets: ["localhost:9090"] - job_name: "django-app" scrape_interval: 10s static_configs: - targets: ["localhost] # nothing works and prometheus attempts to use port 80 with a predefined scheme of http:// - job_name: "node" scrape_interval: 10s static_configs: - targets: ["localhost:9100"] -
Best Approach for Developing a Cross-Platform Mobile App alongside a Django Web App?
I’m currently working on building a Django app, and I anticipate that it will eventually require a cross-platform mobile app as well. While the Django web app can be designed to be mobile responsive, I’m considering the option of developing a native app. I’ve done some research, and it seems like React Native could be a good choice. However, I’m open to suggestions since React Native involves a completely different world and language compared to Django and Python. I’d appreciate any recommendations or insights you may have regarding the best route to take for building a native mobile app alongside my Django app. -
Cannot assign <User: username> must be a "User" instance
I'm trying to create a web gallery in Django, but I'm stuck right at the beginning. I can't assign the user ID as a foreign key in the database. views.py file from django.shortcuts import render, redirect from django.template.context_processors import csrf from .forms import RegistrationForm, LoginForm, ImageForm from django.contrib import messages from django.contrib.auth import authenticate, login, get_user_model from django.contrib.auth import views as auth_views from django.contrib.auth.decorators import login_required from .forms import ImageForm @login_required def add_image_view(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): image = form.save(commit=False) if request.user.is_authenticated: user_obj = get_user_model().objects.get(id=request.user.id) print(user_obj) #I receive the expected value.[marek] print(user_obj.id) #I receive the expected value.[2] print(user_obj.username) #I receive the expected value.[marek] image.username = user_obj image.save() return redirect('user_panel') else: form = ImageForm() return render(request, 'main/add_image.html', {'form': form}) models.py files from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(blank=True) class Meta: verbose_name = 'użytkownik' verbose_name_plural = 'użytkownicy' ordering = ['username'] permissions = [('special_permission', 'Specjalne uprawnienie')] groups = models.ManyToManyField( 'auth.Group', related_name='main_users', # zmianiona nazwa odwrotnego dostępu blank=True, verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_query_name='main_user' ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='main_users', blank=True, verbose_name='user permissions', help_text='Specific permissions for this user.', … -
How to pass in the context data from model in Django
I'm in view (View1) with model1 and i want pass something through context to template. I have a problem because I want to pass data from another model and I don't know how to refer to it: class View1(): model = model1 def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) context_data['mycontext'] = # i want to pass data from model3_field1 model1: class model1(): some_fields.. model2: class model2(): model2_field1 = models.ForeignKey(model1, on_delete=models.CASCADE, null=True, blank=True) model2_field2 = models.ForeignKey(model3, on_delete=models.SET_NULL, null=True, blank=True) model3: class model3() model3_field1 = models.CharField(default=YesNo.NO, max_length=4, blank=True, choices=YesNo.choices) -
Django template render speed issue for large queryset
I have completed a web application for work and was doing some various tests. One of the tests was for a "exaggerated" number of items on a given page and how long it would take to load (the page is basically a dashboard for a helpdesk system) . My results are quite bad with the test page taking some 20 to 25 seconds for 1200 items on a standard spec system and 3 - 10s on a very high spec system. I dont ever expect the active calls to reach that number on the dashboard but am looking at a worst case scenario. I have also tried with pagination, but I am probably implementing it wrong as going to the next page seems to rerun the queries and takes the same time as displaying all 1200 items irrespective of whether I am displaying 1 item or 10. As the project is quite large and contains sensitive information, I cant really provide the code here for reproducible results but I created another basic project that basically highlights what I am experiencing. It can be downloaded here: https://drive.google.com/drive/folders/19yvzHugC7hjcVJpiHeYiEjyX-SA2_wu3?usp=sharing This code is not that bad as not many attributes are referenced in the … -
Handle NoSuchKey error with Custom Storage class AWS S3 and Django
I am using Django, I wanted to handle the NoSuchKey error which happens when am redirected to the file link from my Django project. How best can I use the Custom storage error to handle this : """Custom storage settings.""" from storages.backends.s3boto3 import S3Boto3Storage from botocore.exceptions import NoSuchKey from django.shortcuts import render class FileStorage(S3Boto3Storage): """File storage class.""" print(" Hi there am AWS") def open(self, name, mode='rb'): try: return super().open(name, mode) except NoSuchKey: return {'errror': 'Error Happened'} I already defined the class in the settings.py as below : DEFAULT_FILE_STORAGE = 'proj.storage.FileStorage' Remember when you define the following env variables, you can auto upload files to the specific Images or File fields in the Models, now I want a centralized way of handling the NoSuchKey error and I show a custom page or template AWS_LOCATION = ENV.str('AWS_LOCATION', default='') AWS_ACCESS_KEY_ID = ENV.str('AWS_ACCESS_KEY_ID', default='') AWS_SECRET_ACCESS_KEY = ENV.str('AWS_SECRET_ACCESS_KEY', default='') AWS_S3_REGION_NAME = ENV.str('AWS_S3_REGION_NAME', default='') AWS_S3_SIGNATURE_VERSION = ENV.str('AWS_S3_SIGNATURE_VERSION', default='') AWS_S3_FILE_OVERWRITE = ENV.bool('AWS_S3_FILE_OVERWRITE', default=False) How can I do this ? -
Django not bringing pk to template
I am at the moment practicing my Django-Skills and I am learning a language, so I thought I could combine these two learning paths: I have a models.py class Word(models.Model): English = models.CharField(max_length=50) German = models.CharField(max_length=50) Bahasa_Indonesia = models.CharField(max_length=50) and a class based view, which returns the word-list with a specified language: class WordListByLanguageView(View): '''outputs all the words in a selected language as a list. The link to the detail forwards to word-detail. ''' def get(self, request, language): words = Word.objects.all().values(language) # retrieves only the language field return render(request, 'word_list.html', {'words': words, 'language': language}) I want users to pick which language they want to learn on their dashboard: {% block content %} <h1>User Dashboard</h1> <form method="post" action="{% url 'user-dashboard' %}"> {% csrf_token %} <label for="language">Start learning </label> <select name="language" id="language"> <option value="English">English</option> <option value="German">German</option> <option value="Bahasa_Indonesia">Bahasa Indonesia</option> <!-- Add more language options as needed --> </select> <button type="submit">Start Learning</button> </form> {% endblock %} class UserDashboardView(View): def get(self, request): # Render the user dashboard template return render(request, 'user_dashboard.html') def post(self, request): # Get the selected language from the form submission language = request.POST.get('language') # Redirect to the word list URL with the selected language as a parameter return redirect('word-list-language', language=language) The … -
Vscode extension suggestion not working on some folders
When I tried to create a HTML file inside my django project folder (appfolder/templat/test/page.html) it's not suggesting any tags when I type. But same time it's working on html files that are outside those folder it works perfectly Now I'm creating html file outside and paste it to that folder . How can I solve this ?? -
Firefox can’t establish a connection to the server in django channels echo server
I wrote an echo server with Django Channels, which I will give you the link channels_echo_server When I try to connect to Echo Server, I get this error in the console Firefox can’t establish a connection to the server at ws://127.0.0.1:8000/ws/ Socket closed unexpectedly I get the same error in the Chrome browser I uninstalled and reinstalled Channels and even the Django project several times But it didn't work where is the problem from? -
Django concurrent requests
I'm using Django as a framework, but I'm encountering an issue with concurrent requests. The application consistently responds to (n-1) requests and handles the last one, but it fails to send a response to the end user. I'm seeking assistance to resolve this problem. Can anyone help me with this? -
apache reverse proxy with django authentication and geoserver
i want to use django authentication before redirectiong to geoserver using apache reverse-proxy, i can Redirect to login page but after submitting the /login/?next=/geoserver return me to first page not to geoserver i tried a lot of configuratin but now success: <VirtualHost *:9443> ServerName localhost ProxyPreserveHost On # Proxy requests for GeoServer to Django ProxyPass /geoserver http://localhost:8080/geoserver ProxyPassReverse /geoserver http://localhost:8080/geoserver ProxyPassReverseCookiePath /geoserver / # Redirect /geoserver requests to Django authentication <Location /geoserver> Redirect /geoserver /login/?next=/geoserver </Location> # Proxy all other requests to Django ProxyPass / http://localhost:8000/ ProxyPassReverse / http://localhost:8000/ -
Django - Celery - How to handle complex tasks
Following problem needs to get solved: In my Django project I have to collect, manipulate and save specific data on regular basis. Example: Every minute I have to retrieve data from a heating-system via REST-API and process them Every minute I have to retieve data from a PV-inverter via REST-API and process them Every six hours I have to retrieve data from an external data provider and do some processing on it. After midnight I have to do some calculation on data from previous day ... and more to come in future From my perspective the Django/Celery/Beat approach would fit for above scenarios. I'm aware it's not a real message-based use case - more a batch processing use case to not setup cronjobs. In my Django project I have created apps (for the specific subsystems) and some general packages on project level. Described scenarios can be called (from Python shell and via Bash script outside development via cronjob. Now I tried to use Celery Beat to orchestrate above scenarios. But I'm not able to call the scripts from inside the celery tasks. Simply nothing happens - I guess importing all packages and scripts fail. I worked with several tutorials to … -
Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE
I'm trying to debug url.py in my project but i got this error all the time, I tried almost everything, any ideas? Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.