Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Signin Fails With Custom Errors
Signin is working flawlessly but, Signup returns with {"non_field_errors": ["Incorrect creds"]} Which I have specified in LoginSerializer. I think it's happening due to authenticate function but, I am not able to pinpoint the issue as when I print it, it returns None. Does anybody knows what could be the issue? I have given the whole code but, I reckon the problem is created in LoginSerializer.I have also, added the AUTHENTICATION_BACKENDS in settings.py and after then, it's still gives that error. Models: from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class UserManager (BaseUserManager): def create_user(self, username, password, **extra_fields): if not username: raise ValueError("Username should be provided") user = self.model(username=username, **extra_fields) user.set_password (password) user.save() return user def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(username, password, **extra_fields) class User (AbstractBaseUser): id = models.AutoField (primary_key=True) name = models.CharField(max_length=100) email = models. CharField (max_length=60) password = models. CharField (max_length=16) username = models. CharField (max_length=100, unique=True) USERNAME_FIELD = 'username' objects = UserManager() Serializers: from rest_framework import serializers from .models import User from django.contrib.auth import authenticate class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) email = serializers.CharField(required=False) name = serializers.CharField(required=False) class Meta: model = User fields = ('username', 'password', 'email', 'name') def create(self, validated_data): user = … -
Value error on custom log filter when importing unrelated module
I have the setup below that I'm using to inject extra data from the request object into each log message and it works fine. I recently needed to import a urls.py file from another app into the auth_middleware.py file to check all registered DRF routes and redirect appropriately, but I immediately got ValueError: Unable to configure filter 'session_context' each time I attempt to start the application. The import statement that is triggering this error (called from auth_middleware.py) looks like this: from apps.app_name.api.urls import router proj/middleware/auth_middleware.py import threading local = threading.local() class CheckUserLogin: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): setattr(local, "uip", request.META.get("REMOTE_ADDR")) setattr(local, "sid", request.session.session_key or "n/a") if request.user.is_anonymous and request.path != reverse("auth_service_login"): # apply redirect login and send to url_login return HttpResponseRedirect(url_login) return self.get_response(request) services/log_ctx.py import logging from proj.middleware.auth_middleware import local class ExtraLogCtx(logging.Filter): def filter(self, record): defs = "n/a" record.uip = getattr(local, "uip", defs) record.sid = getattr(local, "sid", defs) return True proj/settings.py MIDDLEWARE = [ ... "proj.middleware.auth_middleware.CheckUserLogin", ] LOGGING = { "filters": { "session_context": { "()": "services.log_ctx.ExtraLogCtx", }, }, "handlers": { "console": { ... "filters": ["session_context"], ... }, }, } I have __init__.py in the services and middleware folders and am unsure where else to look. Any … -
Stream Zeros with Django with StreamingHttpResponse
I have to send an amount of Zeros as response, defined by the request. They have to be plain zeros. (I know, a rather odd task...) so, for example, you need 100mb of zeros, you query ?size=100&unit=mb, you will get a stream of 100mb only zeros. Since it can be up to 16gb of zeros, I do not want to generate them at first, rather generate a stream of zeros and send this "line by line". This is what I came up with, but it does not behave like I want because it first gathers the full data and then sends it. class CreateImageAndResponseView(View): line_count = 0 def get(self, request): size_str = request.GET.get('size', '') unit = request.GET.get('unit', '').lower() if unit not in ('gb', 'mb'): return HttpResponse(status=400) try: size = float(size_str) if unit == 'gb': size_bytes = int(size * 1024**3) else: size_bytes = int(size * 1024**2) except ValueError: return HttpResponse(status=400) self.line_count = size_bytes // 1024 return StreamingHttpResponse((b'0' * 1024 for _ in range(0, self.line_count)), content_type='application/octet-stream',) I already saw Problem with Django StreamingHttpResponse, but I do not know which middleware could block this. Also, I am not running nginx or apache, just django from my console. -
Django - Custom User Model Signal Issue: Token Creation Occurs Before User Is Persisted to Database
CustomUser extends User from django.contrib.auth.models class CustomUser(User): user_id = models.IntegerField(primary_key=True) has_mod_rights = models.BooleanField() picture = models.BinaryField(null=True, blank=True) description = models.CharField(max_length=150, null=True, blank=True) is_premium = models.BooleanField() unban_date = models.DateField(null=True, blank=True) and my signal should be triggered when new CustomUser is created @receiver(post_save, sender=DishDiscoverUser) def create_auth_token(sender, instance=None, created=False, **kwargs): if created and instance.pk: token = Token.objects.create(user=instance) the registration view: @api_view(['POST', ]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): user = serializer.save() # breakpoint() data['response'] = 'successfully registered a new user' data['email'] = user.email data['username'] = user.username token = Token.objects.get(user=user).key data['token']=token else: data: serializer.errors return Response(data) and serializer: class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) class Meta: model = CustomUser fields = ['username', 'password', 'password2', 'email', 'first_name', 'last_name'] def create(self, validated_data): user = CustomUser( email=self.validated_data['email'], username=self.validated_data['username'], has_mod_rights=False, is_premium=False, ) password = self.validated_data['password'] password2= self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Password must match!'}) user.set_password(password) user.save() return user and i get FAILED authorisation/tests/test_auth.py::test_registration - ValueError: Model instances passed to related filters must be saved. Error when running @pytest.mark.django_db def test_registration(): client = APIClient() # Prepare data for a valid registration valid_data = valid_login_data()[0] url = '/api/auth/register' response = client.post(url, valid_data) assert response.status_code == 200, response.json() assert … -
Django rendered content is different in console.log from page source
I have the following code in my django view project: if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): datas = Order() datas.user = current_user datas.save() current_datetime = datetime.datetime.now().strftime('%Y%H%S%m%M%d') order_number = current_datetime + str(datas.id) datas.order_number = order_number datas.save() order = Order.objects.get(user=current_user, is_ordered=False, order_number=datas.order_number) context['order'] = order context['user'] = request.user return render(request, 'orders/order.html', context) Inside order.html, I have: <script> console.log('order number 0: ', {{ order.order_number }}) </script> When I view the page source and browser console, the values of {{ order.order_number }} are different. Browser console.log shows wrong values for str(datas.id) part whereas the rest of the part of {{ order.order_number }} is same in both console.log and page source. -
How can I fix the metaclass conflict in django-rest-framework Serializer
I've written the following code in django and DRF: class ServiceModelMetaClass(serializers.SerializerMetaclass, type): SERVICE_MODELS = { "email": EmailSubscriber, "push": PushSubscriber } def __call__(cls, *args, **kwargs): service = kwargs.get("data", {}).get("service") cls.Meta.subscriber_model = cls.SERVICE_MODELS.get(service) return super().__call__(*args, **kwargs) class InterListsActionsSerializer(serializers.Serializer, metaclass=ServiceModelMetaClass): source_list_id = serializers.IntegerField() target_list_id = serializers.IntegerField() subscriber_ids = serializers.IntegerField(many=True, required=False) account_id = serializers.CharField() service = serializers.ChoiceField(choices=("email", "push")) class Meta: subscriber_model: Model = None def move(self): model = self.Meta.subscriber_model # Rest of the method code. The purpose of this code is that this serializer might need doing operation on different models based on the service that the user wants to use. So I wrote this metaclass to prevent writing duplicate code and simply change the subscriber_model based on user's needs. Now as you might know, serializers.Serializer uses a metaclass by its own, serializers.SerializerMetaclass. This results in the following error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases. I tried making my ServiceModelMetaClass metaclass to inherit from serializers.SerializerMetaclass but it gave me this error: File "/project-root/segment_management/serializers/subscriber_list.py", line 33, in <module> class InterListsActionsSerializer(serializers.Serializer, metaclass=ServiceModelMetaClass): File "/project-root/segment_management/serializers/subscriber_list.py", line 36, in InterListsActionsSerializer subscriber_ids = serializers.IntegerField(many=True, required=False) File "/project-root/.venv/lib/python3.10/site-packages/rest_framework/fields.py", line 894, in __init__ super().__init__(**kwargs) TypeError: Field.__init__() … -
How to add a new value to model at the very beginning, shifting the ID of other values by 1?
models.py: class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) ordering = models.IntegerField(default=0) is_featured = models.BooleanField(default=False) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Category, self).save(*args, **kwargs) def __str__(self): return self.title class Meta: ordering = ['ordering'] verbose_name_plural = 'Categories' def get_absolute_url(self): return '/%s/' % (self.slug) class SubCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) ordering = models.IntegerField(default=0) is_featured = models.BooleanField(default=True) category = models.ForeignKey( Category, related_name='subcategory', on_delete=models.CASCADE ) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(SubCategory, self).save(*args, **kwargs) class Meta: ordering = ['ordering'] verbose_name_plural = 'SubCategories' def __str__(self): return self.title def get_absolute_url(self): return '/%s/%s/' % (self.category, self.slug) class SubSubCategory(MPTTModel): parent = TreeForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=50) slug = models.SlugField(null=False, unique=True) sub_category = models.ForeignKey( SubCategory, related_name='subsubcategory', on_delete=CASCADE, null=True ) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: verbose_name_plural = 'Sub_subcategories' class MPTTMeta: order_insertion_by = ['title'] def get_absolute_url(self): return reverse('susubcategory_detail', kwargs={'slug': self.slug}) def __str__(self): full_path = [self.title] k = self.parent while k is not None: full_path.append(k.title) k = k.apparent return ' / '.join(full_path[::-1]) class Attribute(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(SubSubCategory, related_name='attribute_categories', on_delete=models.CASCADE) def __str__(self): return self.name class AttributeChoice(models.Model): category = models.ForeignKey( SubSubCategory, related_name='attribute_choice_categories', on_delete=models.CASCADE, null=True ) attribute = ChainedForeignKey( Attribute, chained_field="category", chained_model_field="category", show_all=True, auto_choose=True, sort=True, null=True, … -
Using a check box in a web application
Am trying to create a TodoList where a user clicks a checkbox to tick checked when complete is true , but am not understanding the concept with checkboxes. just recently started learning django , the below code is what l have come up with. Model Code from django.db import models # Create your models here. class List(models.Model): list_title = models.CharField(max_length = 200) list_context = models.CharField(max_length = 200) pub_date = models.DateTimeField() complete = models.BooleanField(default=False) def __str__(self): return self.list_title view code from django.shortcuts import render from .models import List # Create your views here. def index(Request): list_items = List.objects.order_by('-pub_date') list_ticked =[] if Request.method == "Post": list_ticked = Request.Post.getlist('items') if list_ticked== True: complete = True context = { 'list_items':list_items, 'list_ticked':list_ticked, } template = 'TodoList/index.html' return render (Request,template,context) Html Code <ul class="list-group mb-0"> <form action="" method="post"> {%if list_items%} {%for item in list_items %} <li class="list-group-item d-flex justify-content-between align-items-center border-start-0 border-top-0 border-end-0 border-bottom rounded-0 mb-2"> <div class="d-flex align-items-center"> <input class="form-check-input me-2" type="checkbox" value="{{item.id}}" id="item {{forloop.counter}}" name="list_ticked =[]" /> {{item.list_context}} </div> <a href="#!" data-mdb-toggle="tooltip" title="Remove item"> <i class="fas fa-times text-primary"></i> </a> </li> {%endfor%} {%else%} <p>No list available</p> {%endif%} </form> </ul> <ul class="list-group mb-0"> <form action="" method="post"> {%if list_items%} {%for item in list_items %} <li class="list-group-item d-flex … -
The task in Celery is being passed from Celery Beats to Workers, and is being received there but the task is not being executed. I am using Django
Pretty much the title. The task is being passed and received properly but isn't getting executed. So I just kept a simple print statement, it still didn't execute. What I did notice was, in the admin interface, the task is being set as type 'custom' instead of 'registered' although it has same name as that of the registered task I am trying to execute. Am I missing something? Celery config in settings.py celery.py tasks.py Django admin interface. The task is made custom type although there is already a registered task of same name Beat log Worker log What could be the problem? Tried prompting Chat GPT, Bard and Bing, I had already performed everything they suggested. The documentation was less useful. -
Django doesnt render Form
When I request the url in the browser, django does not render the form defined in the forms.py but only the hardcoded html in bulk_import.html. bulk_import.html {% extends 'score/base.html' %} {% load static %} {% block content %} <div class="container my-5"> <h1>Bulk Import</h1> <form action="" method=POST> {% csrf_token %} {{ form2 }} <input type="submit" value="Absenden" class="btn btn-secondary"> </form> </div> {% endblock %} forms.py class BulkModulImport(forms.Form): text = forms.Textarea(attrs={'class': 'form-control', 'rows': '4'}) views.py def bulk_modul_import(request): submitted = False if request.method == "POST": form = BulkModulImport(request.POST) if form.is_valid(): def remove_dots_and_numbers(text): lines = text.split('\n') updated_lines = [] for line in lines: # Use regular expression to remove dots and numbers at the end of each line updated_line = line.replace(' .', '') updated_line = re.sub(r'\s*\d*$', '', updated_line) if "Module der Lehreinheit" not in updated_line: Modul(title=line,proposer=request.user, dozent=None, created_date=timezone.now(), description="").save() updated_lines.append(updated_line) remove_dots_and_numbers(form.cleaned_data['text']) messages.success(request, ('Du hast erfolgreich einen Bulk-Import der Module durchgeführt!')) return HttpResponseRedirect(reverse('modul_list')) else: form2 = BulkModulImport() return render(request, 'score/bulk_import.html', {'form2': form2}) -
NoReverseMatch on extra enpoint in GenericViewSet
urls.py app_name = "auth" urlpatterns = [ path("token/", TokenObtainPairView.as_view(), name="token_obtain_pair"), path("token/refresh/", TokenRefreshView.as_view(), name="token_refresh"), path( "password/confirm/<str:uid>/<str:token>/", PasswordResetViewSet.as_view({"post": "password_reset_confirm"}, name="password_reset_confirm"), ), path( "password/reset/", PasswordResetViewSet.as_view({"post": "send_reset_password_link"}), name="password_send_link", ), ] views.py class PasswordResetViewSet(GenericViewSet): def get_permissions(self): return [permissions.AllowAny()] def get_serializer_class(self) -> type[Serializer]: action_serializer_map = { "send_reset_password_link": ResetPasswordSerializer, "confirm_password_changed": ResetPasswordConfirmSerializer, } return action_serializer_map[self.action] @extend_schema(request=ResetPasswordSerializer, responses={201: {}, 404: {}}) @action(methods=["POST"], detail=False) def send_reset_password_link(self, request): serializer = ResetPasswordSerializer(data=request.data) serializer.is_valid(raise_exception=True) return Response( data=reset_password_link_service( email=serializer.validated_data.get("email") ) ) @extend_schema( request=ResetPasswordConfirmSerializer, ) @action(methods=["POST"], detail=False) def password_reset_confirm(self, request): return Response() Trying to do reverse("auth:password_reset_confirm", kwargs={uid: uid, token: token}) gives me NoReverseMatch. Really do not know what is going wrong here... Suggestions? Adding usual FBV to the same namespace "auth" works great. -
disable people from downloading pdf
I have a library system where we publish books but unfortunately people download them and bad enough they reprint them and sell, the system is written in django and I am a newbie on python so far I do not know what to do -
I have issue after hosting my django app, working completely fine in ip address all the django style are working but not working in domain?
See in IP address its working fine without any prblemsSee but in domain the styles are not working i don't know what to change and where i made a mistake Problem in domain hosting Can someone check it and resolve my issue to make django app working flauless in domain I have tried to change the Gunicorn confg and run in gunicorn but it doesnt make any changes so again i run in normal python runserver command. -
Configure an nginx proxy to two applications, a Flask and a Django, via two locations /v1 for Flask and /v2 for Django
I am hosting two Applications on same Server. A Flask App and a new Django App. Flask is startet at local server 127.0.0.1:5000. New Django App is startet at local server 127.0.0.1:8000. In my nginx default Configuration File i added a new location Block for the new Django App and i try something like this: # Nginx Config server { listen 80; server_name my-subdomain.my-domain.com; rewrite ^ https://$server_name$request_uri? permanent; } server { listen 443 default_server ssl; server_name 127.0.0.1; ssl_certificate /etc/letsencrypt/live/my-subdomain.my-domain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/my-subdomain.my-domain.com/privkey.pem; # Old configuration before new Django App #location / { # include proxy_params; # proxy_pass http://127.0.0.1:5000; #} # Default location (version 1) location / { proxy_pass http://127.0.0.1:5000; include /etc/nginx/proxy_params; proxy_redirect off; } # Version 1 explicit location /v1 { rewrite ^/v1(.*) /$1 break; proxy_pass http://127.0.0.1:5000; include /etc/nginx/proxy_params; proxy_redirect off; sub_filter 'href="/' 'href="/v1/'; sub_filter_once off; } merge_slashes on; # Version 2 location /v2 { rewrite ^/v2(.*) /$1 break; proxy_pass http://127.0.0.1:8000; include /etc/nginx/proxy_params; proxy_redirect off; sub_filter 'href="/' 'href="/v2/'; sub_filter_once off; } } Here is a View of my Django URLS Configuration: urlpatterns = [ path('admin/', admin.site.urls), path("shortener/", include("urlshortener.urls")), path('projects/', include('projects.urls')), ] Now the Problem is, when i access https://my-subdomain.my-domain.com/v2/admin I get from Django : Page not found (404) Request Method: GET … -
Creating a logout functionality in Django, however I am getting a HTTP Error 405 when trying to load the page. How do I fix it?
I am creating a blog site. I have found out you are now supposed to use a POST request for Logout, however I did this and I am not sure where I have gone wrong. Here is the relevant code: urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('blog.urls')), ] logout.html {% extends "blog/base.html" %} {% block content %} <h2>You have been logged out</h2> <div class="border-top pt-3"> <form action="{% url 'logout' %}" method="post"> {% csrf_token %} <button type="submit" class="btn btn-primary">Logout</button> </form> <small class="text-muted"> <a href="{% url 'login' %}">Log In Again</a> </small> </div> {% endblock content %} views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in.') return redirect('login') else: form = UserRegisterForm() return render (request, 'users/register.html', {'form': form}) @login_required def profile(request): return render(request, 'users/profile.html') Even tried using Chatgpt to help me, and … -
react+django+rest_framework+jwt API refresh token sometimes response 401 Unauthorized
My problem is most of the time the token refreshed ok. Sometimes when I refresh manually, the server responds 401. If I refreshed again, the server responds 200. Not sure why. The django server side shows: Unauthorized: /api/token/refresh/ [28/Jan/2024 16:44:04] "POST /api/token/refresh/ HTTP/1.1" 401 58 [28/Jan/2024 16:44:04] "GET /api/ HTTP/1.1" 200 109 [28/Jan/2024 16:48:05] "POST /api/token/refresh/ HTTP/1.1" 200 531 [28/Jan/2024 16:52:06] "POST /api/token/refresh/ HTTP/1.1" 200 531 [28/Jan/2024 16:56:07] "POST /api/token/refresh/ HTTP/1.1" 200 531 [28/Jan/2024 17:00:08] "POST /api/token/refresh/ HTTP/1.1" 200 531 Frontend react code: context.js const refreshToken = async ()=>{ let localToken = JSON.parse(localStorage.getItem('authToken')) console.log(localToken) if (localToken){ try{ const res = await fetch(apiUrl + 'token/refresh/',{ method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ 'refresh': localToken.refresh }), }) if (!res.ok){ // if(res.status === 401){ // handleLogout(localToken) // } throw Error } const data = await res.json() setToken(data) setUser(jwtDecode(data.access).username) if(isInit){ setIsInit(false) } localStorage.setItem('authToken', JSON.stringify(data)) } catch (err){ console.log(err) } } } App.js useEffect(()=>{ if(!isLogin){ if(isInit){ refreshToken() } else{ console.log('interval') const interval = setInterval(()=>{ refreshToken() },1000*60*4) return ()=> clearInterval(interval) } } },[token]) backend urls.py I use the built-in Tokenrefreshview. urlpatterns = [ path('', PostList.as_view(), name='listcreate'), path('<int:pk>/', PostDetail.as_view(), name='detailcreate'), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] -
Using Custom Template Tag Inside Built in tags of Django
I have created a simple tag as below. @register.simple_tag(takes_context=True,name="calculate_billamount") def calculate_billamount(quantity,unitprice): return (quantity * unitprice) {% for order_detail in order_details %} {% if order_detail.orderid == order %} <tr> <td>{{order_detail.productid.productname}}</td> <td>{{order_detail.unitprice}}</td> <td>{{order_detail.quantity}}</td> <td>{% calculate_billamount quantity=5 unitprice=4 %} </td> <td>{{billamount}}</td> </tr> {% endif %} {% endfor %} This is just multiplying 2 numbers and returning the result. I am trying to use above simple tag inside a FOR and IF as shown below. I am getting below error. enter image description here when i try this individually, i am not getting any error i.e. it is working fine. <div> {% calculate_billamount quantity=5 unitprice=4 %} </div> Is there any restriction, that we cant use Custom Simple Template tags inside django built in template tags like for and if? Thanking you. -
django collectstatic not working with s3 backend behind nginx
I have a minio server as my object storage which django uses as its Static file storage (using django-minio-storage). I have set up an Nginx server to proxy minio. When I run the collectstatic command, it gets stuck in the first file and does not put the files to minio. Here is my config: settings.py DEFAULT_FILE_STORAGE = "minio_storage.storage.MinioMediaStorage" STATICFILES_STORAGE = "minio_storage.storage.MinioStaticStorage" MINIO_STORAGE_ENDPOINT = config("MINIO_STORAGE_ENDPOINT", "") MINIO_STORAGE_ACCESS_KEY = config("MINIO_STORAGE_ACCESS_KEY", "") MINIO_STORAGE_SECRET_KEY = config("MINIO_STORAGE_SECRET_KEY", "") MINIO_STORAGE_MEDIA_BUCKET_NAME = config("MINIO_STORAGE_MEDIA_BUCKET_NAME", "") MINIO_STORAGE_STATIC_BUCKET_NAME = config("MINIO_STORAGE_STATIC_BUCKET_NAME", "") MINIO_STORAGE_USE_HTTPS = True MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET = True MINIO_STORAGE_AUTO_CREATE_STATIC_BUCKET = True MINIO_STORAGE_MEDIA_OBJECT_METADATA = {"Cache-Control": "max-age=3600"} nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 500; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; error_log /dev/stdout; gzip on; server { listen 80; server_name _; ignore_invalid_headers off; client_max_body_size 0; proxy_buffering off; proxy_request_buffering off; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; real_ip_header X-Real-IP; proxy_connect_timeout 300; proxy_http_version 1.1; proxy_set_header Connection ""; chunked_transfer_encoding off; add_header Access-Control-Allow-Origin "*"; proxy_pass http://minio.svc:9000; } } } collectstatic -v3 result: Deleting 'admin/js/actions.js' the collectstatic command … -
Import package plugin to Django project
I have Python project in which i have plugins with setup.py and Django project in the same level. I want to use those plugins I made inside of Django app views but it cannot find modules I am trying to pass. graph_explorer is Django project. app_platform is Python package plugin which is not django app. api is another Python package plugin which is not django app. In home/views.py I am just trying to call method of app_platform dummy method and I am getting ModuleNotFoundError app_platform. Then i put this code inside of settings.py of Django projcet I get pass first ModuleNotFoundError for app_platform but now I get ModuleNotFoundError for api package which was imported inside of app_platform -
Optimizing Performance in a Django Application
How can I optimize my Django app to improve performance? When load testing my app, the response times start degrading significantly after a moderate number of concurrent users. I need strategies to help it maintain speed as usage increases. I tried caching template fragments and database queries using Django caching framework. I expected this would reduce the load on the database and speeds up rendering, but I didn't see much improvement in my tests. I profiled the app using Django debug toolbar and found some views were running inefficient queries. I attempted to refactor the queries and models, but the performance impact was minimal. I'm not sure what else could be optimized. I added database indexes on the most common query filters and ordering, hoping this would speed up the database operations. However, the speed up was not very significant under load. I deployed the app to a larger server with more CPUs, RAM and SSD storage hoping the increased resources would allow it to handle more load. But I'm still seeing slowdowns and need to optimize the code itself. I expected optimizing templates down to single queries and caching would get page speeds to below 500ms but I'm still … -
How to create hostpath PV for db.sqlite3 database in minikube
I'm building a project(frontend+backend+DB), containerize it, & deploy it on minikube(single node cluster). Due to absence of PV, I lost the data after pod update. Trying to figure out how I can create a PV for hostpath & keep that database on that storage for data persistance. File structure I tried out to link deployment.yml with pvc.yml & pvc.yml with pv.yml. While executing pv.yml file giving node affinity error & host path error. can't find how to resolve the error. settings.py for DB config service.yml pv.yml apiVersion: v1 kind: PersistentVolume metadata: name: mlh-pv spec: capacity: storage: 500Mi accessModes: - ReadWriteOnce hostPath: path: /home/parth/storage-mlh type: DirectoryOrCreate pvc.yml apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mlh-pvc spec: volumeName: mlh-pv storageClassName: manual resources: requests: storage: 500Mi volumeMode: Filesystem accessModes: - ReadWriteOnce deployment.yml (spec section) spec: selector: matchLabels: app: mlh-with-hostpath template: metadata: labels: app: mlh-with-hostpath spec: containers: - name: mlh-with-hostpath image: parth721/django-mlh:4.2 volumeMounts: - name: www-hostpath-storage mountPath: /app/db.sqlite3 resources: limits: memory: "300Mi" cpu: "500m" ports: - containerPort: 8000 volumes: - name: www-hostpath-storage hostPath: path: /home/parth/storage-mlh type: DirectoryOrCreate -
How to Build a Django CreateView with a Pre-Populated ForeignKey Field
I have the following two Django models: class Item(models.Model): description = models.CharField(max_length=250) total_quantity = models.PositiveSmallIntegerField(default=0) def get_absolute_url(self): return reverse_lazy('inventory-item-details', kwargs={'pk': self.pk}) class PurchaseEntry(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) ... I am displaying all of the Item objects I have inside a table. I added a link next to each row item. The link is labeled "Create a Purchase Entry", when opening the link it should display a form for creating PurchaseEntry objects (I'm going to use a generic CreateView for this). Everything is easy with the exception of one key part. When opening the form, I want the Item to be prepopulated with the one I just clicked on its link, so the user won't have to select from a list of items again. The only thing that came to mind was to include the Primary Key when navigating into the form, and use that primary key to select one of the options. But I honestly don't know how to implement this, it's just an idea at the moment, maybe you have a better one? Just for context, and in order for you to help me better here's some more code: My views file: class ItemListView(LoginRequiredMixin, generic.ListView): template_name = 'inventory/home.html' context_object_name … -
Using Django signals during the update instance
I have a project on Django Rest Framework, RabbitMQ and Celery. After sending a post request to create a mailing instance via API, Celery should send messages, and the Celery task number is saved in the mailing instance. The same should happen if you create a mailing instance in the Django admin panel. The mailing instance can be edited both through API and through the Django admin panel (in this case, the outdated Celery task is deleted and a new one is created, the number of the new Celery task is saved in the mailing instance). I solved this problem by overriding the methods in ModelViewSet (DRF) and ModelAdmin (Django). But I would like to solve the problem by using Django signals (on the one hand, this worsens the readability of the code, on the other hand, it eliminates the need to redefine methods). There are no problems with creating and deleting mailing instances and Celery tasks. But I can't create a signal that correctly handles the mailing instance update (the pre_save and post_save signals trigger a cyclic update of the mailing object). Mailing instance update -> a signal is triggered -> a Celery task is created -> the task … -
How Read Replica in django Tenants
I am using Django Tenant for its excellent ability to share a PostgreSQL database in a schema-based manner, which has significantly improved performance for my customers' queries. However, I now need to integrate a read replica for the database to generate reports for my users without impacting the performance of write operations. 've decided to utilize Django's default routing system for this purpose, but I'm encountering some challenges in getting it to work seamlessly with Django Tenants. After extensive research, I found a feature in Django Tenants that seems promising: EXTRA_SET_TENANT_METHOD_PATH (Django Tenants Documentation). However, I'm struggling to find examples or clear guidance on how to implement this correctly. Here's my current setup with the default Django router system: class DatabaseRouter(object): def db_for_read(self, model, **hints): """ Reads go to the read replica. """ return 'replica' def db_for_write(self, model, **hints): """ Writes always go to primary. """ return 'default' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the primary/replica pool. """ db_list = ('default', 'replica') if obj1._state.db in db_list and obj2._state.db in db_list: return True return None I understand that EXTRA_SET_TENANT_METHOD_PATH could be the key to solving this issue, but I'm not sure … -
How do I upload a decoded image to imageField using ContentFile?
Context: I'm creating a chat app in Django, when the user sends an image to a chat the image data get encoded into base 64 (using btoa() javascript func) and get sent to the server so the server could create a new message and store it in the database. This is my model: class Message(models.Model): sender_user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(blank=False, null=False) image = models.ImageField(blank=True, null=True, upload_to='messages/') date = models.DateTimeField(default=timezone.now) chat = models.ForeignKey(Chat, on_delete=models.CASCADE) def __str__(self) -> str: return self.text Problem: Whenever I use a decoded (base 64) image data as the content in the ContentFile class the content seems to be corrupted and the result image in the database can't be opened by any program. This is the code def create_message( self, sender_user_id: Union[str, int], text: str, image: Optional[str], chat_id: Union[str, int], ) -> None: """Creates and stores a new message object in the database. Args: sender_user_id (Union[str, int]): The id (numeric value) of the user that sent the message. text (str): What the message says. image (str): The encoded image data in base64 encoding. chat_id (Union[str, int]): The id (numeric value) of the chat that the sender sent this message on. """ sender_user_instance = User.objects.get(id=sender_user_id) chat_instance = …