Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Message delievering through local host of react app but not after deploying on netlify
I have a react app which is basically my portfolio app with backend made with django. But, the message is delievering through local host of react but after deploying it on netlify i am not able to deliever the message. i tried to use CORS_ALLOW_ORIGINS with specific list of my local host as well as of my backend server but still not working. The error on deployed app console is :- Blocked loading mixed active content “http://wahab901278.pythonanywhere.com/contact/submit/” index-DUkXO2lH.js:628:7274 Error: Network Error index-DUkXO2lH.js:631:4990 How to fix that anyone please assist -
Update columns of DataTable after having the data from server
I'm new at DataTables js, I need a solution for my problem. I have a Django app where I use DataTables with server-side processing, the table template is dynamic for all the models I have, I just pass the columns (a list of dicts with data, name and title) within the context of the template, pretty straightforward... def my_page_view(request): columns = generate_datatables_columns("MyModel") return render( request, "my_page.html", {"columns": columns} ) <script> $(document).ready(function() { var columns = []; {% for col in columns %} var jsObject = { {% for key, value in col.items %} "{{ key }}": "{{ value }}", {% endfor %} }; columns.push(jsObject); {% endfor %} var table = $('#my-table').DataTable({ "processing": true, "serverSide": true, "ajax": { "url": "/my/url", "type": "GET", }, "columns": columns, }); }); </script> <table id="my-table" class="display" width="100%"> <thead> <tr> {% for column in columns %} <th id="dt_col_{{column.data}}">{{ column.name }}</th> {% endfor %} </tr> </thead> </table> After that, I needed to make some changes on the columns, but depending on the data received, meaning I should be able to update my columns inside the DataTable definition after having the data. To make the idea clearer, the following code represents one of the attempts I tried, using ajax.dataSrc … -
How to properly load data into a ComboBox in Django with m3_ext and objectpack?
I am developing a Django application using m3_ext and objectpack for the UI components. I need to load ContentType objects into a ComboBox directly from the database. However, my current implementation is not working as expected. The combo box does not show the ContentType of an existing record when editing. You still can choose from combo box, but i really need existing value shoving in combo box for editing. from objectpack.actions import ObjectPack from objectpack.ui import ModelEditWindow, BaseEditWindow, make_combo_box from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission, Group, User from m3_ext.ui import all_components as ext class ContentTypePack(ObjectPack): model = ContentType add_to_desktop = True add_window = edit_window = ModelEditWindow.fabricate(ContentType) class PermissionEditWindow(BaseEditWindow): def _init_components(self): super(PermissionEditWindow, self)._init_components() self.field__name = ext.ExtStringField( label='Name', name='name', allow_blank=False, anchor='100%') self.field__content_type = make_combo_box( label='Content Type', name='ContentType', allow_blank=False, anchor='100%', data=[(ct.id, ct.model) for ct in ContentType.objects.all()]) self.field__codename = ext.ExtStringField( label='Codename', name='codename', allow_blank=False, anchor='100%') def _do_layout(self): super(PermissionEditWindow, self)._do_layout() self.form.items.extend(( self.field__name, self.field__content_type, self.field__codename, )) def set_params(self, params): super(PermissionEditWindow, self).set_params(params) self.height = 'auto' class PermissionPack(ObjectPack): model = Permission add_to_desktop = True add_window = edit_window = PermissionEditWindow def save_row(self, obj, create_new, request, context): obj.name = request.POST.get('name') content_type_id = request.POST.get('ContentType') if content_type_id: obj.content_type = ContentType.objects.get(pk=content_type_id) obj.codename = request.POST.get('codename') obj.save() return obj In edit window content type … -
A discussion on data fetching in Nextjs: Adding types to requests and response and using the fetch API
Context I've been building a web app with nextjs and a custom backend in Django Python and I've been struggling to find a clean way to make API requests to my backend from Nextjs. What I'm looking for is a way to centralise the logic for the fetch function while adding type safety to the request body and responses. Current approach const api = { get: async function (url: string): Promise<any> { console.log("get", url); return new Promise((resolve, reject) => { fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}${url}`, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", }, cache: "no-store", }) .then((response) => response.json()) .then((json) => { console.log("Response:", json); resolve(json); }) .catch((error) => { reject(error); }); }); }, post: async function (url: string, data: any): Promise<any> { console.log("post", url, data); return new Promise((resolve, reject) => { fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}${url}`, { method: "POST", body: JSON.stringify(data), headers: { Accept: "application/json", "Content-Type": "application/json", }, }) .then((response) => response.json()) .then((json) => { console.log("Response:", json); resolve(json); }) .catch((error) => { reject(error); }); }); }, } In this approach, I am centralising the logic for get and post requests in the sense that now I can just import api and call api.post/get to make a request to my backend. However, I don't like repeating code … -
ASGI for django not compatible with Server-sent-events?
I previously wrote an SSE (Server sent event) request using Django and it looked all right. def event_stream(): """ Generator function to yield messages. """ for i in range(10): yield f"data: Message {i}\n\n" time.sleep(1) # Simulate delay in message generation response = StreamingHttpResponse(event_stream(), content_type='text/event-stream') response['Cache-Control'] = 'no-cache' response['Connection'] = 'keep-alive' return response Later, I installed channels because I needed to use websocket, and switched from WSGI to using ASGI. At this point, I noticed that the request was not returning properly, but was returning all the data at once at the end. I'm not sure what is causing this or how to fix it. python version:3.11.7 django version:5.0.6 channels version:3.0.5 -
Django deployment. Apache, wsgi, python 3.12
Everything worked fine on python 3.8, but I need to update python to version 3.12. libapache2-mod-wsgi-py3 apparently does not support version 3.12. After starting the server, I get the error module django not found. What should I do?) <VirtualHost *:443> DocumentRoot /.../back/... <Directory /.../back/.../.../...> <Files wsgi.py> Order deny,allow Require all granted </Files> </Directory> <Directory /.../back/...> Require all granted </Directory> WSGIDaemonProcess ... lang='en_US.UTF-8' locale='en_US.UTF-8' python-path=/.../back/... python-home=/.../back/venv WSGIProcessGroup ... WSGIScriptAlias / /.../back/.../.../wsgi.py WSGIPassAuthorization On ServerName ... ServerAlias ... ErrorLog /.../back/logs/back-error.log CustomLog /.../back/logs/back-access.log combined SSLEngine on SSLCertificateFile "..." SSLCertificateKeyFile "..." SSLCertificateChainFile "..." </VirtualHost> -
drf and simplejwt error in coreapi : None type object has no attribute 'Field'
I have DRF project documented with drf_yasg and validator rest framework simple jwt. this is my requirements.txt file. File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\core\accounts\api\v1\urls\accounts.py", line 5, in <module> from .. import views File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\core\accounts\api\v1\views.py", line 4, in <module> from rest_framework.authtoken.views import ObtainAuthToken File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_framework\authtoken\views.py", line 11, in <module> class ObtainAuthToken(APIView): File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_fra File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\core\accounts\api\v1\views.py", line 4, in <module> from rest_framework.authtoken.views import ObtainAuthToken File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_framework\authtoken\views.py", line 11, in <module> class ObtainAuthToken(APIView): File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_fra from rest_framework.authtoken.views import ObtainAuthToken File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_framework\authtoken\views.py", line 11, in <module> class ObtainAuthToken(APIView): File "C:\Users\ASUS\OneDrive\Desktop\django\Django-Advance\venv\Lib\site-packages\rest_framework\authtoken\views.py", line 21, in ObtainAuthToken coreapi.Field( ^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'Field' this is my requirements.txt file: # general modules django<4.3,>4.2 python-decouple Pillow # third party modules djangorestframework markdown django-filter drf-yasg[validation] djangorestframework-simplejwt[crypto] # deployment modules this is my created CustomObtainAuthToke class: class CustomObtainAuthToken(ObtainAuthToken): serializer_class = CustomAuthTokenSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class( data=request.data, context={"request": request} ) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] token, created = Token.objects.get_or_create(user=user) return Response( { "user_id": user.pk, "email": user.email, "token": token.key, } ) and this is how I import that in line 4 from rest_framework.authtoken.views import ObtainAuthToken I tried to reversion the requirements.txt modules. I changed the DRF to different version for testing purposes to 3.12, 3.13, 3.14, 3.15 and the latest version … -
Invalid Token Error with Static Files in Django Template
I'm encountering an issue with my Django project where I'm trying to include a static CSS file in my HTML template. Despite trying multiple solutions, I keep getting the error: ERROR: Invalid Token. Expected stringEnd but found tag start "{%" instead. Here's my HTML template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Image</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <h1>This is a pic</h1> <img src="{% static 'images/pic.jpg' %}" alt="pic"> </body> </html> I getting this error on this line <link rel="stylesheet" href="{% static 'css/style.css' %}"> by hovering on this line on my editor(vs code). Solutions I've Tried: Placed {% load static %} at the top. Verified no syntax errors. Checked static settings in settings.py. Confirmed template backend setup. Ensured correct directory structure. Restarted server and cleared cache. -
How can I check if the item is the last item in the list in Django template?
While working on dictionaries, How can I check if the item is the last item in the list in Django template? dict = { "items":[3,4,7,0,6] } # I am mixing things here in my poor attempt {% with dict.items|length as range %} {% for i in range %} {% if i != range %} <a> dict.items[i] </a> {% elif i == range %} <a> Last item: dict.items[i] </a> # 6 {% endif %} {% endfor %} {% endwith %} -
Django auth_adfs Access to Azure Externals
In a Django application, I am using the django_auth_adfs module. In my frontend, I can have users log in as company externals via Microsoft authentication. Unfortunatelly, they are getting a 401 error when trying to send requests to my Django backend. In the Django Documentation I found the following I’m receiving an KeyError: 'upn' error when authenticating against Azure AD.¶ In some circumstances, Azure AD does not send the upn claim used to determine the username. It’s observed to happen with guest users who’s source in the users overview of Azure AD is Microsoft Account instead of Azure Active Directory. In such cases, try setting the USERNAME_CLAIM to email instead of the default upn. Or create a new user in your Azure AD directory. If I switch the USERNAME_CLAIM from upn to email the guest can now receive the HTTP results, but the problem is that the company members now can not. I then went to my App Registration -> Token configuration -> Access and added upn as an optional token with the option Externally authenticated: This option includes the guest UPN as stored in the resource tenant. set to yes. Now the guest has in its access token also … -
VSCode/Pylance - fail to import specific class
I'm trying out VSCode for Django development instead of PyCharm. I'm quite happy with the new configuration, but there's an issue which is driving me mad: VSCode fails to suggest only specific classes from django lib. So far, I'm able to get import suggestions like this: and selecting the class will import it correctly. But, if I try with ListView or LoginRequiredMixin, this happens: where django_tables2.views and hijack.views are third party libraries. If I search for additional import matches, the two classes are not found This is my VSCode workspace configuration: { "python.testing.pytestArgs": [ "." ], "python.testing.unittestEnabled": false, "python.languageServer": "Pylance", "python.testing.pytestEnabled": true, "python.analysis.autoFormatStrings": true, "python.analysis.autoSearchPaths": false, "python.analysis.autoImportCompletions": true, "python.analysis.inlayHints.callArgumentNames": "off", "python.analysis.inlayHints.functionReturnTypes": true, "python.analysis.userFileIndexingLimit": -1, "python.analysis.indexing": true, "python.analysis.stubPath": "", "python.analysis.inlayHints.variableTypes": true, "python.analysis.typeCheckingMode": "off", "python.autoComplete.addBrackets": true, "python.analysis.completeFunctionParens": true, "python.analysis.packageIndexDepths": [ { "name": "", "depth": 10, "includeAllSymbols": true }, ], "python.experiments.enabled": false, } Is this a bug or something? I found many issues on the Pylance repository, but in my case the files are correctly indexed (I can find UpdateView and other django classes). I also tried to uninstall the 3rd party libraries except for Django, but the LoginRequiredMixin and CreateView are not found anyway. I have Microsoft official extensions only, everything else … -
Django application logs are not rotated
In a Django application, version 3.2.14, running on an ec2 instance that also has a gunicorn web server with 9 workers, plus ngnix and with the log configuration shown below, the files are not rotated. The user of the gunicorn service is ubuntu and belongs to the group: www-data What could it be? Is there an issue with gunicorn and the workers? I appreciate your answers. LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "simple": {"format": "%(levelname)s %(message)s"}, "verbose": { "format": "[%(levelname)8s] [%(asctime)s] [%(funcName)30s] %(message)s" }, "elegant": { "format": ( "%(asctime)s [%(levelname)-8s] " "(%(module)s.%(funcName)s) %(message)s" ), "datefmt": "%Y-%m-%d %H:%M:%S", }, }, "handlers": { "console": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "elegant", }, "app": { "level": "INFO", "class": "logging.handlers.TimedRotatingFileHandler", "formatter": "elegant", "filename": os.path.join("logs", "app"), "when": "D", "interval": 30, "encoding": "utf-8", }, "groups": { "level": "INFO", "class": "logging.handlers.TimedRotatingFileHandler", "formatter": "elegant", "filename": os.path.join("logs", "groups"), "when": "D", "interval": 30, "encoding": "utf-8", }, }, "root": { "level": "INFO", "handlers": ["console"], "formatter": "elegant", }, "loggers": { "app": { "level": "INFO", "handlers": ["app"], "propagate": True, }, "groups": { "level": "INFO", "handlers": ["groups"], "propagate": True, }, }, } -
consist connection with multi websocket in django
In my django project i must interact with several server throw websocket and it needs constant connection with them. how can i define a management command to connect to all servers and then i my api i call each one of them that i want with their url I wrote an async manager and management command to creat connection to all of them: # servers/websocket_manager.py import asyncio class WebSocketManager: def __init__(self): self.clients = {} async def add_client(self, url): client = WebSocketClient(url) await client.connect() self.clients[url] = client def get_client(self, url): return self.clients.get(url) async def close_all_clients(self): await asyncio.gather(*[client.close() for client in self.clients.values()]) self.clients.clear() class WebSocketClient: def __init__(self, url): self.url = url self.connection = None async def connect(self): # Logic to establish the WebSocket connection pass async def close(self): # Logic to close the WebSocket connection if self.connection: await self.connection.close() # management/commands/init_websockets.py from django.core.management.base import BaseCommand from servers.websocket_manager import WebSocketManager from servers.models import Server # Ensure this is the correct path to your Server model import asyncio from multiprocessing import Process class Command(BaseCommand): help = 'Initializes WebSocket connections to specified URLs' def handle(self, *args, **options): manager = WebSocketManager() servers = Server.objects.all() urls = [server.url for server in servers] process = Process(target=self.run_event_loop, args=(manager, urls)) … -
Issue Running Unittests on GitHub Actions - ImportError
I’m encountering an issue running unit tests for my Django project on GitHub Actions. The tests run fine on my local machine using Docker containers, but I’m facing errors when running tests on GitHub Actions. Issue Description: In my CI/CD configuration file (GitHub Actions), I encounter an error when attempting to run tests. Here is a snippet of the error I’m receiving: ====================================================================== ERROR: AHC_app.AHC_app (unittest.loader._FailedTest.AHC_app.AHC_app) ---------------------------------------------------------------------- ImportError: Failed to import test module: AHC_app.AHC_app Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.12.4/x64/lib/python3.12/unittest/loader.py", line 429, in _find_test_path package = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.12.4/x64/lib/python3.12/unittest/loader.py", line 339, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'AHC_app.AHC_app' What I’ve Tried: 1. Setting PYTHONPATH: I’ve experimented with different configurations for the PYTHONPATH environment variable to point to the module locations, but I encounter the same error. Below are some examples of configurations I’ve tried: 2. _init_.py Files: I verified that all necessary _init_.py files are present, confirming the project structure is correct. What I Need Help With: Has anyone experienced similar issues with importing modules when running tests on GitHub Actions? What could be causing the ModuleNotFoundError, and what are best practices for configuring PYTHONPATH in the context of GitHub Actions? Additional Context: I am using Docker … -
django AttributeError at /signup/ 'dict' object has no attribute 'error'
enter image description here it was working just fine but suddenly when some tries to signup it shows this error. please note that messages at messages.error(request, "Invalid reCAPTCHA. Please try again.") is from pyexpat.errors import messages from django.contrib import messages instead of from pyexpat.errors import messages -
Django ViewFlow - Add dropdown selector to BPMN process step
Have a basic ViewFlow BPMN Process Flow set up. How can i add a dropdown selector to a step in the BPMN process with for instance a dropdown list of selections e.g. Users or Companies that needs to be selected as part of the step? the jsonstore proxy class does not have a dropdown option. Can i use the Forms and embed in the step somehow? thanks -
configure the nginx server
When I run the Docker container, I can see that Django correctly specifies the paths to the static and media files, but Nginx still can't find them. This causes a 404 error when trying to access files like bootstrap.min.css. Django settings: STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") # NOQA # STATICFILES_DIRS = [ # os.path.join(BASE_DIR, "static"), # NOQA F405 # ] MEDIA_URL = "media/" MEDIA_ROOT = BASE_DIR / "media/" # NOQA print(os.path.join(BASE_DIR, 'static')) # I wanted to see what the path would be print(os.path.join(BASE_DIR, 'media')) the console displays this path: /shop/src/static /shop/src/media Nginx configuration: server { listen 80 default_server; listen 443 default_server; server_name shop; location /static/ { alias /shop/src/static/; } location /media/ { alias /shop/src/media/; } location / { proxy_set_header Host $host; proxy_pass http://backend:8010; } } In the Nginx logs, I get: 2024/07/30 07:53:31 [error] 30#30: *1 open() '/shop/src/static/css/bootstrap.min.css' failed (2: No such file or directory), client: 172.18.0.1, server: shop, request: 'GET /static/css/bootstrap.min.css HTTP/1.1', host: 'localhost' -
Swapping images in Django(Using javascript/js)
This is the block of HTML code which contains one Main image and other additional images. If the user clicks on any additional images, the image should get replaced by the Main image. The logic works fine until I click the same image twice. After that the main image is lost <img id="mainThumbnail" class="card-img-top mb-5 mb-md-0 rounded" src="{{ product.image.url }}" alt="{{ product.name }}" /> <!-- Additional Images --> {% if additional_images %} <div class="additional-images mt-4"> <div class="row"> {% for image in additional_images %} <div class="col-2"> <img class="img-fluid rounded cursor-pointer thumbnail-image" src="{{ image.image.url }}" alt="Additional image for {{ product.name }}" onclick="swapImages('{{ image.image.url }}', this)" /> </div> {% endfor %} </div> </div> {% endif %} This is my javascript function function swapImages(newImageUrl, clickedElement) { console.log(this); // Get the current main image URL const currentThumbnailUrl = document.getElementById('mainThumbnail').src; // Update the main thumbnail image with the new image URL document.getElementById('mainThumbnail').src = newImageUrl; // Update the clicked image with the previous main thumbnail image URL clickedElement.src = currentThumbnailUrl; // Remove 'selected' class from all thumbnail images document.querySelectorAll('.thumbnail-image').forEach(img => img.classList.remove('selected')); // Add 'selected' class to the clicked thumbnail image clickedElement.classList.add('selected'); } document.querySelectorAll('.cursor-pointer').forEach(el => el.style.cursor = 'pointer'); I don't wanted to use the javascript but that's the … -
How to Load Templates in Django for specific application?
So I am Learning Django at in advanced level, I Already know how to include templates from BASE_DIR where manage.py is located. However I wanted to know how to locate templates in the specific app in Django. For Example, I have a project named 'mysite' and an app called polls. Now, I Added Templates in settings.py DIRS=[os.path.join(BASE_DIR, "templates")]. but, how to add templates specific to polls app in polls app directory? . ├── db.sqlite3 ├── manage.py ├── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── polls │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ ├── models.py │ ├── static │ │ ├── images │ │ ├── scripts.js │ │ └── style.css │ ├── tests.py │ ├── urls.py │ └── views.py └── templates ├── polls │ └── index.html └── static ├── images ├── scripts.js └── style.css Before, I Wanted it to look like this. . ├── db.sqlite3 ├── manage.py ├── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── polls │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── … -
Django & rest_framework - method get_queryset being called twice, is there any other better solution?
Currently I have a project using django and rest_framework to get some basic APIs on the run. The problem is, when i make a view using the generic lib on rest_framework and DjangoModelPermissions, my method get_queryset is being called twice My Permission Class class DefaultModelPermissions(DjangoModelPermissions): """ The request is authenticated using `django.contrib.auth` permissions. See: https://docs.djangoproject.com/en/dev/topics/auth/#permissions It ensures that the user is authenticated, and has the appropriate `view`/`add`/`change`/`delete` permissions on the model. This permission can only be applied against view classes that provide a `.queryset` attribute. """ perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': ['%(app_label)s.view_%(model_name)s'], 'HEAD': ['%(app_label)s.view_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } class DefaultModelViewPermissions: permission_classes = (DefaultModelPermissions,) My View class AgentListCreateView(DefaultModelViewPermissions, generics.ListCreateAPIView): serializer_class = serializers.AgentSerializer def get_queryset(self): print('get_queryset') return models.Agent.objects.all() Debbuging the app, I found out that the permission also call the get_queryset to retrieve the model to validate the django's user's permissions. permission_calling_get_queryset From my point of view, this is an unecessary operation. Deppending on the size of the DB table, this could be a major performance problem, and leed many other app issues. My solution was to override this "has_permission" method. So my class got like class DefaultModelPermissions(DjangoModelPermissions): """ The request is authenticated using `django.contrib.auth` permissions. … -
Unable to display a Message immediately while adding to wishlist url by clicking the wishlist button from the product card
this is the views.py function for the backend from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from .models import Product, Wishlist @csrf_exempt @login_required def add_to_wishlist(request): product_id = request.GET.get('id') product = Product.objects.get(id=product_id) wishlist_count = Wishlist.objects.filter(product=product, user=request.user).count() if wishlist_count > 0: msg = "Product already exists in wishlist" else: Wishlist.objects.create(product=product, user=request.user) msg = "Product added to wishlist" wishlist_count = Wishlist.objects.filter(user=request.user).count() request.session['wishlist_count'] = wishlist_count return JsonResponse({"bool": wishlist_count > 0, 'totalwishlistitems': wishlist_count, 'msg': msg}) this is my functions.js ajax call to sent to the backend $(document).ready(function () { $(document).on('click', '.add-to-wishlist', function (event) { event.preventDefault(); event.stopPropagation(); console.log('Button clicked'); let product_id = $(this).data("product-item"); console.log("Product ID is", product_id); let this_val = $(this); $.ajax({ url: "/add-to-wishlist", data: { "id": product_id }, dataType: "json", beforeSend: function () { console.log('Before sending AJAX'); this_val.css("color", "red"); }, success: function (response) { console.log('AJAX success', response); this_val.toggleClass("wishlist-added", response.bool); $(".wishlist-items-count").text(response.totalwishlistitems); if (response.msg) { console.log('Message from server:', response.msg); // Create the message element const message = $('<div class="wishlist-message">' + response.msg + '</div>'); console.log('Message element created:', message); // Append the message element to the page $('body').append(message); console.log('Message element appended to body'); // Show the message element message.fadeIn(); console.log('Message element faded in'); // Hide the message element after 3 seconds setTimeout(function () { message.fadeOut(function … -
Module is suddenly not found, and can't install it either with pip
Yesterday I was working on my project. Today, when I opened it, two modules aren't found. Yesterday they were, so that is pretty strange already. When I try to install using pip, it says 'Requirement already satisfied'. The modules I need to install are these: from decouple import config from celery.schedules import crontab I already surfed around the internet trying random things, since I am new and learning django and python I find my problem very hard to understand. -
How can I grant permissions to a client that is not a User in Django?
I have a Django Rest Framework application that has been working well with OIDC auth and human interactions using django-oauth-toolkit. Now I want to add a couple of service accounts so that some external automation can make some requests and create some objects. According to django-oauth-toolkit, The Client Credential grant is suitable for machine-to-machine authentication. So I've implemented this grant type and tested it out with the below script: client_id='axXSSBVuvOyGVzh4PurvKaq5MHXMm7FtrHgDMi4u' secret='hun***2' credential="${client_id}:${secret}" CREDENTIAL=$(printf '%s' "$credential" | base64) export CREDENTIAL ( set -x r=$( curl "http://[::1]:8080/o/token/" \ -H "Authorization: Basic ${CREDENTIAL}" \ -H "Cache-Control: no-cache" \ -H "Content-Type: application/x-www-form-urlencoded" \ -X POST \ -d "grant_type=client_credentials" \ -d 'user=2' ) access_token=$(jq -r '.access_token' <<< "$r") curl -H "Authorization: Bearer ${access_token}" -H "Cache-Control: no-cache" 'http://[::1]:8080/notify/riskimpacts/' ) and the response is an HTTP 403: {"detail":"You do not have permission to perform this action."} It authenticates, but does not authorize any access to any views, because there is no user associated with these credentials. In fact, django-oauth-toolkit removes the user from the request even if there should be one, so there really cannot ever be a user associated with the access token created here. Yet, all but the most open (practically anonymous) django-rest-framework permissions require … -
Best Practices for Deploying Permanently Running Applications on Windows Server
I'm currently managing several projects deployed on a Windows Server, including: A Django backend, Celery for background tasks, React frontends Due to coorperate constraints, we can't use a Linux server, where solutions for these needs are more straightforward. I'm looking for the best practices or tools that can help in deploying these applications on a Windows environment, ensuring they run reliably over time. Specifically: Django Backend: What are the recommended ways to deploy Django on Windows? Celery: What are the best practices for running Celery workers and the beat scheduler on Windows? How can I ensure they are automatically restarted in case of a failure? React Frontend: What are the best deployment strategies for React applications on a Windows server? Additionally, I'd appreciate any advice on: Setting up a robust logging system. Monitoring the health and performance of these services. Ensuring automatic startup and recovery after server reboots or failures. Any guidance or resources would be greatly appreciated! Thank you in advance. I have looked into using NSSM (Non-Sucking Service Manager) for managing services, but it seems to be a dead project with no recent updates or active maintenance. Currently, we are using Windows Task Scheduler, but it appears ill-suited … -
Creating a reusbale form in Django SOLVED
Right, trying to create a reusable form into my Django website. For some reason, it's just not displaying the form fields. It's displaying the submit button, but despite correctly setting out the fields, and passing them to my template, the template is refusing the display the form fields. Trying to set up the form on the privacy-statement page and would also just love to reuse this i my cookie-statement page as well. The privacy-statement already exists, the form is new and I want this to be reusable. Here is my setup, including the file paths of each file: Update: this has been solved. See altered working below: #PROJECT-NAME/legal/forms.py from django import forms class TicketForm(forms.Form): subject = forms.CharField(max_length=255) description = forms.CharField(widget=forms.Textarea) email = forms.EmailField() #PROJECT-NAME/legal/views.py from django.shortcuts import render, redirect from django.http import HttpResponse from . forms import TicketForm from django.core.mail import send_mail, BadHeaderError from django.template import loader from blauwestadtech import utils from django.conf import settings import requests def legal__privacy_statement(request): form = TicketForm() context = { 'form' : form } return render (request, 'privacy-statement.html', context) #PROJECT-NAME/legal/urls from django.contrib import admin from django.urls import path, include from . import views from .views import create_ticket urlpatterns = [ path( 'privacy/', include( [ path('cookie-statement', …