Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I implement email verification in Django
Completely stumped! I'm using the console as my email backend. I end up with False in token_generator.check_token as a result Invalid or expired token. is displayed in my homepage when I navigate to say http://localhost:8000/user/verify-email/?token=cgegv3-ec1fe9eb2cebc34e240791d72fb10d7d&email=test16@example.com Here's my code from django.contrib.auth.tokens import PasswordResetTokenGenerator class CustomPasswordResetTokenGenerator(PasswordResetTokenGenerator): pass # Define a single instance of the token generator token_generator = CustomPasswordResetTokenGenerator() def verify_email(request): email = request.GET.get("email") token = request.GET.get("token") try: user = CustomUser.objects.get(email=email) except CustomUser.DoesNotExist: messages.error(request, "Invalid verification link.") return redirect("home") if token_generator.check_token(user, token): user.is_active = True user.save() messages.success(request, "Your email has been verified!") return redirect("sign_in") else: messages.error(request, "Invalid or expired token.") return redirect("home") from django.core.mail import send_mail from django.urls import reverse from user_management.utils import token_generator def send_verification_email(user, request): token = token_generator.make_token(user) verification_url = request.build_absolute_uri( reverse("verify_email") + f"?token={token}&email={user.email}" ) send_mail( "Verify your email", f"Click the link to verify your email: {verification_url}", "no-reply@example.com", [user.email], fail_silently=False, ) -
Django filter not working when using F() with ManyToMany
I have the following query: MyModel.objects.filter(foreing_key__value=F('value')) And It works perfectly. But now I have some complex rules where I need to evaluate the ForeignKey value depending on some conditions. Just to simplify, if I refactor the query to: MyModel.objects.annotate( valid_value=F('foreing_key__value') ).filter( valid_value=F('value') ) It doesn't work when the foreing_key__value is NULL. Why is this happening? I think it's related to LEFT JOIN, which is not applied when using the F() operator, but I'm unsure how to fix this issue. Thanks in advance -
Django project domains
I'm trying to figure 1) if Django can do these things and 2) if it can, should I? I'm thinking it is easier to manage just 1 project vs multiple, but I don't know exactly what Django is capable of yet... If I have my main application at example.com and say I begin a blog about the application at blog.example.com. Can I use one Django project for that or do I need to have 2 Django projects. One to handle example.com and the other to handle blog.example.com? Note: I will be using DRF in this project and I don't know if that makes a difference? -
Multiple different forms in a view Django
I was wondering if there was a way to have multiple different forms in a single view and to press a single submit button for the information to be stored. I have the following forms, the first one is my general form that should be created first: class GeneralForm(forms.ModelForm): name = forms.CharField(max_length=50) TYPE_CHOICES = ( ("C","C"), ("E","E") ) STATUS_CHOICES = ( ("A", "A"), ("F", "F"), ) type=forms.ChoiceField(choices=STATUS_CHOICES) number=forms.CharField(max_length=50) TURN_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3") ) turn = forms.ChoiceField(choices=TURN_CHOICES) class Meta: model = models.General fields=["name","type","number","turn"] The second one needs an instance of the first one and so does the third: class TypeOneForm(forms.ModelForm): num_chairs=forms.IntegerField() num_instalations = forms.IntegerField() total = forms.IntegerField() num_programs = forms.IntegerField() class Meta: model = models.TypeOne fields=["num_chairs","num_instalations","total","billetes_cien"] class TypeTwoForm(forms.ModelForm): num_available_seats=forms.IntegerField() num_available_instalations = forms.IntegerField() total = forms.IntegerField() num_new_programs = forms.IntegerField() class Meta: model = models.TypeTwo fields=["num_available_seats", "num_available_instalations","total","num_programs" ] I was reading I could use FormSets but im not sure if i can use different forms instead of multiple instances of the same form -
I am actually working on the route integration with my personal web site || Is there any available public api for YouTube [closed]
I needed to integrate the YouTube with my personal website backend. Is there any public api available for the same. Thanks.... The API is required to integrate. So that can call to the api & get the data of the relevant YouTube videos.. -
Django not found in Github actions
I have the following CI pipeline defined in Github Actions. It is using the same container as which the production server is using. The pipeline was running fine last week, but this week it suddenly stopped working. Some observations from the run logs: We start with upgrading pip, but this doesn't seem to happen The dependencies are installed correctly, but it gives a warning that pip can be upgraded Running fake migrations immediately fails with ModuleNotFoundError: No module named 'django'. Any ideas how I can debug this to investigate what is going wrong? test_project: runs-on: ubuntu-latest container: image: python:3.11-slim strategy: max-parallel: 2 matrix: python-version: [ "3.11" ] services: postgres: image: postgres:14 env: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres ports: - 5432:5432 options: >- --health-cmd "pg_isready -U postgres" --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install -r requirements-test.txt - name: Check missing migrations run: python project/manage.py makemigrations --check --dry-run --settings project.settings.local - name: Run Tests run: pytest --cov=project project/ -
How to apply a django filter only if both field have a value
I have a simple django filters interface like this This is how I wrote the filters, but of course it is wrong because it adds the filter even when i choose only one field. Also I'm sharing the same FilterSet for both. tipo_oid = filters.ChoiceFilter(label='Tipo Identificativo', choices = TipoOid.objects.all().values_list("id","denominazione").exclude(annullato=True).filter(id__in=[2,3,12,22,9,49]).order_by('denominazione'), method='filter_ide') identificativo = filters.CharFilter(label='Identificativo', method='filter_ide') def filter_ide(self, queryset, name, value): if name == 'tipo_oid': filtroPfIdInPfIde = PfIdentificativi.objects.filter(pf_id=OuterRef('id')).filter(tipo_oid=value).exclude(annullato=True) queryset = queryset.filter(Exists(filtroPfIdInPfIde)) if name =='identificativo': filtroIdeInPfIde = PfIdentificativi.objects.filter(pf_id=OuterRef('id')).filter(identificativo=value).exclude(annullato=True) queryset = queryset.filter(Exists(filtroIdeInPfIde)) I need to ignore if only one of the fields have a value and to apply filter() to the queryset only once and only if both have a value. How would you do that? Now even if I would use two separate filters, the result would not be the one I'd like. I think I could just do it in the viewSet, but it's not what I want because I want to do it in the Filter. -
How to adjust the size of help_texts in Django form?
I'm trying to adjust the size of help_texts field of 'username'. I don't understand where should apply the styling. class SignUpForm(UserCreationForm): password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'}), label='') password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Confirm Password'}), label='') class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'phone'] widgets = { 'username': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Username'}), 'email': forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email Address'}), 'phone': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone Number'}), } labels = { 'username': '', 'email': '', 'phone': '' } help_texts = { "username": "Must contain only letters, numbers, hyphens and underscores.", } -
SSL issue in django web application
I am working on a django web application in python and I use docker containers. My ssl certificate has expired and I want to get a signed certificate from a domain such as go daddy. I tried to use a self signed certificate but I am not able to redirect the website to https. Even though I added reverse proxy in my nginx.conf file to listen to port 80 and 443. Has anyone worked on this before and I will share more details on the same. i have this in my app.conf file server { listen 80; server_name appliication.com www.application.com Ip address 0.0.0.0; location /.well-known/acme-challenge/ { root /var/www/certbot; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name appliication.com www.appliication.com Ip address 0.0.0.0; ssl_certificate /etc/path to key; #.crt ssl_certificate_key /etc/path to key; #.pem location / { proxy_pass http://backend:8000; #for demo purposes } } in my docker-compose.yml file I have the below code services: nginx: image: nginx ports: - "80:80" - "443:443" volumes: - ./app.conf:/etc/nginx/conf.d/default.conf - /path/to/your/certificate.pem:/etc/ssl/certs/your_certificate.pem - /path/to/your/private.key:/etc/ssl/private/your_private.key i am not sure where I am going wrong. can anyone help with this -
Django with crisp_forms and django_filters
I want to build a form to create a database object instance using the crispy Layout object. I need a Django filter which appears between the 2 radios (Article List and Category List) and the categories listboxes (see mock below). The 2 filters (Name and Level) should filter the available categories. So, I need a GET form (for the filters) inside the POST form (to create the database object). Any idea how to solve this with crispy? Thanks! -
Execute raw SQL before each select for specific model
I have a complicated report in Django, which is written as raw SQL, and than stored in the database as a database view. I have a Django model (managed=False), tied to that database view, so that I can utilize the django ORM and django rest framework, on top of the database view. This practice is something that I have used on several projects, and works fine. For one specific report, I found that I need to meddle with the postgres query planner, to get it running faster. Before each SELECT statement on that model (database view), to get the SQL to run faster, I need to do: SET enable_nestloop TO off; The query is quite complex, with aggregate functions, and joins on subqueries, so I gave up on trying to optimize it. Turning off the nestloop solves all my performance issues, and I am fine with that, as long as I turn it on back after the query. Here is an explanation of the problem and the solution. (What are the pitfalls of setting enable_nestloop to OFF) At the moment, what I do, is wrap the Report query in a database trasaction, and set the enable_nestloop only within that transaction, … -
Unable to send messages via React frontend and POST requests fail on Django REST API panel
I am building a chat application using React for the frontend and Django for the backend. I am facing the following two issues: Issue with sending messages in React: When I try to send a message through the React app, I receive a 400 Bad Request error. The API request is made to the backend using a POST request, but the response indicates that there was a problem. The error message doesn't provide much insight, and I cannot send the message. Issue with POST request in Django REST API panel: When I try to make a POST request from the Django REST framework interface (admin panel) to send a chat message, the request seems to go through successfully but redirects to a blank page (without an error). The data is not posted, and nothing changes on the frontend. However, when I use curl to send the same request, it works fine. Here’s a snippet of the relevant React code for sending messages: const handleSendMessage = async () => { if (message.trim() || file) { setSendingMessage(true); const formData = new FormData(); formData.append('receiver', selectedContact.id); formData.append('content', message); if (file) formData.append('file', file); try { const response = await fetch(`http://127.0.0.1:8000/api/chat/${userData?.current_basic_user?.username}/`, { method: 'POST', headers: { … -
Django Docker Setup: OperationalError - "FATAL: database 'guardian_grid' does not exist" with PostgreSQL After Running for a Few Days
I’m experiencing a recurring issue with my Django project configured to run with PostgreSQL in Docker. After a few days of smooth operation, the PostgreSQL database unexpectedly fails, and I receive the following error: django.db.utils.OperationalError: connection to server at "postgres" (172.18.0.2), port 5432 failed: FATAL: database "guardian_grid" does not exist I’ve shared my Docker Compose configuration below. The setup includes volumes for persistent data and backup storage for PostgreSQL. Despite this, the database sometimes "disappears," and I’m unsure why this is happening. I’m looking for insights into potential causes and solutions to ensure the database remains intact. volumes: guardian_grid_local_postgres_data: {} guardian_grid_local_postgres_data_backups: {} services: postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: guardian_grid_local_postgres container_name: guardian_grid_local_postgres volumes: - guardian_grid_local_postgres_data:/var/lib/postgresql/data - guardian_grid_local_postgres_data_backups:/backups - /home/ehabsami/Desktop/guardian_grid/init.sql:/docker-entrypoint-initdb.d/init.sql env_file: - .envs/.local/.postgres ports: - "5432:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 10s retries: 5 guardian_grid: build: context: . dockerfile: ./compose/production/django/Dockerfile # Ensure correct path for Django Dockerfile restart: always image: guardian_grid_local_django container_name: guardian_grid_local_django depends_on: postgres: condition: service_healthy redis: condition: service_started volumes: - .:/app:z command: /bin/sh -c "/run.sh" # Ensure run.sh exists ports: - "8000:8000" env_file: - .envs/.local/.django redis: image: "redis:alpine" ports: - "6379:6379" # Python and dependencies setup FROM docker.io/python:3.12.4-slim-bookworm AS python # Python build stage FROM python … -
Django model to relate with "container" of another model multiple objects
Sorry for weird topic naming but trying to find out the best way to create model relation with some kind of objects set. Lets say I have some models: class Furniture(models.Model): title = models.CharField() category = models.ForeignKey(Category) price = models.PositiveIntegerField() class Plumbing(models.Model): title = models.CharField() .... class Part(models.Model): title = models.CharField() code = models.CharField() I want to build relations of every Furniture / Plumbing instances with some set of Part instances (like fittings, screws, etc.). The first most obvious approach is to create ManyToMany field in Furniture and Plumbing models. But wondering if there is another approach to create some kind of "container" to have all the objects related together. As we know - there is no one-to-many field in Django and I don't want to keep planty null fields in Part if I decide to make relations for many other models (not only Furniture and Plumbing). I know that models archutecture is weid since it's a legacy code but any suggestions are welcome. -
Django - Unable to convert a list of dictionary to a table
I've a list of dictionary. mylist = [{'id': 1, 'name': 'abc'}, {'id': 2, 'name': 'xyz'}] i'm passing this mylist to an html page. return render(request, "viewdb.html", {'mylist':mylist}) and in my viewdb.html, code is as given below. {% if mylist %} <table> <tr> <th> ID </th> <th> Name </th> </tr> {% for user in mylist %} {% for key, value in user.items %} <tr> <td> {{ value }} </td> <td> {{ value }} </td> </tr> </table> {% endfor %} {% endfor %} {% endif %} </body>``` I want the table to look like this. ID NAME 1 abc 2 xyz please help. -
CustomUser model setup in django rest framework
i tried creating a CustomUser model which inherits from AbstractBaseUser in drf, but when i try creating a new super user to log into the admin site, it doesn't work. it shows superuser created successfully but when running manage.py shell and trying to get that exact user i just created, it apparently doesn't exist. my custom user model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, Group, Permission from .managers import UserManager from django.utils.translation import gettext_lazy as lz import uuid import base64 ITEM = ( ("pastries", 'pastries'), ("rentals",'rentals'), ("music", 'music'), ("help", 'help') ) class CustomUser(AbstractBaseUser, PermissionsMixin): objects = UserManager() id = models.CharField(max_length=12, unique=True, primary_key=True, editable=False) username = models.CharField(max_length=55, unique=True) email = models.EmailField(verbose_name=lz('email address'), unique=True, max_length=255) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) last_login = models.DateTimeField(null=True, blank=True) is_verified = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) groups = models.ManyToManyField( Group, related_name='accounts_user_groups', blank=True, help_text="the groups this user belongs to", verbose_name=lz('groups') ) user_permissions = models.ManyToManyField( Permission, related_name='accounts_user_permissions', blank=True, help_text="permissions for this user", verbose_name=lz('user permissions') ) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] def __str__(self) -> str: return self.email @property def get_full_name(self): return f'{self.first_name} {self.last_name}' def save(self, *args, **kwargs): if not self.id: # Generate a shorter base64-encoded UUID hex_string … -
pyodbc Transactions in Django View are Committing Changes Despite Rollback Attempts
I'm working on a Django application where I'm using pyodbc to connect to an AWS RDS SQL Server database. I need to run a series of raw SQL queries (including INSERT, UPDATE, DELETE, DISABLE or ENABLE a trigger etc.) as a transaction, ensuring that no changes are committed if any error occurs during execution. However, I’m running into an issue where changes are getting committed to the database even when an error occurs, and I call rollback(). Here’s what I’ve tried so far: Set autocommit = False on the pyodbc connection to prevent automatic commits. Used multiple cursors for different SQL statements, all under the same connection with autocommit = False. Wrapped the Django view with @transaction.non_atomic_requests to disable Django’s default transaction handling. Also tried wrapping the code with transaction.atomic() to see if Django’s transaction management could help. Despite all of these efforts, changes are still being committed to the database after the error occurs in the Django view, but when I run the exact same code in a standalone Python script (outside of Django), the rollback works perfectly, and no changes are committed. Here’s a simplified version of the code I’m using: import pyodbc from django.conf import settings from … -
Issue with django-crispy-forms and django-filter: CSS class not applying to custom ChoiceFilter field
I'm using django-filter and django-crispy-forms to create a filter form in Django, but I'm having trouble applying a CSS class to a custom ChoiceFilter field. The CSS class is successfully applied to the date field but does not work for the transaction_type field, which is defined as a ChoiceFilter. Here’s my current code: import django_filters from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Field from .models import Transaction class TransactionFilter(django_filters.FilterSet): type = django_filters.ChoiceFilter( choices=Transaction.TRANSACTION_TYPE_CHOICES, field_name="type", lookup_expr="iexact", empty_label="Any", ) class Meta: model = Transaction fields = ['transaction_type', 'date'] def __init__(self, *args, **kwargs): super(TransactionFilter, self).__init__(*args, **kwargs) self.form.helper = FormHelper() self.form.helper.form_method = 'GET' self.form.helper.layout = Layout( Field('transaction_type', css_class='MY-CLASS'), Field('date', css_class='MY-CLASS'), ) In this setup, I expected both fields to have the MY-CLASS CSS class, but only the date field reflects it, not transaction_type. I suspect this might be due to transaction_type being a custom ChoiceFilter field, but I'm not sure how to resolve it. I've tried a few different approaches, such as updating widget attributes and applying CSS directly through attrs, but nothing has worked so far. Has anyone encountered this issue before or have suggestions on how to force the CSS class to apply to the ChoiceFilter field? -
'TranscriptionConsumer' object has no attribute 'base_send' Websocket Django
I'm trying to do site that translates .wav audio into text in django. I've got a problem here. I'm using websocket to send translated text immediately. But when I try to send a text, this error occurs ('TranscriptionConsumer' object has no attribute 'base_send') views.py # this function recognites text and send it to Consumers's function def get_large_audio_transcription(path,language, consumer ,minutes=2): sound = AudioSegment.from_file(path) chunk_length_ms = int(1000*60*minutes) chunks = [sound[i:i + chunk_length_ms] for i in range(0, len(sound), chunk_length_ms)] folder_name=str(settings.MEDIA_ROOT) + "/audio-chunks/" if not os.path.isdir(folder_name): os.mkdir(folder_name) whole_text = "" for i, audio_chunk in enumerate(chunks,start=1): chunk_filename = os.path.join(folder_name, f"chunk{i}.wav") audio_chunk.export(chunk_filename, format="wav") try: text = transcribe_small_audio(chunk_filename, language=language) except sr.UnknownValueError as e: print("Error:", str(e)) else: text = f"{text.capitalize()}." print(text) whole_text += text json_transcribe = json.dumps({"message": text}) # Sending json text through WebSocket consumer.send_json(json_transcribe) # deleting chunk try: os.remove(chunk_filename) except FileNotFoundError: print("Error: file not found") return whole_text @login_required(login_url='login_user') def index(request): context = None audio_form = UploadFileForm() if request.method == "POST": audio_form = UploadFileForm(request.POST, request.FILES) if not audio_form.is_valid(): messages.success(request, ("Error!")) return render(request, 'recognition/index.html', {"error": "Provide a valid file"}) try: form = audio_form.save(commit=False) form.name = request.user form.save() file = form.audio # get the audio file_size = file.size file_path = str(settings.MEDIA_ROOT) + '/' + str(file.name) consumer = TranscriptionConsumer() messages.success(request, ("File … -
Django compiling to pyc and running server
Ok so i run python -m compileall . However the generated files are in pycache manage.cpython-311.pyc and urls.cpython-311 my issue is when i run python manage.cpython-311.pyc runserver I keep getting the error File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked ModuleNotFoundError: No module named 'settings' I am not the brightest django developer. However, i would appreciate if someone shares with me how to fix this issue. -
Shorcut for opening vs code from windows explorer
Is there any keyboard shortcut that i can use to open folder in vs code from windows explorer. I am too lazy to right click and open that with vs code. -
How to ManifestStaticFilesStorage with django-storages, boto3 on DigitalOcean Spaces Object Storage?
Context: I am running Django==5.1.2. I need to have cache busting for my static files on prod. On dev, my settings are like so STORAGES = { "default": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") This works as you would expect. When debug=False, django uses the hashed static files for the urls. But on prod my settings are like so # DigitalOcean Spaces Settings # Ref: https://www.digitalocean.com/community/tutorials/how-to-set-up-object-storage-with-django AWS_ACCESS_KEY_ID = os.getenv("DO_SOS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("DO_SOS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = os.getenv("DO_SOS_STORAGE_BUCKET_NAME") AWS_S3_ENDPOINT_URL = os.getenv("DO_SOS_ENDPOINT_URL") AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400", } AWS_DEFAULT_ACL = "public-read" STORAGES["default"]["BACKEND"] = "storages.backends.s3boto3.S3Boto3Storage" STORAGES["staticfiles"]["BACKEND"] = "storages.backends.s3boto3.S3Boto3Storage" AWS_S3_SIGNATURE_VERSION = ( "s3v4" ) AWS_S3_CUSTOM_DOMAIN = os.getenv("DO_SOS_CUSTOM_DOMAIN") # Static & Media URL STATIC_URL = f"{AWS_S3_ENDPOINT_URL}/static/" MEDIA_URL = f"{AWS_S3_ENDPOINT_URL}/media/" As you can see, the backend is using "storages.backends.s3boto3.S3Boto3Storage" on prod instead of "django.contrib.staticfiles.storage.ManifestStaticFilesStorage". Which is kindof my problem. Whatever static content is saved to my Digital Ocean Spaces Object Storage is not hashed. How can I configure my django project to save the hashed static files to my Spaces Object Storage? -
Document is empty after performing fitz.open() on an io.BytesIO stream of a pdf
I am trying to get a PDF file from Mongodb and convert it to an io.BytesIO stream to keep it in the memory. Here is the snippet. fs = gridfs.GridFS(db) outputData = fs.get(file_id).read() pdf_stream = io.BytesIO(outputData) # Open the PDF from the stream doc = fitz.open(stream=pdf_stream, filetype="pdf") Running the Debugger I can see that the outputData is correct and has b'%PDF-' indicating a valid PDF. The pdf_stream is also generated correctly, but when I try to open this using fitz.open(), the document created is empty and returns Document('', <memory, doc# 2>) I am not able to figure out what the problem is and would like to have to help. -
Follow-up: How to override the Map Widget in Django Admin in which Geom Data Loaded via LayerMapping?
This question follows up on my initial query about dynamically changing the color of shapefile layers on a Django Admin Leaflet map. In my GeoDjango project, I'm loading geometry data via the LayerMapping method. Below is the load.py file I'm using for this: from django.contrib.gis.utils import LayerMapping from .models import Municipality municipality_mapping = { 'reg_code': 'Reg_Code', 'reg_name': 'Reg_Name', 'pro_name': 'Pro_Name', 'mun_code': 'Mun_Code', 'mun_name': 'Mun_Name', 'mean_ctrl': 'mean_ctrl', 'geom': 'MULTIPOLYGON', } zonalmeanctrl_shp = "path/to/shapefile.shp" def run(verbose=True): lm = LayerMapping(Municipality, zonalmeanctrl_shp, municipality_mapping, transform=False) lm.save(strict=True, verbose=verbose) In admin.py, I configured the admin panel with LeafletGeoAdmin: from django.contrib import admin from .models import Municipality from leaflet.admin import LeafletGeoAdmin class MunicipalityAdmin(LeafletGeoAdmin): list_display = ('pro_name', 'reg_code', 'reg_name', 'mun_code', 'mun_name', 'mean_ctrl') admin.site.register(Municipality, MunicipalityAdmin) Now, I would like to go further by customizing the map widget to dynamically style the geometries based on certain attributes (e.g., changing the color based on the mean_ctrl value). How can I override the map widget in Django Admin to apply dynamic colors to these shapefiles loaded via LayerMapping? -
django rest framework with simplejwt getting a 200 ok response even for invalid tokens
I am using django-rest-framework, djoser and simplejwt to build out token auth for user accounts. I can create an account, activate and login with Postman. But for some reason I having an issue with the /refresh and /verify endpoints. I'm also having an issue with /logout and /auth/me but I'm guessing if I can fix the /refresh and /verify endpoints the other ones will also fix themselves. These are the test urls and methods that I'm using with Postman POST http://localhost:8000/api/users/ After this I go to my email and copy the uid and token POST http://localhost:8000/api/users/activation/ enter the uid and token in the body of the request POST http://localhost:8000/api/jwt/create/ make sure email and pw are in the body and click send, receive refresh and access tokens POST http://localhost:8000/api/jwt/refresh/ enter the refresh token like so {"refresh": "kjlsjfdlskldjfls...."} It is here that I will enter an extra character at the end to make it and invalid token, but I still get a 200 ok along with an access token, why? POST http://localhost:8000/api/jwt/verify enter {"token": "jaslkfjsld...."} again, enter an extra character to invalidate the token but I still get a 200 ok with an access token, why? I have poured over what I …