Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how to create a unique instance of one model as a field in another model
I am trying to store an instance of an items model as a field in my users model using ForeignKey like so: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length=255) items = models.ForeignKey('Item', on_delete=models.CASCADE) def __str__(self): return self.username class Item(models.Model): stats = models.JSONField(null=True) name = models.CharField(max_length=255) def __str__(self): return self.name However, it currently seems that every new user is sharing the same list of items when I check my Django admin panel (essentially, there currently exists only one Items instance that is shared by every user). Instead, my goal is to have each user have their own list of items, unrelated to other users' list. Is there a way to make each user have a field in their account that is a unique instance of the Items model? -
Why will my Django middleware redirect googlebot instead of directly allowing it?
class BlockDirectAPIAccessMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): protected_paths = ['/api/socialinfo', '/api/crypto-data'] if any(request.path.startswith(path) for path in protected_paths): googlebot_user_agents = [ "Googlebot", "Googlebot-Image", "Googlebot-News", "Googlebot-Video", "Storebot-Google", "Google-InspectionTool", "GoogleOther", "Google-Extended" ] # Check for Googlebot (allow access) user_agent = request.META.get('HTTP_USER_AGENT', '').lower() # Convert to lowercase for case-insensitive matching if any(ua.lower() in user_agent for ua in googlebot_user_agents): return self.get_response(request) # Allow requests from your own domain (optional, but good practice) referer = request.META.get('HTTP_REFERER', '') if 'mysite.com' in referer: return self.get_response(request) # Allow local development (if needed) if 'localhost' in referer or '127.0.0.1' in referer: return self.get_response(request) # Block other direct access return HttpResponseForbidden('Access denied.') # Allow access to non-protected paths return self.get_response(request) I am testing to let googlebot access the API but i get a 301 response HTTP/1.1 301 Moved Permanently Date: Thu, 16 May 2024 19:46:45 GMT Server: Apache/2.4.29 (Ubuntu) Strict-Transport-Security: max-age=63072000; includeSubdomains X-Frame-Options: DENY X-Content-Type-Options: nosniff Location: /api/socialinfo/?beginRange=0&endRange=19 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Content-Type: text/html; charset=utf-8 -
Issue connecting MySQL to Django
My Django project will not migrate the changes I have made to the settings.py I get this error (1045, "Access denied for user 'root'@'localhost' (using password: NO)") I installed and setup a MySQL created a database connected all the information to my settings.py quadruple-checked to ensure they were correct. I have tried refreshing the server, granting all privileges to localhost, changing localhost to 127.0.0.1, and ran "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mypassword'; FLUSH PRIVILEGES;". I am open to any ideas. Django version: 5.0.4 MySQL version: 8.4 DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "aquadexdb", "USER": "root", "Password":os.environ.get("MySqlPassword"), #tried the raw password as well "HOST": "localhost", "PORT": "3306", } } -
Django with nginx & uwsgi: incomplete file response
Hello i have a django app and i recently added nginx & uwsgi on it. I have an endpoint that response with a file (xlsx). Before doing the changes this endpoint worked fine, but after the changes, the endpoint only gave the first 74 characters bytes of my file, causing a corrupted excel error. This is my django code for the response: with NamedTemporaryFile(delete=True) as temp_file: temp_file.write(response.content) temp_file.flush() return StreamingHttpResponse( open(temp_file.name, "rb"), headers=response.headers, status=response.status_code, ) I tried using FileResponse also and the same happened. This is my nginx file: server { listen 8000; server_name localhost; charset utf-8; add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; client_body_buffer_size 32k; client_header_buffer_size 8k; large_client_header_buffers 8 64k; location / { include uwsgi_params; uwsgi_pass unix:///var/uwsgi/my_api.sock; uwsgi_buffer_size 32k; uwsgi_buffers 16 16k; uwsgi_busy_buffers_size 32k; uwsgi_read_timeout 300; uwsgi_send_timeout 300; uwsgi_connect_timeout 300; uwsgi_ignore_client_abort on; }} What configuration do i need to do to solve this problem? -
image gallery using magnific-popup always popup first one, not the one selected when clicked
I'm using JQUERY and Magnific Popup in a django project. When I clicked on any image in the gallery, it always popup the first image instead of the one selected. This is my current code: Here is the django template <!-- jQuery library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <!-- Magnific Popup JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js"></script> {% for image in images %} <div class="image"> <a href="{{ MEDIA_URL }}images/{{ dir }}/{{ image }}"> {% thumbnail MEDIA_ROOT|add:"images/"|add:dir|add:"/"|add:image 300x300 crop="smart" as im %} <a href="{{ MEDIA_URL }}images/{{ dir }}/{{ image }}" class="image-link"> <img src="{{ im.url }}"> </a> </a> <div class="info"> <a href="{{ MEDIA_URL }}images/{{ dir }}/{{ image }} " class="title" > {{ dir }} </a> </div> </div> {% endfor %} Here is the javascript and magnific popup <script> $(document).ready(function() { $(document).on('click', '.image-link',function(e) { e.preventDefault(); $('.image-link').magnificPopup({ type: 'image', closeOnContentClick: true, closeBtnInside: true, midClick: true, mainClass: 'mfp-with-zoom mfp-img-mobile', gallery: { enabled: true, navigateByImgClick: true, preload: [0,1] // Will preload 0 - before current, and 1 after the current image }, image: { verticalFit: true, }, zoom: { enabled: true }, callbacks: { beforeOpen: function() { } }, }).magnificPopup('open'); }); }); </script> -
Django (DRF) Channels getting SynchronousOnlyOperation on deleting User instance
I'm using DjangoRestChannels (based on Django Channels). I made a simple comments page. When new Comment added by any User instance consumer sends in to JS and renders on HTML. Everything works exceps when User instance gets deleted I'm getting exception django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Consumers: class CommentConsumer(ListModelMixin, GenericAsyncAPIConsumer): queryset = ( Comment.objects.filter(level=0) .select_related("user", "parent") .prefetch_related("children") .order_by("-date_created") ) serializer_class = CommentSerializer permission_classes = (AllowAny, ) @action() async def subscribe_to_comment_activity(self, request_id, **kwargs): await self.comment_activity.subscribe(request_id=request_id) @model_observer(Comment) async def comment_activity( self, message: NewCommentSerializer, observer=None, subscribing_request_ids=[], **kwargs ): await self.send_json(dict(message.data)) @comment_activity.serializer def comment_activity(self, instance: Comment, action, **kwargs) -> NewCommentSerializer: """Returns the comment serializer""" return NewCommentSerializer(instance) Model: class Comment(MPTTModel): """ The base model represents comment object in db. """ user = models.ForeignKey(CustomUser, related_name="comments", on_delete=models.CASCADE) parent = TreeForeignKey( "self", blank=True, null=True, related_name="children", on_delete=models.SET_NULL ) date_created = models.DateTimeField( verbose_name="Created at", auto_now_add=True, blank=True, null=True ) text = models.TextField(max_length=500) In terminal exception tracing don't help me much as among all the exception lines my code was only : await self.send_json(dict(message.data)) in Consumer method async def comment_activity. Any guess regarding this topic? Appreciate any help. -
How can I redirect to okta for only saml authentication from my app's login page and get a response?
I am using auth0(okta) as sp for SAML authentication, I want to have a button on my django app login page (not hosted by okta) to have a button "SAML Login", upon click on that button, I want to redirect the user to (okta hosted) login page for SAML authentication, and when the okta authenticate the user send a callback to my callback url. I am new to okta and Saml auth, any help would be appreciated. I followed auth0 tutorials using authlib, Here is how I registered my auth0 app oauth = OAuth() auth0 = oauth.register( "auth0", client_id=settings.AUTH0_CLIENT_ID, client_secret=settings.AUTH0_CLIENT_SECRET, client_kwargs={ "scope": "openid profile email", }, server_metadata_url=f"https://{settings.AUTH0_DOMAIN}/.well-known/openid-configuration", ) Here is I am trying to redirect to auth0 hosted saml login page. def saml_login(request): state = random_UUID_generator(size=16) request.session['oauth_state'] = state # Construct the Auth0 SAML endpoint URL with your Auth0 domain and connection name auth0_saml_url = 'https://{settings.AUTH_DOMAIN}/samlp/{settings.AUTH0_CONNECTION_NAME}' # Include the state parameter as a query parameter in the redirect URL # Redirect the user to the Auth0 SAML endpoint URL with the state parameter return oauth.auth0.authorize_redirect(request, auth0_saml_url, state=state) Here is the callback method for auth0 to send authentication results @csrf_exempt def callback(request): print(request.__dict__) print(request.session.__dict__) # Extract the state parameter from the … -
Error in vercel while uploading a django app
While trying to upload my Django application I got these errors requirements.txt error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully Error: Command failed: pip3.12 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error how do I come about it? This is what I have in my vercel.json file: { "version": 2, "builds": [ { "src": "ecommerce/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } } ], "routes": [ { "src": "/(.*)", "dest": "ecommerce/wsgi.py" } ] } and these are the packages in my requirements.txt file: Django==4.1.5 django-phonenumber-field==7.3.0 mysqlclient==2.2.4 numpy==1.26.4 phonenumbers==8.13.36 psycopg2==2.9.9 requests==2.31.0 requests-oauthlib==1.3.1 twilio==9.0.5 I have tried using a virtual env but still didn't work and I also changed the python version from 3.10 to 3.9 in the vercel.json file also didn't work. -
How to efficiently convert denormalized data to JSON?
I am learning django and couldn't find an answer on this. I am receiving data a query in denormalized form. Here is how it looks like. |Store_id|Shelf_id|Product_id|Qty| |--------|--------|----------|---| |store1 |shelf1 |product1 |20 | |store1 |shelf1 |product2 |24 | |store1 |shelf2 |product1 |34 | |store1 |shelf2 |product3 |12 | |store2 |shelf1 |product3 |21 | |store2 |shelf1 |product1 |46 | and so on. There is one-to-many relationships from store to shelf to product models. I have written a foreach loop to go over the entire dataset and convert it to JSON like [ {"store1" : [ {"shelf1" : [ {"product1" : 20}, {"product2" : 24}] }, {"shelf1" : [...]}] }, {"store2" : [...]}, ] Although, the foreach loop is pretty straightforward to write, it is pretty inefficient in the execution. For every record, it has to check if the store and shelf exists before adding the product entry. The production data is expected to have 100+ stores and 5000+ shelves and be about 1.5MM rows per day. That is a large number of key lookups. Is there a way one can generate the data in JSON format directly out of django queries? -
Upgrading postgres version in django error
I'm trying to get postgres 14 (upgrading from 11) to work locally. Initially the docker file looked like: db: image: postgres-14.11 environment: volumes: healthcheck: test: timeout: 20s retries: 10 ports: - "5432:5432" When running this ended up giving the following error: find /usr -name postgis.control -->>DETAIL: Could not open extension control file "/usr/share/postgresql/15/extension/postgis.control": No such file or directory. So i did some research and tried to change my docker-compose to: db: image: postgis/postgis:14-3.4 environment: volumes: healthcheck: test: timeout: 20s retries: 10 ports: - "5432:5432" this instead gave me this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "pg_extension_name_index" DETAIL: Key (extname)=(postgis) already exists. which doesn't make sense to me .. not sure what's happening or what the fix for this should be -
error in django KeyError at /accounts/register/
I have a problem. When clicking on the link http://127.0.0.1:8000/accounts/register / returns the KeyError error at /accounts/register/ 'email'. I program in django in pycharm this is code: registration/urls.py: from django.contrib.auth import views as auth_views from django.urls import path from . import views urlpatterns = [ path('/register', views.register, name='register'), ] registration/views.py: from django.shortcuts import render from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from .forms import RegistrationForm from django.shortcuts import render, redirect def sign_up(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') else: form = RegistrationForm() return render(request, 'registration/register.html', {'form': form}) def register(): print("hello!") urls.py(In the project itself): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('news/', include('news.urls')), path('accounts/', include('django.contrib.auth.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) register.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Регистрация</title> </head> <body> <h1>Регистрация</h1> <form method="post" action="{% url 'register' %}"> {% csrf_token %} {{ form.email }} {{ form.password1 }} {{ form.password2 }} <button type="submit">Зарегистрироваться</button> </form> </body> </html> forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): … -
Bad Request (400): Django / Nginx / Gunicorn / Kubernetes
I have a Django project running on Kubernetes with Redis, Postgres, Celery, Flower, and Nginx. I deploy it using Minikube and Kubectl on my localhost. Everything looks fine; the pod logs appear good, but when I'm trying to tunnel the Nginx service, it returns a Bad Request (400). The logs, the project files, the dockerfile, and the different YAML files are attached. Django pod logs: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, website Running migrations: No migrations to apply. 138 static files copied to '/app/staticfiles'. [2024-05-11 15:21:33 +0000] [9] [INFO] Starting gunicorn 22.0.0 [2024-05-11 15:21:33 +0000] [9] [INFO] Listening at: http://0.0.0.0:8000 (9) [2024-05-11 15:21:33 +0000] [9] [INFO] Using worker: sync [2024-05-11 15:21:33 +0000] [10] [INFO] Booting worker with pid: 10 Nginx pod logs: Nginx pod logs: /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh 10-listen-on-ipv6-by-default.sh: info: can not modify /etc/nginx/conf.d/default.conf (read-only file system?) /docker-entrypoint.sh: Sourcing /docker-entrypoint.d/15-local-resolvers.envsh /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh /docker-entrypoint.sh: Configuration complete; ready for start up 2024/05/14 19:15:32 [notice] 1#1: using the "epoll" event method 2024/05/14 19:15:32 [notice] 1#1: nginx/1.25.5 2024/05/14 19:15:32 [notice] 1#1: built by gcc 12.2.0 (Debian 12.2.0-14) 2024/05/14 19:15:32 … -
Django 5 use of static files with images
I´m trying to a picture to website with help of Django 5 and static files, the website its self is working with no error is diplayed in Django 5 but image is displayed Has tried to read the documentation about static files and Django 5 Has tried to change path to location of jpg file Website is running locally on my machine HTML: <body> <img src="{% static 'images\house_of_functions_hawkeye.jpg' %}" alt=""> <div class="container"> <h1 id="main__title">Welcome to House of functions</h1>` In settings.pyyour text `BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR =Path(BASE_DIR, "templates") STATIC_DIR =Path(BASE_DIR, "static") print(STATIC_DIR)` and STATIC_URL = 'static/' STATIC_DIRS = [ STATIC_DIR / "static", ] Example from my website -
How to deal with Django and TimescaleDB hypertables?
Firstly hypertable needs all PK contains partition column, in this case time, and in the other hand Django does not allow create multi column PK so you can't create a PK that could contains the time column. Second: if I have rows with repeated time, it will break unique constraints in time column. How can you use Django and TimescaleDB together and make use of hypertables? I have tried to create a table with time as primary key and eventually I have got duplicate key error inserting data in the table -
Django cycles/wrapped classes error with running server
I am learning to build and run django framework web applications. Recently I am watching this video tutorial:https://www.youtube.com/watch?v=pLN-OnXjOJg&list=PL-51WBLyFTg38qZ0KHkJj-paDQAAu9HiP . I am doing everything as shown in the video, cmd shows that the server is working properly. But I can'topen the web application in localhost itself: enter image description hereenter image description here I've tried to search for the error type, google says it's a cycled import error and youtube says there's something wrong with wrapping classes or something like that. I am a completely beginner, so please help me out very fast to not stagnate there -
CSRF Token in Angular 17 using django
I am using django for backend and for POST/GET request I am using this function which is def player_list(request): if request.method == 'GET': players = Player.objects.all().values() # get all players as Python dictionaries player_list = list(players) return JsonResponse(player_list, safe=False) elif request.method == 'POST': try: data = json.loads(request.body) # load JSON data from request player = Player(**data) # create a new player instance player.full_clean() # validate the player instance player.save() # save the player instance to the database return JsonResponse({'message': 'Player created successfully.'}, status=201) except json.JSONDecodeError: return HttpResponse('Invalid JSON', status=400) except ValidationError as e: return JsonResponse({'error': e.message_dict}, status=400) else: return HttpResponse('Invalid HTTP method', status=405) if I add @csrf_exempt above my function then it fetch the POST the data in database otherwise my Angular apps gives me 403 error. even I have added in app.module.ts imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule, HttpClientXsrfModule.withOptions({ cookieName: 'csrftoken', headerName: 'X-CSRFToken' }) ], and my POST fucntion in service is postPlayers(player: Player): Observable<any> { return this.http.post(this.url, player, { headers: { Accept: 'application/json' }}); } I am new so I am not able to figure it out. can anyone help me please? The data should be store in the database with CSRF token but its not. -
Django objects.filter returns empty array even it returns an object befor with same request
Im currently working on a Excel to DB Project where i put the 3000 products in my SQLite DB. Some of the products are duplicated or already exist in the DB. So I am looping through the Excel sheet and checking with # Check if "Produkt" already Exists. If it dose, return the id of the "Produkt" produkt = Produkt.objects.filter(**{"name": produktName}) p_serializer = ProduktSerializer(produkt, many=True) with: if len(p_serializer.data) == 0: I am checking if the product already exists. My main problem now is that it may detect the first product, but skip the next one (for example, if the same product appears 3 times in a row) and just return []. i thougt about race conditions but that should not be possible cause im the only one accessing the application right now I Tryed timeouting the loop but this didnt helped. i also tryed to tell the if statement: if len(p_serializer.data) == 0 and lastItem != produktName: also didnt worked -
Page not found on Django using Websockets
It's the first time I'm working with websockets in Django and I'm not doing it very well, what's happening to me is that I get either the 404 not found error or the error: unexpected server response: 200, I've been checking some tutorials and also reading the documentation and some say to use typeScript but I don't really understand why Objective My goal is to be able to make a request to Electron so it can take a print-screen of your user's screen and send it to me as a string so I can manipulate it in Django Python, this part is already functional, I tested it with Simple WebSockets Client, but now that I'm trying to test with other users and get their screenshot, and for that I'm using ngrok to keep the server up for other users to access. What happens is that I capture my electronic server and not the other's my users, and now I'm going to try to change the Routes to capture theirs but I'm not succeeding, if anyone can help a lot index.js const { desktopCapturer, screen, BrowserWindow, app } = require('electron'); const { spawn } = require('child_process'); const django = spawn('python', ['manage.py', … -
How can I generate and download an HTML document, based on a template?
To improve my workflow, I want to automate the creation of HTML files that I and my colleagues usually prepare by hand. In these files, only the logo and a few texts need to change, everything else remains the same. I know HTML and such, so it's not a problem for me to edit those HTML templates, but my colleagues are having a hard time, so I'm looking for a way to create an app that would get user inputs, put those inputs in the template, export the template in a .HTML format, and voilà. I know it will take a lot of work and learning, but I'll have a lot of free time to work on it soon. I already began to look for solutions, and discovered that Python's Django could help with the template part, and Tkinter for the user input part, but I've never really worked with Python before, so I'm looking for any other alternatives, or advices on how to proceed. The two previously mentioned solutions seems viable, but I don't know if they work together. And I don't know if there is a tag for an open discussion... -
How to implement a message system with Django across domain and subdomains?
I want to develop a web application using Django. This application is a support network. End users will create support tickets via the 'www.mydomain.com' web address, and employees will respond to these tickets via an admin panel at 'support.mydomain.com'. Tickets will be single-threaded, meaning, for example, that end users cannot write another message until the support team responds. I'll use cPanel for hosting. How can I establish the connection between the domain and subdomain in this application? Should I develop two separate projects and connect them with REST Framework, or is there a better way? -
Django-allauth NoReverseMatch Error for 'account_login' with Custom URL Patterns
I'm working on a Django project that includes user authentication using django-allauth. I have set up custom URL patterns that include a library_slug parameter for multi-tenancy purposes. However, when I navigate to the signup page (http://localhost:8000/bgrobletest/accounts/signup/), I encounter a NoReverseMatch error: Here is the relevant traceback: Traceback (most recent call last): File "/Users/williamgroble/lib_man/env/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ... File "/Users/williamgroble/lib_man/env/lib/python3.12/site-packages/allauth/account/views.py", line 173, in get_context_data login_url = self.passthrough_next_url(reverse("account_login")) File "/Users/williamgroble/lib_man/env/lib/python3.12/site-packages/django/urls/base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "/Users/williamgroble/lib_man/env/lib/python3.12/site-packages/django/urls/resolvers.py", line 851, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'account_login' with no arguments not found. 1 pattern(s) tried: ['(?P<library_slug>[^/]+)/accounts/login/\\Z'] Here are my relevant files users/urls.py: from django.urls import path from . import views app_name = 'users' urlpatterns = [ path('<slug:library_slug>/accounts/signup/', views.CustomSignupView.as_view(), name='account_signup'), path('<slug:library_slug>/accounts/login/', views.CustomLoginView.as_view(), name='account_login'), # other patterns... ] lib_man/urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('<slug:library_slug>/accounts/', include('users.urls', namespace='users')), # other patterns... ] users/views.py from django.shortcuts import render, get_object_or_404 from allauth.account.views import SignupView from catalog.models import Library from .user_forms import CustomSignupForm import logging logger = logging.getLogger(__name__) class CustomSignupView(SignupView): form_class = CustomSignupForm template_name = 'account/signup.html' # Set the custom template def dispatch(self, request, *args, **kwargs): library_slug = kwargs.get('library_slug') logger.debug(f"Dispatching signup … -
How can I download satellite images (e.g sentinel-2) from Google Earth Engine (GEE) using the python api in Django
So basically I am trying to create an API endpoint using Django that returns a geoJSON of coordinates and satellite images, which would be consumed by a frontend application (Nextjs/React). The coordinates are displaying as grids, but I am not seeing an image downloaded, I have tried various approaches, even overhauling my codebase a couple of time. In my console cloud Google com monitoring metrics-explorer (image below), it shows that there is an activity going on in my Earth Engine, yet the satellite images are not downloaded in my local directory. enter image description here My code base models.py: from django.contrib.gis.db import models # Create your models here. class farm(models.Model): fid = models.FloatField() name = models.CharField(max_length = 50) size = models.FloatField() crop = models.CharField(max_length = 10) geom = models.MultiPolygonField(srid = 4326) image_path = models.CharField(max_length = 255, blank = True, null = True) def __str__(self): return self.name serializers.py: from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometryField from .models import farm class farmSerializer(GeoFeatureModelSerializer): geom = GeometryField() class Meta: model = farm geo_field = "geom" fields = "__all__" urls.py: from rest_framework.routers import DefaultRouter from django.conf import settings from django.conf.urls.static import static from .views import farmViewSet router = DefaultRouter() router.register( prefix = "api/v1/farms", viewset = farmViewSet, basename … -
'pages' is not a registered namespace
Trying to load a index in this ambient: ├── admin_material │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── models.py │ ├── __pycache__ │ │ ├── admin.cpython-311.pyc │ │ ├── admin.cpython-312.pyc │ │ ├── apps.cpython-311.pyc │ │ ├── apps.cpython-312.pyc │ │ ├── forms.cpython-311.pyc │ │ ├── __init__.cpython-311.pyc │ │ ├── __init__.cpython-312.pyc │ │ ├── models.cpython-311.pyc │ │ ├── models.cpython-312.pyc │ │ ├── tests.cpython-311.pyc │ │ ├── urls.cpython-311.pyc │ │ ├── utils.cpython-311.pyc │ │ ├── utils.cpython-312.pyc │ │ └── views.cpython-311.pyc │ └── static │ ├── templates │ │ ├── accounts │ │ │ ├── login.html │ │ │ ├── password_change_done.html │ │ │ ├── password_change.html │ │ │ ├── password_reset_complete.html │ │ │ ├── password_reset_confirm.html │ │ │ ├── password_reset_done.html │ │ │ ├── password_reset.html │ │ │ └── register.html │ │ ├── admin │ │ │ ├── actions.html │ │ │ ├── auth │ │ │ │ └── user │ │ │ │ ├── add_form.html │ │ │ │ └── change_password.html │ │ │ ├── change_form.html │ │ │ ├── change_form_object_tools.html │ │ │ ├── change_list.html │ │ │ ├── change_list_object_tools.html │ │ │ ├── change_list_results.html │ │ │ ├── delete_confirmation.html │ │ │ ├── … -
KeyError at /accounts/register/
I have a problem with an error occurring when switching to /accounts/register/. I hope you can help me. this is code: registration/urls.py: from django.contrib.auth import views as auth_views from django.urls import path from . import views urlpatterns = [ path('/register', views.register, name='register'), ] registration/views.py: from django.shortcuts import render from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from .forms import RegistrationForm from django.shortcuts import render, redirect def sign_up(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') else: form = RegistrationForm() return render(request, 'registration/register.html', {'form': form}) def register(): print("hello!") urls.py(In the project itself): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('news/', include('news.urls')), path('accounts/', include('django.contrib.auth.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I've tried a lot of YouTube videos and documentation, but still -
How to get set-cookies in react from django
I am running frontend as react and backend as Django. I've configured CORS and set up my environment for my web application. Within this application, I'm storing some values in session for each user. The requirement is to persist data across subsequent requests from the frontend. However, I'm facing an issue in retrieving the session ID from the response.I've ensured that the CORS policies are correctly configured. Despite this, I'm unable to extract the session ID from the response.I was able to see the sessionid from the Browser but not on react. Question: How can I properly extract the session ID from the response in my React application? Could someone guide me on how to properly retrieve the session ID from the response in my setup? Any insights or suggestions would be greatly appreciated. Thank you! My CORS from corsheaders.defaults import default_headers,default_methods CORS_ALLOW_HEADERS = ( *default_headers, ) CORS_ALLOW_METHODS = ( *default_methods, ) CORS_ORIGIN_ALLOW_ALL = True # Set to False for security reasons # CORS_ORIGIN_WHITELIST = [ # "http://127.0.0.1:3000", # "http://localhost:3000", # # Add other origins as needed # "http://192.168.1.36:3000", # ] CORS_ALLOW_CREDENTIALS = True My MIDDLEWARE MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', # Include only once 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', …