Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Forms and Formset edit
I am trying to create a edit fbv but my edit is not saving up. views.py def editplayform(request,id): play = Play.objects.get(id=id) if request.method =='POST': form = forms.PlayForm(request.POST, instance=play) time_shown_formset = forms.TimeShownFormSet(request.POST, instance=play) if form.is_valid() and time_shown_formset.is_valid(): form.save() time_shown_formset.save() return redirect("play:home") else: form = forms.PlayForm(instance=play) time_shown_formset = forms.TimeShownFormSet(instance=play) return render(request, 'play/fbvplayform.html', context={'form':form, "time_shown_formset":time_shown_formset, 'play':play}) edit.html <form method="POST"> {% csrf_token %} <h1>Edit PLAY</h1> <div>{{ form.non_form_errors }} {{ form.as_p }}</div> <h1>Edit Timeshown</h1> <!-- prettier-ignore --> {{ time_shown_formset.non_form_errors }} {{ time_shown_formset.management_form}} {% for form in time_shown_formset %} <div>{{ form.times.label }}: {{ form.times }}</div> {% if time_shown_formset.can_delete %} <div>{{ form.DELETE }} {{ form.DELETE.label }}</div> {% endif %} {% endfor %} <div> <button type="submit">Update Play</button> </div> </form> It is returning POST response on the terminal but the edit is not saving and its not returning to home.html. What am i doing wrong please? -
Is there a way to specify library types and versions on GitHub other than using requirement.txt?
I've been exploring different approaches to specify library types and versions on GitHub for my solo project using Django and React. In my research, I've predominantly come across the use of requirement.txt files for managing project libraries. I've tried reviewing documentation and online discussions, but I'm curious to hear from the community about their experiences. Specifically, I'm interested in knowing if using requirement.txt is a widely adopted practice in the industry for managing project dependencies. Additionally, I'm open to learning about alternative methods that developers might find effective. What approaches have you tried for specifying library types and versions in your GitHub projects, and what were your expectations regarding the ease of maintenance and collaboration? Thank you for sharing your insights! -
Django Rest + Vuejs axion CSRF not working
I try using Django Rest Framework together with VueJS and axion. But always I get the MSG: CSRF Failed: CSRF token missing. But my Header in the frontend looks correct. And in the developer tools the cockie is correct loading into the header. {"Accept": "application/json, text/plain, /","Content-Type": "application/json","X-CSRFToken": "*******"} my csrf settings in django settings.py CSRF_COOKIE_NAME = "csrftoken" CSRF_HEADER_NAME = 'X-CSRFTOKEN' CSRF_TRUSTED_ORIGIN = ['http://.127.0.0.1', 'http://.localhost'] CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE= False I have no problems with the get requests. Only than it come to POST, PUT, DELETE. Thank you for your advice. With regards Philipp Homberger I try: CSRF_TRUSTED_ORIGIN = ['http://*.127.0.0.1', 'http://localhost'] as well. My Dev deployment build with 3 docker images. 1 Nginx as reversproxy to get both on the same port. 1 Container with Bakcend (Django) 1 Container with VueJs Frontend. What were you expecting? I expecting that I can do Post Requests as well without disable CSRF. Than I use the swagger frontend of my restapi all work fine as well. -
User can chose from a great amount of configurations/templates, need a way to handle without creating Django views/forms for every single one
Currently i am working on a project in Django which will let the user generate a router/switch configuration based on what type of service/router brand/router model he chooses. View: config list (List of registered configurations to generate) User -> Service_1 for router X model Y Then i would need to present the user with a page which will take the inputs needed to generate such configs View: generate config (Form that will ask the user for inputs needed to create X config file) Ex.: IP Address / Subnet Mask / is DHCP needed / routes needed This input will then be passed to variables which will be used to populate a jinja2 template file for said service/router model/router brand in a function Assume the structure is: -Router Brand X --Model Y ---Service1.j2 ---Service2.j2 ---Service3.j2 --Model Z ---Service1.j2 ---Service2.j2 ---Service3.j2 -Router Brand Y --Model Y ---Service1.j2 ---Service2.j2 ---Service3.j2 --Model Z ---Service1.j2 ---Service2.j2 ---Service3.j2 I have a big part of the project already done, right now i can save the config templates to my database, show said templates for the user to choose from and i gave it a try to create a page to generate the config. The issue i have … -
DJANGO websocket 404 not Found with wss
I am trying to connect my web socket with wss over https protocol. But getting 404 in logs saying not found. But it works fine in development over http://localhost in settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [ ("redis-container", 6379) ], }, }, } I am using Redis for the host and my asgi.py import os from django import setup from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from NotificationApp.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.settings") setup() application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( URLRouter( websocket_urlpatterns, ) ), } ) and my ***routes.py*** file from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"ws/notify/", consumers.NotificationConsumer.as_asgi()), ] on frontend const createWebSocket = () => { const socket = new WebSocket( `wss://localhost:8000/ws/notify/` ); socket.onopen = function (e) { console.log("Socket successfully connected."); }; socket.onclose = function (e) { console.log(e); console.log("Socket closed unexpectedly"); // Try to reconnect every 5 seconds // setTimeout(createWebSocket, 5000); }; socket.onmessage = function (e) { const data = JSON.parse(e.data); document.getElementById("bellIcon").className = "shakeIt"; const wait = async () => { await sleep(2000); document.getElementById("bellIcon").className = ""; }; wait(); setNotifications((prevNotifications) => [data, ...prevNotifications]); setUnreadNotifications((prevCount) => prevCount + 1); }; return socket; }; const … -
Arcpy not supporting in djnago in all machine but some machine it supporting
I have a Django application running in a virtual Conda environment generated from ArcPro. I need to use the arcpy library in this Django application, which is why I used the virtual environment. However, the class I used with arcpy is working on some machines but not on others. I used the subprocess method, and it worked at that time since arcpy is running outside of Django with that method. Why is arcpy not compatible with Django? -
Can anyone help? I'm following a tutorial to make a basic blog site using Django and PostgreSQL and I can't add a database
I've added a 'templates' folder into the blog directory but I can't get the Django database urls to recognise it. I think I need to add my url into the settings.py file but I have no idea how I'm supposed to do that. When I try to run the server I get this error: Traceback (most recent call last): File "/workspace/django-blog/manage.py", line 22, in <module> main() File "/workspace/django-blog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/gitpod/.pyenv/versions/3.12.1/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 994, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/workspace/django-blog/codestar/settings.py", line 91, in <module> 'default': dj_database_url.parse(os.environ.get("DATABASE_URL")) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/dj_database_url/__init__.py", line 126, in parse raise ValueError( ValueError: No support for 'b'''. We support: cockroach, mssql, mssqlms, mysql, mysql-connector, mysql2, mysqlgis, oracle, oraclegis, … -
Django runserver Problems
Everytime I start the python manage.py runserver command I get this Error: python manage.py runserver ModuleNotFoundError: No module named '<your_project_name>' I created the virtual Enviroment, installed djangoo and sucefully created a project but after that I cant start the server somehow. -
Django allauth + React google social login
I have django-allauth working well with Google social login when I'm directly accessing the backend. I'm now wondering how to use this from (or replace with) my React frontend. Originally my backend was FastAPI and with fastapi-users and it was working well enough with React. That is, in React I have a useAuth hook which in turn relies on useContext, while my React button would GET the auth_url from the backend's /auth/google/authorize, redirect me, use the /auth/google/callback, and ultimately store the token in a cookie. With Django I now wonder what the general approach should be. Should I: Option A: have my React button take me to django-allauth's /accounts/google/login, where the user completes the login cycle and is ultimately redirected back to my React's /profile? The issue so far is that even though the backend google part seems to work, upon redirect React complains that the token is empty. For now this is not surprising since I'm not yet sending that token back to the frontend. But idk if to keep working on this approach or if instead I should... Option B: try to recreate the /auth/google/authorize and /auth/google/callback flow I had working with FastAPI but now using Django. Specifically … -
Nginx + Gunicorn: Django Application Not Loading on Domain, But Works on IP and Port
I've tried accessing my Django application using the configured domain (e.g., http://succyloglobalfx.com) after ensuring that the domain is correctly pointing to the VPS IP address. I expected to see my Django application load successfully, similar to when accessing it via the IP address and port (e.g., http://162.254.35.54:8000). I run Gunicorn with the following command: gunicorn --bind 0.0.0.0:8000 TransferPrj.wsgi However, when accessing the application through the domain, I only encounter the default Nginx welcome page instead of my Django application. This behavior is unexpected, and I'm seeking guidance on what steps I can take to troubleshoot and resolve the issue. Below is my nginx config file server { listen 80; server_name succyloglobalfx.com www.succyloglobalfx.com; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name succyloglobalfx.com www.succyloglobalfx.com; ssl_certificate /etc/letsencrypt/live/succyloglobalfx.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/succyloglobalfx.com/privkey.pem; include /etc/nginx/snippets/ssl-params.conf; # Include recommended SSL parameters location /static/ { alias /opt/myproject/myproject/Trabsfer/static/; } location / { include proxy_params; proxy_pass http://162.254.35.54:8000; # server ip address proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } Any insights or troubleshooting steps would be greatly appreciated. Thank you! I've tried accessing my Django application using the configured domain (e.g., http://succyloglobalfx.com) after ensuring that the … -
Integrating GIS platform with ESRI system
I am currently working on a start up that involves the integration of a custom GIS platform with an existing ESRI system. Our platform is built using GeoServer postgres for geospatial data management, Leaflet for map interaction on the frontend, and a Python-based backend (likely Django).I want to know if the integration of open source platform with the current ESRI enterprise system achievable or no. Response on if the possibility of the integration of open source platform with the the ESRI enterprise. -
Django, can I force a request to bypass the cache, even if the cache key already exists
settings.py ['django.middleware.cache.UpdateCacheMiddleware'] + MIDDLEWARE + ['django.middleware.cache.FetchFromCacheMiddleware'] middleware.py def middleware(request): if global_value % 2 == 1: # bypass cache, can I do something? response = get_response(request) else: response = get_response(request) return response The reason is that we use certain values in headers to distinguish which need cache(url is same), but the cache cannot recognize it. -
Having issues with importing model to another app in order to use model there
My project structure: ecomarket: ecomarket: cart: product: user: manage.py Here's product.models class Product(models.Model): title = models.CharField(verbose_name=_("Называние"), max_length=255) description = models.TextField(verbose_name=_("Описание"), null=True, blank=True) price = models.DecimalField( verbose_name=_("Цена"), max_digits=9, decimal_places=2 ) quantity = models.PositiveIntegerField(verbose_name=_("Количество"), default=0) category = models.ForeignKey( "Category", verbose_name=_("Категория"), on_delete=models.PROTECT ) And this is cart.models class Cart(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) total_price = models.DecimalField(max_digits=9, decimal_places=2, default=0) def __str__(self): return f"{self.user}'s cart" class CartProduct(models.Model): product = models.ForeignKey("product.Product", on_delete=models.CASCADE) total_price = models.DecimalField( decimal_places=2, max_digits=9, verbose_name=_("Общая цена") ) cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name="cart_products") quantity = models.PositiveIntegerField(default=1, verbose_name=_("Количество")) def __str__(self): return self.product.title The issue is when I'm importing Product in the top of file like from product.models import the django is refusing to understand it. In cart.models I imported Product model in ForeignKey as a string and it worked. But I need Product model in my cart.views to create when endpoint get request. So how can I import it to my cart.views? Here's my views.py class AddToCartView(generics.UpdateAPIView): permission_classes = (permissions.IsAuthenticated,) authentication_classes = (JWTAuthentication,) def update(self, request, *args, **kwargs): quantity = request.data.get("quantity") id = kwargs.get('id') user = request.user product = generics.get_object_or_404("product.Product", id=id) cart, _ = Cart.objects.get_or_create(user=user) cart_product = CartProduct.objects.filter( product=product, cart=cart ) if cart_product: raise exceptions.NotAcceptable( 'You already have this product in your cart' ) if … -
Extract values from Django <QuerySet> object
I have this Python code for filtering: x_list = [] x = SupplierCommunication.objects.filter(supplier=supplier.id).values_list("x",flat=True) x_list.append(x) this code outputs this: x_list: [<QuerySet ['no']>, <QuerySet ['yes']>] however I want it to be like this x_list = ['no','yes'] How can I achive this? I have tried using .values() , .value_list() however none of it worked for me. Any other suggestions? -
How can we transfer ERC721 tokens through MetaMask and JavaScript?
We are trying to develop an NFT marketplace in a Django project. At this point we know how to integrate MetaMask with our project and use the JavaScript MetaMask API to send ETH transactions ('eth_sendTransaction') or check the balance of a wallet. But we would also know how to transfer NFT (ERC721) tokens between wallets (allow users to buy their NFTs) with and endpoint of this JavaScript API for MetaMask. If it's possible, we would like to have the transfer of the ERC721 token and the amount of ETH payed in the same transaction. Like it's shown in the image below: Example of SepoliaETH token transfer Is there any endpoint in the link below which can help us solving this issue? MetaMask API Thank you We tried to use scripts but we don't want to have the private keys of the users' wallets in our marketplace server because we don't have the permissions to store this kind of data. -
Django Admin & Cloud Storage - Favicon is not uploaded to bucket and not referenced by website
I wanted to use Cloud Storage for my static and media files. Static files work properly by following this answer: https://stackoverflow.com/a/72216226/20802935 The DEFAULT_FILE_STORAGE has been deprecated since version 4.2 so I used this instead: #settings.py STORAGES = { "default": {"BACKEND": "core.gcs_utils.Media"}, "staticfiles": {"BACKEND": "core.gcs_utils.Static"}, } I'm using Gunicorn and Docker -
Django-Unicorn: django_unicorn.errors.ComponentModuleLoadError: The component module 'views_unicorn' could not be loaded
I have a Django Application where I need a partial refresh and I wanted to implement django-unicorn. It works locally but on the server, I am getting this error. The server runs gunicorn. The setup I tried to follow and based my items on it in the documentation here: https://www.django-unicorn.com/docs/direct-view/#template-requirements Traceback (most recent call last): File "/home/django/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/django/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.10/dist-packages/sentry_sdk/integrations/django/views.py", line 84, in sentry_wrapped_callback return callback(request, *args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/decorator.py", line 232, in fun return caller(func, *(extras + args), **kw) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/decorators.py", line 16, in timed return func(*args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/views/__init__.py", line 49, in wrapped_view return view_func(*args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django/views/decorators/http.py", line 43, in inner return func(request, *args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/views/__init__.py", line 555, in message json_result = _handle_component_request(request, component_request) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/views/__init__.py", line 408, in _handle_component_request return _process_component_request(request, component_request) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/views/__init__.py", line 86, in _process_component_request component = UnicornView.create( File "/usr/local/lib/python3.10/dist-packages/decorator.py", line 232, in fun return caller(func, *(extras + args), **kw) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/decorators.py", line 16, in timed return func(*args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/components/unicorn_view.py", line 927, … -
Can I use AES Encryption in Django + MySQL? If yes, will it affect the use of Django's ORM and other features?
We are migrating our PHP codebase to Django. In the current application, all database columns are encrypted (except ID) using AES_ENCRYPT and AES_DECRYPT. something like this: $sql = " INSERT INTO users SET username = AES_ENCRYPT('".$email."','".$key."') , email = AES_ENCRYPT('".$email."','".$key."') "; $sql = "SELECT id , AES_DECRYPT(username ,'".$key."'), AES_DECRYPT(email,'".$key."')" Can this code be replicated in Django and is it possible to still maintain the cool features of Django like migration and ORM? -
Django redirect to Instagram
I'm creating a simple service in Django that redirects to Instagram social profiles. I have some troubles with Android devices where, even if the Instagram appis installed, the link is opened in the browser. I would like the link to be opened with the app, as already happens for iPhones. Here is the code: urls.py from django.urls import path from . import views urlpatterns = [ path('insta-bio/', views.redirect_to_url, name='redirect-to-url'), ] views.py from django.shortcuts import redirect def redirect_to_url(request): my_url = 'https://www.instagram.com/thesimpsons/' return redirect(my_url) I also tried with RedirectView type CBV, but nothing change... Any advice??? Thank's! -
mozilla-django-oidc doesnt authenticate users
I am using mozilla-django-oidc to authenticate keycloak users but i doesnt work. this is settings.py: AUTHENTICATION_BACKENDS = ( 'mozilla_django_oidc.auth.OIDCAuthenticationBackend', ) OIDC_RP_CLIENT_ID = 'HoubanCrm' OIDC_RP_CLIENT_SECRET = '7n9Kw7FgVYEkr1NKUDUA9KDBlMBiFjMS' OIDC_OP_AUTHORIZATION_ENDPOINT = 'http://localhost:8080/realms/HoubanCrm/protocol/openid-connect/auth' OIDC_OP_TOKEN_ENDPOINT = 'http://localhost:8080/realms/HoubanCrm/protocol/openid-connect/token' OIDC_OP_USER_ENDPOINT = 'http://localhost:8080/realms/HoubanCrm/protocol/openid-connect/userinfo' and when I want to login it redirect corrctly to keycloak but I get this erroe when I try to login: JWS token verification failed. Traceback (most recent call last): File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/mozilla_django_oidc/views.py", line 124, in get self.user = auth.authenticate(**kwargs) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/views/decorators/debug.py", line 73, in sensitive_variables_wrapper return func(*func_args, **func_kwargs) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 79, in authenticate user = backend.authenticate(request, **credentials) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/mozilla_django_oidc/auth.py", line 324, in authenticate payload = self.verify_token(id_token, nonce=nonce) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/mozilla_django_oidc/auth.py", line 218, in verify_token payload_data = self.get_payload_data(token, key) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/mozilla_django_oidc/auth.py", line 201, in get_payload_data return self._verify_jws(token, key) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/mozilla_django_oidc/auth.py", line 157, in _verify_jws raise SuspiciousOperation(msg) django.core.exceptions.SuspiciousOperation: JWS token verification failed. Bad Request: /oidc/callback/ [01/Feb/2024 06:48:28] "GET /oidc/callback/?state=R3r6Dg2XcLCWUIVlEUOOkqra0aU1Ta7t&session_state=068dc2c3-1b4f-447f-b31f-56f14a3adb5c&iss=http%3A%2F%2Flocalhost%3A8080%2Frealms%2FHoubanCrm&code=d65bdaef-0c4b-4231-a341-217e51966c7a.068dc2c3-1b4f-447f-b31f-56f14a3adb5c.e38b37dd-6828-4bb9-a457-babc25eb4e01 HTTP/1.1" 400 126592 I printed the jws token it seems ok -
I'm setting the category as the url in django and i'm getting error that ';' expected.javascript
I'm setting the category as the url in django and i'm getting error that ';' expected.javascript {% for category in all_categories %} <div onclick="location.href='{% url 'category' category.category %}';" style="box-shadow:0 5px 30px 0 rgba(0,0,0,.05);" class="hover:scale-105 hover:transform transition duration-300 cursor-pointer bg-gray-900 rounded-lg h-40 w-full my-4 text-center p-5 grid place-items-center"> <div> <p class='text-4xl my-2'><i class="bi bi-tags text-transparent bg-clip-text bg-gradient-to-r from-cyan-200 to-blue-500"></i> </p> <p class='text-base'>{{ category.category }}</p> </div> </div> {% endfor %} -
Django "Failed to establish a new connection: [Errno 111] Connection refused" error when connecting to django API via python script
I have this basic django api that i can access through the browser at https://127.0.0.1:8000/norm/status/; however, when i use python script to connect to it, i keep getting multiple error. This is the python script: BASE_URL='https://127.0.0.1:8000' ENDPOINT='norm/status/' headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'} def get_resource(): resp=requests.get(BASE_URL+"/"+ENDPOINT, verify=False, headers=headers) print(resp.status_code) print(resp.json()) get_resource() The errors i see: urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x7f80f8286490>: Failed to establish a new connection: [Errno 111] Connection refused urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /norm/status/ (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f80f8286490>: Failed to establish a new connection: [Errno 111] Connection refused')) I am running the django server inside a docker container and i am not sure if it has anything to do because of that. I really appreciate if someone can help me debug this. Thanks! I tried using django-cors-headers and also HTTPAdapter libraries but it didn't work. -
"mptt_tags" is not registered tags - Django Erro
I am having error when developing blog website.Can anyone help ? raise TemplateSyntaxError( django.template.exceptions.TemplateSyntaxError: 'mptt_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz I have installed in settigs.py as 'mptt' also and tried rerunning the server also.but couldn't find answer. I need to solve this error -
How to monitor Celery worker and return the task back to the queue if the worker dies or is killed?
**Problem Description:** I have a microservice that uses Celery for executing asynchronous tasks. I need to monitor the state of the Celery worker and return the task back to the queue if the worker dies or is killed (e.g., due to a SIGKILL signal). I also have another instance of Celery running on the main service side. **Question:** Is there a way to monitor the state of the Celery worker and automatically return the task back to the queue if the worker dies or is killed? **Additional Information:** - Using visibility_timeout is not suitable as it would require waiting for a day before the task returns to the queue, while I need it to happen almost instantly. -
Design and architecture of Blood Donation Managment in Django
I have almost completed the famous Django tutorial; Writing your first Django app. To consolidate my concepts I want to do a project in Django. So, I am starting a Blood Donation Management System in Django. It is supposed to serve as a network of blood donors and seekers, both the donors and seekers will be able to register, and search through blood group type, and the search result will show list the list of donors/seeker along with the contact details. This way it going to serve the blood donors/seekers community. What I want here is only a design level guidance; What apps should I create. What should the model (tables and attributes) What views should I code I cannot figure out the project structure or a sketch that I should follow. Initially I want only a sketch of the design to have a roadmap to follow along. Best Regards