Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AJAX Filtering with jQuery and Django Not Updating Product List
I am working on a project where I need to filter products based on selected categories and vendors using AJAX with jQuery and Django. However, despite no errors in the console, the product list is not updating as expected. Here are the relevant parts of my code: JavaScript: $(document).ready(function(){ $(".filter-checkbox").on("click",function(){ console.log("A checkbox have benn clicked"); let filter_object = {} $(".filter-checkbox").each(function(){ let filter_value = $(this).val() let filter_key = $(this).data("filter") // console.log("Filter value is:", filter_value); // console.log("Filter key is:", filter_key); filter_object[filter_key] = Array.from(document.querySelectorAll('input[data-filter = '+ filter_key +']:checked')).map(function(element){ return element.value }) }) console.log("Filter object is:", filter_object) $.ajax({ url: '/filter-product', data: filter_object, dataType: 'json', beforeSend: function(){ console.log("Trying to filter Product...") }, success: function(response){ console.log(response); console.log("Data filtered successfully..."); $("#filtered-product").html(response.data) } }) }) }) Django Views: def filter_product(request): categories = request.GET.getlist("category[]") vendors = request.GET.getlist("vendor[]") products = Product.objects.filter(product_status="published").order_by("-id").distinct() if len(categories) > 0: products = products.filter(cagtegory__id__in = categories).distinct() if len(vendors) > 0: products = products.filter(vendor__id__in = vendors).distinct() context = { "products":products } data = render_to_string("core/async/product-list.html",context) return JsonResponse({"data":data}) Template: <div class="showcase" id="filtered-product"> {% for p in products %} <div class="showcase-banner"> <img src="{{p.image.url}}" width="300" class="product-img default"> <img src="{{p.image.url}}" width="300" class="product-img hover"> <p class="showcase-badge">15%</p> <div class="showcase-actions"> <button class="btn-action"> <ion-icon name="heart-outline"></ion-icon> </button> <button class="btn-action"> <ion-icon name="eye-outline"></ion-icon> </button> <button class="btn-action"> <ion-icon name="repeat-outline"></ion-icon> </button> … -
Payment Gateway Integration with Django
I'm integrating payment gateway APIs in my application (Django). I have written a class PaymentGateway that provides all the methods for all payment related utility. The __init__ initialises the payment gateway client as self.client so that it's available across all methods. But, I need help in making a decision on how to use it. Is it OK if I instantiate and use the payment gateway object across the program, whenever I need it? OR Should I maintain a single instance of it across the whole application? Need help in understanding what could be pros and cons or any other suggestion so that I can make this decision. My current code looks something like below right now: class PaymentGateway: def __init__(self): self.client = PG(api_key="api_key") def create_intent(self, user): return self.client.intents.create(customer_id=user.email) def get_user_id(email): return self.client.users.retrieve(customer_id=email) class MyView(GenericAPIView): def get(self, request): pg_instance = PaymentGateway() intent = pg_instance.create(request.user) return Response({"user_id": get_user_id(request.user), "intent": intent}) # Somewhere in utils.py def get_user_id(user): pg = PaymentGateway() return pg.get_user_id(user.email) -
runser can't serve media if MEDIA_URL is within STATIC_URL, even different settting
In my server,django and nginx is deployed on ECS fargate and connected to loadbalancer, but URL is transferd by Akamai https://www.exmplae.com/company/playground/* -> https://amazonloadbalancer/* So,https://www.exmplae.com/company/playground/ is the url in browser. I have this error django on server (DEBUG=TRUE) runser can't serve media if MEDIA_URL is within STATIC_URL However in this case I have only static setting, no media settings. STATIC_URL = "static/" STATIC_ROOT = "static/" So I just added the media setting in settings.py = STATIC_URL = "static/" STATIC_ROOT = "static/" MEDIA_URL = 'media/' MEDIA_ROOT = 'media/' However , strangely the same error runser can't serve media if MEDIA_URL is within STATIC_URL occurs. How can I fix this? -
Handle Http 302 response on Django view and Javascript async function
For strict security, how can I implement redirect on Django view in response to a JS async call that only updates a div InnerHTML? That is the first preference. I tried JS client-side redirect in multiple ways. It didn't work either. JS keeps rendering home page as InnerHTML in the div. When user's session is ended, server returns 302 Location: /. To take the user to the home page. View @csrf_protect def edit_form(request): if not request.user.is_authenticated: return redirect('/') form = userForm() return render(request, 'edit_form.html', {'form': form}) JS async function fetch_form() { try { const response = await fetch('http://192.168.1.10:8000/edit_form',{ method: 'GET', }); if (!response.ok) { //redirect didn't work const redirectUrl = response.headers.get('Location'); console.log(redirectUrl); window.location.href = redirectUrl; //throw new Error('Network response was not ok ' + response.statusText); } else if (response.status === 302) { //redirect didn't work const redirectUrl = response.headers.get('Location'); console.log(redirectUrl); window.location.href = redirectUrl; } document.getElementById('firstModal').innerHTML = data; } catch (error) { console. Error('There has been a problem with your fetch operation:', error); } }; async function fetch_form() { try { const response = await fetch('http://192.168.1.10:8000/edit_form',{ method: 'GET', }); if (!response.ok){ throw new Error('Network response was not ok ' + response.statusText); } document.getElementById('firstModal').innerHTML = data; } catch (error) { if (error.response.status … -
Django Auto Assigning Author to the user creating the post
I am having an issue with my Author being auto-assigned, it was previously working but has stopped working since I added some inline formsets- Here is my model: class Recipe(models.Model): title = models.CharField(max_length=100) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) serving = models.PositiveIntegerField(default=1) temperature = models.PositiveIntegerField(default=1) prep_time = models.PositiveIntegerField(default=1) cook_time = models.PositiveIntegerField(default=1) ##tags = models.ManyToManyField('Tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('recipes-detail', kwargs={"pk": self.pk}) def __str__(self): return self.title Unsure if maybe some of my other code could be overriding this? This is my form: class RecipeForm(forms.ModelForm): class Meta: model = Recipe exclude = ['author', 'created_at', 'updated_at'] def __init__(self, *args, **kwargs): super(RecipeForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('title'), Field('description'), Field('temperature'), Field('serving'), Field('prep_time'), Field('cook_time'), ) ) If I set blank=True, null=True in the model, it allows the form to go through but with no author associated- Even any indication to what could be causing my issue would be hugely helpful! Many Thanks -
binascii.Error: Invalid base64-encoded string: number of data characters (41) cannot be 1 more than a multiple of 4
I'm trying to use py-vapid, pywebpush, and django-push-notifications to send notifications via Webpush. When I try to send a test notification from the django admin website, I get this traceback log in the console: | Internal Server Error: /djangoadmin/push_notifications/webpushdevice/ | Traceback (most recent call last): | File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 518, in thread_handler | raise exc_info[1] | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 38, in inner | response = await get_response(request) | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 233, in _get_response_async | response = await wrapped_callback(request, *callback_args, **callback_kwargs) | File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 468, in __call__ | ret = await asyncio.shield(exec_coro) | File "/usr/local/lib/python3.8/site-packages/asgiref/current_thread_executor.py", line 40, in run | result = self.fn(*self.args, **self.kwargs) | File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 522, in thread_handler | return func(*args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/options.py", line 616, in wrapper | return self.admin_site.admin_view(view)(*args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view | response = view_func(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func | response = view_func(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 232, in inner | return view(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper | return bound_method(*args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view | response = view_func(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1723, in changelist_view | response = self.response_action(request, … -
COUNT(DISTINCT <col>) without GROUP BY
In Django, Count("col", distinct=True) can be used to perform COUNT(DISTINCT col) but it automatically adds a GROUP BY so is there a way to prevent that from happening so the distinct count of all rows that match the WHERE can be received? -
Why we should install postgresql in the Django container?
Why is necessary install postgresql as dependency in a Django backend container? the Django app is intended to connect to a PostgreSQL DB running in a separate container. I have the next Dockerfile: # pull official base image FROM python:3.12.4-slim-bookworm # set working directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # new # install system dependencies RUN apt-get update \ && apt-get -y install gcc postgresql \ && apt-get clean # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # add app COPY . . And I have the next docker-compose.yml file: services: movies: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8009:8000 env_file: - ./app/.env.dev depends_on: - movies-db movies-db: image: postgres:16 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=movies - POSTGRES_PASSWORD=movies - POSTGRES_DB=movies_dev volumes: postgres_data: This is the case in the course "Test-Driven Development with Django, Django REST Framework, and Docker" by testdriven.io Thanks in advance. -
Better directory structure for Django projects with git perspective
I'm new to Django and trying to decide between two different directory structures. I want to understand the implications of each structure from git perspective and also which one is more favorable in the industry or common practice. Method 1 . ├── .git ├── mysite │ ├── manage.py │ └── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── README.md Method 2 . ├── .git ├── manage.py ├── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── README.md created a few projects with both the structures and want to stick to one or atleast have a favourite. -
Incorrect Redirection to Login Page from Profile and Logout Links After User Login
Context: I’m working on a Django project where I have implemented user authentication with profile and logout functionality. The issue I'm encountering is that when I try to access the profile or logout links from the navbar, it redirects me to the login page instead of navigating to the user's profile or performing logout. Profile Link: Should navigate to the user's profile page if the user is logged in. Logout Link: Should log out the user and redirect to the homepage. Current Setup: Templates (base.html): {% if logged_in %} <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {{ customer_name }} </a> <ul class="dropdown-menu" aria-labelledby="userDropdown"> <li><a class="dropdown-item" href="{% url 'profile' %}?email={{ customer_email }}">Profile</a></li> <li><a class="dropdown-item" href="{% url 'logout' %}">Logout</a></li> </ul> {% else %} <a class="nav-link" href="{% url 'login' %}">Login</a> {% endif %} Views: from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import costumer @login_required def profile_view(request): email = request.GET.get('email') if email: try: user = costumer.objects.get(email=email) if user.id == request.session.get('customer_id'): return render(request, 'profile.html', {'user': user}) else: return redirect('index') except costumer.DoesNotExist: return redirect('index') else: return redirect('index') def logout_view(request): request.session.flush() auth_logout(request) return redirect('index') def login_view(request): if request.method … -
How to create a node in neo4j using Django
I am working on a web app. For the backend I chose Django and as a database I would like to use a graph database so I chose neo4j. There is a python library neomodel to work with neo4j and a specific library django_neomodel to incorporate neomodel with Django. I am able to use Django to with neo4j to retrieve data from a node in the database, however I cannot get it to create a node in the database. Here is my a part of my settings.py file: INSTALLED_APPS = [ ... 'django_neomodel', 'neomodel', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'create', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.TokenAuthentication', ], } NEOMODEL_NEO4J_BOLT_URL = 'bolt://neo4j:password@localhost:7687' and here the views.py from create class RegisterView(View): """ This view handles POST requests to create a new user in the database. """ def post(self, request): new_node = myNode(XXX=request.POST['XXX'], YYY=request.POST['YYY'], ZZZ=request.POST['ZZZ']) new_nodesave() Here the myNode class: from neomodel import (StructuredNode, StringProperty, UniqueIdProperty) from .event import Event class myNode(StructuredNode): # Properties uid = UniqueIdProperty() XXX = StringProperty(required=True, unique_index=True) YYY = StringProperty(required=True) ZZZ = StringProperty(required=True) The error I get is: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I asked chatGPT and … -
Concurrency Control Mechanism For Dataframe Processing In Django WebApp
I have django webapp where processing data directly on pandas dataframe without using django model. now, i want to make this operations concurrency control for multiple processing requests simultaneously. suggest me best approach for it. i am aware about atomic transactions in django but it is not useful for the pandas processing. -
Invalid block tag on line 1: 'include'. Did you forget to register or load this tag?
During a Django tutorial I've got an issue with the index.html file. I can't handle this exception: Invalid block tag on line 14: 'else'. Did you forget to register or load this tag? I really don't understand why it doesn't recognize "include". My index.html is like this: <h1>{{ title }}</h1> {% include 'alphas/includes/nav.html' %} <ul> {% for item in posts %} {% if item.is_published %} <li> <h2>{{ item.title }}</h2> <p>{{ item.content }}</p> <p><a href="{% url 'post' item.id %}">Читать пост</a></p> {% if not forloop.last%} <hr> {% endif %} </li> {% endif %} {% endfor %} </ul> -
Importing rembg in Celery Task breaks workers
I'm trying to use the rembg library in a Celery worker (Django), but once I import the library, the worker is exited prematurely: objc[47160]: +[NSCharacterSet initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug. [2024-07-24 14:16:14,501: ERROR/MainProcess] Process 'ForkPoolWorker-16' pid:47160 exited with 'signal 6 (SIGABRT)' [2024-07-24 14:16:14,514: ERROR/MainProcess] Message: Error: {'signal': <Signal: task_failure providing_args={'traceback', 'einfo', 'kwargs', 'task_id', 'exception', 'args'}>, 'sender': <@task: assets.tasks.image_background.remove of oml at 0x1046a5c50>, 'task_id': '6219ab75-62b5-4d14-88ac-034d9fa71d45', 'exception': WorkerLostError('Worker exited prematurely: signal 6 (SIGABRT) Job: 15.'), 'args': [], 'kwargs': {}, 'traceback': 'Traceback (most recent call last):\n File "/Users/cesarrodriguez/.pyenv/versions/3.11.2/lib/python3.11/site-packages/billiard/pool.py", line 1264, in mark_as_worker_lost\n raise WorkerLostError(\nbilliard.exceptions.WorkerLostError: Worker exited prematurely: signal 6 (SIGABRT) Job: 15.\n', 'einfo': <ExceptionInfo: ExceptionWithTraceback()>} Data: {} [2024-07-24 14:16:14,514: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 6 (SIGABRT) Job: 15.') Traceback (most recent call last): File "/Users/cesarrodriguez/.pyenv/versions/3.11.2/lib/python3.11/site-packages/billiard/pool.py", line 1264, in mark_as_worker_lost I'm not sure if it's something related to multiprocessing Issues, have any thoughts? -
How do I transfer axes to the Django 5 custom admin panel?
I have a django project with two admin panels, one main for filling with models, etc., and the second for blogs (I want to store users, groups and all sorts of logs there) I connected logentry to the custom one, untied everything superfluous to the main one, but axes cannot be transferred how can this be done? -
Implement google login with django
I have a django application in which I want to deploy google login auth. My frontend framework is flutter. After login with flutter in to the google, it sends auth_code received from google to the django backend. This is how I implement my login google_auth_request = HttpRequestManager() class GoogleAuth: def __init__(self, code): self.code = code def get_access_token(self, code: str, redirect_uri: str) -> str: data = { "code": code, "client_id": config.settings.constants.GOOGLE_AUTH_CONFIG["GOOGLE_OAUTH2_CLIENT_ID"], "client_secret": config.settings.constants.GOOGLE_AUTH_CONFIG["GOOGLE_OAUTH2_CLIENT_SECRET"], "redirect_uri": redirect_uri, "grant_type": "authorization_code", } response = google_auth_request.post( config.settings.constants.GOOGLE_AUTH_CONFIG["GOOGLE_ACCESS_TOKEN_OBTAIN_URL"], data=data ) if not response.ok: log.error("Response.json() for get access_token") log.error(response.json()) print(response.json(), flush=True) raise ValidationError("Could not get access token from Google.") access_token = response.json()["access_token"] return access_token def get_user_info(self, access_token: str) -> Dict[str, Any]: response = google_auth_request.get( config.settings.constants.GOOGLE_AUTH_CONFIG["GOOGLE_USER_INFO_URL"], params={"access_token": access_token} ) if not response.ok: log.error(f"google auth response data: {response.data}") print(response.json(), flush=True) raise Exception("google service is unavailable") return response.json() def login(self): domain = config.settings.constants.GOOGLE_AUTH_CONFIG["GOOGLE_OAUTH2_API_URL"] redirect_uri = f"{domain}/api/auth/v1/login/google/" access_token = self.get_access_token(code=self.code, redirect_uri=redirect_uri) user_data = self.get_user_info(access_token) # Creates user in DB if first time login query = EtloUser.objects.filter(email=user_data["email"]) if not query.exists(): EtloUser.objects.create( email=user_data["email"], first_name=user_data.get("given_name"), last_name=user_data.get("family_name"), ) profile_data = { "email": user_data["email"], "first_name": user_data.get("given_name"), "last_name": user_data.get("family_name"), } return profile_data And this is its view @extend_schema(request=GoogleAuthSerializer, responses={200: OutputCredentialSerializer}) class GoogleAuthView(APIView): throttle_scope = "auth" def post(self, request, … -
Django annotation based on Count not working, always return 1
In models.py I have defined: class Order(models.Model): ... class Operation(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="operations") ... I have a queryset of orders where the first order has two operations. orders = order.annotate(mycount=Count('operations')) print(orders[0].operations.count()) print(orders[0].mycount) The previous piece of code returns: 2 1 Hence orders.filter(mycount__gte=2) erroneously returns an empty set. I can see from old posts that this was already a problem in the past, and that it seems like it got fixed as the forum discussions are old (here for example) . -
Can I get the related data directly when using a join query in django?
Well considering two models: class School(models.Model): name = TextField() class Student(models.Model): school = ForeignKey(School related_name=students ) firstname = TextField() And the query: School.objects.filter(Q(name="oldschool") & Q( Q(students__firstname="hello") | Q(students__firstname="testname") )) I retrieve the schools. However there is a join/subquery obviously executed, yet I do not get the student information. I also wish to get the student information for which the "first name is set". Can I make django orm actually fill in a students_set, so I do not have to do multiple lookups later? (having to iterate over the schools and check per school). -
python manage.py runserver No such file or directory
enter image description hereenter image description here I have learned the lesson and applied all the steps, but the page did not appear to me as in the lesson. It is expected that the server should work, but an error is showing. What is the reason? -
what is the default engine value used in django rest framework while using postgres database [closed]
ImproperlyConfigured at /api/token settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Request Method: POST Request URL: http://localhost:8000/api/token Django Version: 5.0.6 Exception Type: ImproperlyConfigured Exception Value: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Exception Location: /home/k/PycharmProjects/ProjectPMS/.venv/lib/python3.10/site-packages/django/db/backends/dummy/base.py, line 20, in complain Raised during: rest_framework_simplejwt.views.TokenObtainPairView Python Executable: /home/k/PycharmProjects/ProjectPMS/.venv/bin/python Python Version: 3.10.12 http://localhost:8000/api/token i am accessing this endpoint inorder to obtain token for authorization in postman -
Django local server deployment on windows
I have a Django project that has to be installed on local servers for multiple customers. I've looked into utilizing Docker, but I can't find any solid information about how to use it on local hosting. My customers use computers running Windows. A friend advised that I utilize a virtual machine to run the Linux Server, then install my project with all dependencies, produce an image of that custom OS, then install it on more virtual computers. The issue that bothers me is consistency in installing and maintaining dependencies. I don't know whether you have any better suggestions. On the subject of virtual machines, my plan was for them to start automatically as soon as the computer turned on and operate the server that would be accessed via the Windows operating system. I'm concerned about whether autotation is possible, whether the server can be accessed by other computers, and whether the client machines are powerful enough to handle the virtualisation. I have installed before, the old school way (straight to the OS), but is a hustle. Im afraid if the server fails, reapeting the whole process of intalling dependences and configurations might take a lot of time while a client … -
Websocket handshake result in 404 not found
All http(s) request are working fine but whenever I try to make a websocket connection it results in the following: Request URL: https://my-domain.com/ws/listen?jwt=<token> Request Method: GET Status Code: 404 Not Found This is my project configuration: nginx upstream geej_app_server { server unix:/webapp/run/gunicorn.sock fail_timeout=0; } server { server_name my-domain.com; access_log /webapp/logs/access.log; error_log /webapp/logs/error.log; location /static/ { alias /webapp/geej_backend/static/; } location /media/ { alias /webapp/geej_backend/media/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass https://geej_app_server; } } location /ws/ { proxy_pass https://geej_app_server; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; } listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /etc/ssl/cert.pem; ssl_certificate_key /etc/ssl/key.pem; ssl_client_certificate /etc/ssl/cloudflare.crt; ssl_verify_client on; } server { listen 80; listen [::]:80; server_name my-domain.com; return 302 https://$server_name$request_uri; } supervisor [program:geej] command = /webapp/env/bin/gunicorn_start user = guser stdout_logfile = /webapp/logs/supervisor.log redirect_stderr = true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 gunicorn_start (bash file for starting) #!/bin/sh NAME='geej' DJANGODIR=/webapp/geej_backend SOCKFILE=/webapp/run/gunicorn.sock USER=geejuser GROUP=webapp NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=geej.settings DJANGO_ASGI_MODULE=geej.asgi TIMEOUT=120 cd $DJANGODIR source ../env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mdkir -p $RUNDIR exec ../env/bin/gunicorn -k uvicorn.workers.UvicornWorker ${DJANGO_ASGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --timeout $TIMEOUT \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- routing.py … -
How to Version Control a PostgreSQL Table?
Backend: Python 3.11 and Django 5.0.6 Database: PostgreSQL 15 Our app deals with reporting from the database. We don't store report SQL queries in the codebase; instead, we store them in DB tables. However, developers change SQL queries from time to time. How can we track such changes made in the database, similar to using Git? For example, I want to see the query changes made in the database one year ago. How can I do that? Does anyone have any approach to do this? I tried to set up Liquibase, but it lacks support/documentation for a Python + Django app. Currently, what we are doing is we created a repo for the database, manually generating insert statements from the table and pushing them into the repo. But this is a hectic procedure. Some approaches that may work include using PostgreSQL triggers or logs. There are only some specific static tables that I want to track because some tables have data in the millions. If possible, I need an implementation similar to a version control tool like Git. Does anyone have a better approach to this problem? -
What does __code mean in Django?
What does __code mean in Django? I'm beginner find this code, but I don't now what does name__code mean. def get_queryset(self): names = self.request.query_params.get("name", None) if names: # qs = Hero.objects.filter(name=names) for name in names.split(self.names_separator): qs = Hero.objects.filter(name__code=name) # res = Hero.objects.get(name="Bad") # print(res) return qs I tried to find info in enthernet, but I can't -
Django decorator and middleware issue
My decorator looks like this def require_feature(feature_name): def decorator(view_func): print(f"process_view - view_func: {view_func}") # Debugging @wraps(view_func) def _wrapped_view(request, *args, **kwargs): return view_func(request, *args, **kwargs) _wrapped_view.required_feature = feature_name return _wrapped_view return decorator and the middleware looks like this class EntitlementMiddleware(MiddlewareMixin): def __init__(self, get_response) -> None: self.get_response = get_response def __call__(self, request) -> Any: if request.user.is_authenticated: request.user.features = get_user_features(request.user) else: request.user.features = [] return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): print(f"process_view - view_func: {view_func}") # Debugging required_feature = getattr(view_func, "required_feature", None) if required_feature and not request.user.features.filter(name=required_feature): raise PermissionDenied("You do not have access to this feature") return None # if none is returned then view is called normally def process_response(self, request, response): return response and this is how I am using it in my viewset class MyViewSet(ValidatePkMixin, viewsets.ViewSet): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] queryset = My.objects.all() @method_decorator(require_feature("Basic")) def list(self, request): pass the decorator sets the required_feature when server starts. the middleware gets called when I make a /get call but this required_feature = getattr(view_func, "required_feature", None) returns None what am I missing here?