Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Upload File API Endpoint
so I have a view in my Django website that is supposed to accepted uploaded backup files and save a backup record to the database. It's meant to accept http post requests with a file and user credentials so that I can associate backup uploads to each user. I also created a different script entirely to test if this works and it's been fine when I upload small files but keeps failing when I try and upload large files (e.g. 100mb +). I'm not sure if there's a better way to do this or if I'm making a mistake somewhere. views.py: @csrf_exempt def upload(request): if request.method == 'POST': try: file = request.FILES['file'] # check file type before saving. only allow .zip files if not file.name.endswith('.zip'): return HttpResponse("Invalid file type. Only .zip files are allowed.", status=415) # get the user credentials from the request username = request.POST.get('username') password = request.POST.get('password') # authenticate the user user = authenticate(request, username=username, password=password) if user is None: return HttpResponse("Invalid credentials", status=401) saveDir = os.path.join('backups/', user.username) savePath = os.path.join(saveDir, file.name) storage_left = user.profile.max_storage - user.profile.used_storage backup = Backup(user=user, file=file) backup.file.name = savePath backup.save() if backup.filesize > storage_left: response_str = f"Could not upload file {backup.basename}. " \ … -
What are the appropriate configurations for the WSGIDaemonProcess if memory is not being released?
I have a Django application which is hosted using Apache and a WSGI Daemon Process. It fetches large amounts of data from a database, and I have an issue where it won't release the RAM after completing the request if the request was large and/or many requests come in at the same time. I've tried debugging this without touching the server configuration (since I don't have editing privileges on the server and need to request the change), but my last hope is changing the options on the WSGI Daemon process to mitigate the problem. It is currently set to processes=2 threads=5, nothing else is configured. I have read through the documentation of the different configuration options, but I am unsure what an appropriate configuration for my use case would be. The site doesn't see a lot of traffic (probably only used once or twice a day), but when it IS being used, it will have to handle large amounts of data and 100-500 requests in relatively short sucession. So I don't want to set the maximum-requests too low, but since the site doesn't see traffic regularly, the RAM might never be released if the limit isn't reached. Would a restart-intervall … -
__isnull not working in Django ORM in test method
In my test setup: def setUp(self): self.myitem_1 = mommy.make(MyModel, my_field=None) ... In the test: result = MyModel.objects.my_field__isnull().all() self.assertEqual(result.count(), 1) I was expecting is null to work for None, but doesn't count the value. Test fails as 0 != 1 What am I missing? -
Making a that enables 'GET' without token but not posts without tokens
I recently started working with Django backend development, so I'm still struggling with some features. This time, I've encountered a problem that has been quite challenging, and I couldn't find any helpful answers on the web. I'm creating a view that supports both 'GET' and 'POST' requests. The issue I'm facing is that while I need a Bearer token for the 'POST' request, I don't want to require a token for the 'GET' request. Initially, I considered creating a separate view just for the 'GET' request, but that seemed redundant. Then, I came across the 'IsAuthenticatedOrReadOnly' permission class in the Django Rest Framework documentation. I thought this would solve my problem, but even after implementing this verification, the 'GET' endpoint still asks for a token. Could someone please provide me with some insights? Here's my view: from rest_framework.views import Request, Response, status, APIView from .serializers import MovieSerializer from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework.permissions import IsAuthenticatedOrReadOnly from movies.models import Movie class MovieView(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticatedOrReadOnly] def post(self, request: Request) -> Response: serializer = MovieSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(user = request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) def get(self, request: Request) -> Response: movies = Movie.objects.all() serializer = MovieSerializer(movies, many=True) return Response(serializer.data, status=status.HTTP_200_OK) ...and … -
Django generic List View with multiple query search
Hello I'm working with class based views in Django and I want to create a search form for users to find their own favourite products in my app with multiple filters and excludes but I couldn't do it. my code is here if anyone can modify it to make it right please help me out : models.py from django.db.models import models from django.core.validators import RegexValidators class Product(models.Model): num=RegexValidators(r'^[0-9a-zA-Z]*$') title = models.CharField(max_length=100) embed_id = models.CharField(max_length=15, validators=[num]) description = models.TextField(null=True, blank=True) forms.py from django import forms class ProductSearchForm(forms.Form): title = forms.CharField(required=False) embed_id = forms.CharField(required=False) description = forms.CharField(required=False) views.py from django.views.generic import ListView from .models import Product from .forms import ProductSearchForm class ProductListView(ListView): model = Product form_class = ProductSearchForm template_name = 'pages/product/list_products.html' def get_queryset(self): queryset = super().get_queryset() form = self.form_class(self.request.GET) if form.is_valid(): title = form.cleaned_data.get('title') embed_id = form.cleaned_data.get('embed_id') description = form.cleaned_data.get('description') if title: queryset = queryset.filter(title__icontains=title) if embed_id: queryset = queryset.filter(embed_id__icontains=embed_id) if description: queryset = queryset.filter(description__icontains=description) return queryset def get_context_data(self, [**kwargs): context = super().get_context_data(self, **kwargs): context['form'] = self.form_class(self.request.GET) return context I know how to handle this in Function based views, but I want to create its generic.listview. -
Why isn't it recommended to use bare HTTP status codes in a response?
According to the documentation for Django REST Framework, "using bare status codes in your responses isn't recommended". They recommend instead using the objects from the status module (e.g. status.HTTP_404_NOT_FOUND). My question is, where does this recommendation come from? I wasn't able to find any kind of 'official' source for this recommendation. -
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 …