Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to setup Nginx as a reverse proxy for Django in Docker?
I'm trying to setup nginx as a reverse proxy for Django in docker so I can password prompt users that don't have a specific IP. However I can't get it to work. I have a Django app with a postgreSQL database all set up and working in Docker. I also have a Nginx container I just can't see to get the two connected? I haven't used Nginx before. The closest I have got is seeing the welcome to Nginx page at localhost:1337 and seeing the Django admin at localhost:1337/admin but I get a CSRF error when I actually try and login. Any help would be much appreciated! I have tried setting up Nginx in Docker using the following files: Here's my docker-compose.yml file: services: web: build: . command: gunicorn config.wsgi -b 0.0.0.0:8000 environment: - SECRET_KEY=django-insecure-^+v=tpcw8e+aq1zc(j-1qf5%w*z^a-5*zfjeb!jxy(t=zv*bdg - ENVIRONMENT=development - DEBUG=True volumes: - .:/code - static_volume:/code/staticfiles expose: - 8000 depends_on: - db networks: - my-test-network db: image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ nginx: build: ./nginx ports: - "1337:80" volumes: - static_volume:/code/staticfiles depends_on: - web networks: - my-test-network volumes: postgres_data: static_volume: networks: my-test-network: driver: bridge Here's my dockerfile for Nginx: FROM nginx:1.25 RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d Here's my Nginx config file: upstream … -
Django Migration Error: NodeNotFoundError Due to Missing Migration Dependency in Django 5.0
My error is about this migrations and I couldn't understand, i'm burning about this error django.db.migrations.exceptions.NodeNotFoundError: Migration authuser.0001_initial dependencies reference nonexistent parent node ('auth', '0014_user_address_user_city_user_phone_number_and_more') This problem related to django? have to update it? I tried to delete all migrations but after that ruining my project. How to avoid it? -
CRITICAL: [Errno 104] Connection reset by peer in reviewboard due to UnreadablePostError: request data read error
In a reviewboard when am posting the review with rbtools (like cmd: 'rbt post') am getting CRITICAL: [Errno 104] Connection reset by peer error. In reviewboard logs am getting this StackTrace: request data read error Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.7/site-packages/django/views/decorators/cache.py", line 52, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/lib/python2.7/site-packages/django/views/decorators/vary.py", line 19, in inner_func response = func(*args, **kwargs) File "/usr/lib/python2.7/site-packages/djblets/webapi/resources/base.py", line 162, in call method = request.POST.get('_method', kwargs.get('_method', method)) File "/usr/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 146, in _get_post self._load_post_and_files() File "/usr/lib/python2.7/site-packages/django/http/request.py", line 219, in _load_post_and_files self._post, self._files = self.parse_file_upload(self.META, data) File "/usr/lib/python2.7/site-packages/django/http/request.py", line 184, in parse_file_upload return parser.parse() File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 140, in parse for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 598, in iter for sub_stream in boundarystream: File "/usr/lib/python2.7/site-packages/django/utils/six.py", line 535, in next return type(self).next(self) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 415, in next return LazyStream(BoundaryIter(self._stream, self._boundary)) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 441, in init unused_char = self._stream.read(1) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 315, in read out = b''.join(parts()) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 308, in parts chunk = next(self) File "/usr/lib/python2.7/site-packages/django/utils/six.py", line 535, in next return type(self).next(self) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 330, in next output = next(self._producer) File "/usr/lib/python2.7/site-packages/django/utils/six.py", line 535, in next return … -
Serving a dockerized react and django static files with nginx as web server and reverse proxy
I have simple dockerized react and django app that I'd like to serve using nginx as web server for serving both react and django's static files and as reverse proxy to forward user requests to the django backend served by gunicorn. But I have been struggling with nginx for serving react and django static files. here is the nginx Dockerfile: FROM node:18.16-alpine as build WORKDIR /app/frontend/ COPY ../frontend/package*.json ./ COPY ../frontend ./ RUN npm install RUN npm run build # production environment FROM nginx COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf COPY --from=build /app/frontend/build /usr/share/nginx/html here is the docker-compose file: version: '3.9' services: db: image: mysql:8.0 ports: - '3307:3306' restart: unless-stopped env_file: - ./backend/.env volumes: - mysql-data:/var/lib/mysql backend: image: vinmartech-backend:latest restart: always build: context: ./backend dockerfile: ./Dockerfile ports: - "8000:8000" volumes: - static:/app/backend/static/ env_file: - ./backend/.env depends_on: - db nginx: build: context: . dockerfile: ./nginx/Dockerfile ports: - "80:80" volumes: - static:/app/backend/static/ restart: always depends_on: - backend # - frontend volumes: mysql-data: static: here is the nginx configuration file: upstream mybackend { server backend:8000; } server { listen 80; location /letter/s { proxy_pass http://backend; } location /contact/ { proxy_pass http://backend; } location /admin/ { alias /static/; } location /static/ { alias /static/; } location / … -
Converting django serializer data to google.protobuf.struct_pb2.Struct gives error: TypeError: bad argument type for built-in operation
I want to create a response message in grpc with the following format: message Match { int32 index = 1; google.protobuf.Struct match = 2; google.protobuf.Struct status = 3; } I have a serializer and I want to convert the data into protobuf struct. my serializer is nested and long, so i have posted only a small part of the code in here. class MatchSerializer(proto_serializers.ModelProtoSerializer): competition = serializers.SerializerMethodField() match = serializers.SerializerMethodField() status = serializers.SerializerMethodField() class Meta: model = Match proto_class = base_pb2.Match fields = ['index', 'match', 'competition', 'status'] def get_competition(self, obj): data = SomeSerializer(obj.competition).data struct_data = struct_pb2.Struct() return struct_data.update(data) def get_status(self, obj): status_dict = { 0: {0: "not started"}, 1: {1: "finished"}, 2: {9: "live"}, } result = status_dict[obj.status] struct_data = struct_pb2.Struct() return struct_data.update(result) def get_match(self, obj): data = SomeOtherSerializer(obj.match).data struct_data = struct_pb2.Struct() return struct_data.update(data) Besides, I cannot find the source of what is really making this problem. I am getting this error from serializing: Traceback (most recent call last): File "/project/venv/lib/python3.10/site-packages/grpc/_server.py", line 555, in _call_behavior response_or_iterator = behavior(argument, context) File "/project/base/grpc/services.py", line 44, in GetUserSubscribedTeamsMatches return MatchSerializer(val).message File "/project/venv/lib/python3.10/site-packages/django_grpc_framework/proto_serializers.py", line 31, in message self._message = self.data_to_message(self.data) File "/project/venv/lib/python3.10/site-packages/rest_framework/serializers.py", line 555, in data ret = super().data File "/project/venv/lib/python3.10/site-packages/rest_framework/serializers.py", line 253, in … -
Ckeditor how addRichoCombo in fetch api?
CKEDITOR.plugins.add('type_elem_dropdown', { init: function (editor) { editor.on('instanceReady', function () { // Retrieve scenarioId and branchId from the editor's configuration var scenarioId = editor.config.scenarioId; var branchId = editor.config.branchId; // Function to fetch type_elements data function fetchTypeElements(scenarioId, branchId) { return fetch(`/scenario/${scenarioId}/branch/${branchId}/typeelements`) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .catch(error => { console.error('Error fetching type_elems:', error); return []; }); } // Fetch type elements and initialize the RichCombo fetchTypeElements(scenarioId, branchId).then(typeElems => { if (!typeElems || typeElems.length === 0) { console.warn('No typeElems available, aborting addRichCombo.'); return; } // Create RichCombo UI elements typeElems.forEach((element, index) => { // Add a RichCombo for each typeElem editor.ui.addRichCombo('TypeElemNames' + (index + 1), { label: 'Type Elements', title: 'Insert Type Element', voiceLabel: 'Type Elements', className: 'cke_format', multiSelect: false, panel: { css: [CKEDITOR.skin.getPath('editor')].concat(editor.config.contentsCss), attributes: { 'aria-label': 'Type Elements Dropdown' } }, init: function () { this.startGroup('Type Elements'); this.add(element.id, element.name, element.name); }, onClick: function (value) { editor.focus(); editor.fire('saveSnapshot'); editor.insertHtml(value); editor.fire('saveSnapshot'); } }); }); }); }); } }); I tried to add a dropdown list in editor with options of dropdown list by get from API (fetch(`/scenario/${scenarioId}/branch/${branchId}/typeelements`) but not working, show nothing. And I want to add many of Rich Combo, a number … -
ValueError at /admin/backoffice/profile/add/ save() prohibited to prevent data loss due to unsaved related object 'profile'
i use my prfile as a managing user models and i got this error: ValueError at /admin/backoffice/profile/add/ save() prohibited to prevent data loss due to unsaved related object 'profile'. i want add profile and then can login with these profiles that i created. my profile: class ProfileManager(BaseUserManager): def create_user(self, NATIONALID, password=None, **extra_fields): if not NATIONALID: raise ValueError("The NATIONALID field must be set") user = self.model(NATIONALID=NATIONALID, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, NATIONALID, password=None, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) return self.create_user(NATIONALID, password, **extra_fields) class Profile(models.Model): id = models.BigAutoField(primary_key=True) deathdate = models.DateField(blank=True, null=True, verbose_name='تاریخ فوت') isactive = models.BigIntegerField(default=1, blank=True, null=True, verbose_name='وضعیت کاربر') activefrom = models.DateTimeField(blank=True, null=True, verbose_name='فعال از') activeto = models.DateTimeField(blank=True, null=True, verbose_name='فعال تا') childrennumber = models.BigIntegerField(blank=True, null=True, verbose_name='تعداد فرزند') createdat = models.DateTimeField(auto_now_add=True, blank=True, null=True, verbose_name='تاریخ ایجاد') createdby = models.BigIntegerField(default=1, blank=True, null=True, verbose_name='ایجاد شده توسط') defunctdate = models.BigIntegerField(blank=True, null=True, verbose_name='') foundationdate = models.BigIntegerField(blank=True, null=True, verbose_name='') gender = models.BigIntegerField(blank=True, null=True, verbose_name='جنسیت') graduation = models.BigIntegerField(blank=True, null=True, verbose_name='سطح تحصیلات') location = models.BigIntegerField(blank=True, null=True, verbose_name='شهر') maritalstatus = models.BigIntegerField(blank=True, null=True, verbose_name='وضعیت تاهل') modifiedat = models.DateTimeField(auto_now=True, blank=True, null=True, verbose_name='تاریخ بروزرسانی') modifiedby = models.BigIntegerField(blank=True, null=True, verbose_name='بروزرسانی شده') religion = models.BigIntegerField(blank=True, null=True, verbose_name='مذهب') postalcode = models.CharField(max_length=10, blank=True, null=True, verbose_name='کدپستی') zonecode = models.CharField(max_length=10, blank=True, null=True, verbose_name='منطقه') FOREIGNERID = models.CharField(max_length=12, blank=True, … -
Media Files being unable to serve on production environment
I'm trying to deploy my django app on the render, but confronted a problem when I set DEBUG=FALSE. My media files, which are uploaded by using admin interface through the models' imagefield, are unable to show. I think the problem exists within my nginx settings and django setting. However, I've tryied several times but still unable to fix the problme. I set nginx.conf: http { include mime.types; server { listen 80; root C:/Users/USER/Desktop/onemoretime; # location / { # try_files $uri $uri/ =404; # } location /static/ { alias C:/Users/USER/Desktop/onemoretime/staticfiles/; } location /media/ { alias C:/Users/USER/Desktop/onemoretime/media/; } location / { proxy_pass http://127.0.0.1:8000; # 代理到 Waitress proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } } events {} and django setting: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') in this way. I think nginx should be able to deal with and serve all the media files, but the thing is the other way around. I'll be really thankful if someone know why the problem arise and how to fix it. Thank you so much. -
I am facing this error while running a docker file, and unable to solve it
I am getting this error while executing docker-compose build, i am unable to understand it. 1.241 The following information may help to resolve the situation: 1.241 1.241 The following packages have unmet dependencies: 1.324 mongodb-org-mongos : Depends: libssl1.1 (>= 1.1.0) but it is not installable 1.324 mongodb-org-server : Depends: libssl1.1 (>= 1.1.0) but it is not installable 1.324 mongodb-org-shell : Depends: libssl1.1 (>= 1.1.0) but it is not installable 1.327 E: Unable to correct problems, you have held broken packages. ------ failed to solve: process "/bin/sh -c apt-get install -y mongodb-org" did not complete successfully: exit code: 100 This is the docker file # set base image (host OS) FROM python:3.8 RUN rm /bin/sh && ln -s /bin/bash /bin/sh RUN apt-get -y update RUN apt-get install -y curl nano wget nginx git RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list # Mongo RUN ln -s /bin/echo /bin/systemctl RUN wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | apt-key add - RUN echo "deb http://repo.mongodb.org/apt/debian buster/mongodb-org/4.4 main" | tee /etc/apt/sources.list.d/mongodb-org-4.4.list RUN apt-get -y update RUN apt-get install -y mongodb-org # Install Yarn RUN apt-get install -y yarn # Install PIP RUN easy_install pip ENV ENV_TYPE staging … -
Django asks to migrate an unknown app: authtoken
Recently I got this message on running the server. You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): authtoken. The git branch is unchanged, no recent commit contains any authtoken relations. rest_framework.authtoken is part of INSTALLED_APPS since a long time, but as said, no recent changes relate to it. How can I discover what is causing this message in order to get rid of it? -
Django CSS not reflecting, issue only in my system
I encountered an issue where my CSS isn't loading. To troubleshoot, I tried running a previously working project created by my team, but I encountered the same problem. Even the Admin panel isn't loading correctly. It's an exact copy of the project, and I haven't made any changes. I activated the Python virtual environment and installed all the necessary requirements. Can someone help, please? I've tried most of the solutions I found online, including verifying the STATIC_URL, checking security permissions, and even reinstalling Python to match the versions on the machine where everything worked. -
Empty table in DB with django allauth
I am facing a problem with my django application which uses django-allauth as authentication framework. I need to authenticate to my application via google, store the authentication tokens, and then use the token to make some calls to the Google Search Console api. The first part (login) is going straightforward, but I am encountering a major problem in the second part. In particular, the socialaccount_socialapp table in the db remains empty. Does anyone spot any error in my settings? Or can anyone link me any resource regarding the use of Google Console API with an user authenticated with django allauth? These are my relevant parts of settings.py (default django resources omitted) SOCIALACCOUNT_PROVIDERS = { 'google' : { 'APP': { 'client_id' : os.getenv('CLIENT_ID'), 'secret' : os.getenv('SECRET'), 'key': '' }, 'SCOPE': ['profile', 'email', 'https://www.googleapis.com/auth/webmasters'], 'AUTH_PARAMS': { 'access_type' : 'offline', # per fare durare sessione }, "OAUTH_PKCE_ENABLED": True } } SOCIALACCOUNT_STORE_TOKENS = True MIDDLEWARE = [ #......... 'allauth.account.middleware.AccountMiddleware', ] INSTALLED_APPS = [ #........... 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' ] LOGIN_REDIRECT_URL = 'landing_page' LOGIN_URL = 'account_login' I did all the migrations, and it works for the login part, but when I run this view: try: social_account = SocialAccount.objects.get(user=request.user, provider='google') … -
Django formset show raw data in POST but never gets valid
I have the following Django structure. I use the latest Django version 5.1. I aim to get Formset working for the first time. Anyway, whatever I tried my formset is never valid. I can see raw data in request.POST but it does not validate therefore I never get parsed data in cleaned_data. What am I missing ? Model.py class Folder(models.Model): reference = models.CharField(max_length=64, null=False, unique=True,) class Revenue(models.Model): folder = models.ForeignKey(Folder, null=False, on_delete=models.RESTRICT,) amount = models.DecimalField(max_digits=10, decimal_places=2, null=False,) Form.py class FolderForm(forms.ModelForm): class Meta: model = models.Folder fields = ['reference'] class RevenueForm(forms.ModelForm): class Meta: model = models.Revenue fields = ["amount"] RevenueFormset = inlineformset_factory( models.Folder, models.Revenue, RevenueForm, validate_min=True, extra=1, can_delete=True ) View.py class FolderTestView(LoginRequiredMixin, UpdateView): template_name = "core/folder_test.html" model = models.Folder form_class = forms.FolderForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["revenue_formset"] = forms.RevenueFormset(instance=context["object"]) return context def post(self, request, *args, **kwargs): print(request.POST) # Contains whole form raw data formset = forms.RevenueFormset(request.POST) print(formset.is_valid()) # Always set as False return super().post(request, *args, **kwargs) def form_valid(self, form): print(form.cleaned_data) # Never gets the formset data return super().form_valid(form) def get_success_url(self): return reverse("core:folder-test", kwargs={"pk": self.kwargs["pk"]}) url.py urlpatterns = [ path('folder/<int:pk>/test/', views.FolderTestView.as_view(), name='folder-test'), ] folder_test.html <form action="{% url 'core:folder-test' object.id %}" method="POST"> {% csrf_token %} {{ form|crispy }} {{ formset.management_form }} … -
how can i used django on python 3.13?
am trying to install Django on Python 3.13 but am getting this problem (action) PS C:\Users\HP\desktop\AVP> python -m django --version Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\__main__.py", line 7, in <module> from django.core import management File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\management\__init__.py", line 19, in <module> from django.core.management.base import ( ...<4 lines>... ) File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\management\base.py", line 14, in <module> from django.core import checks File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\checks\__init__.py", line 18, in <module> import django.core.checks.caches # NOQA isort:skip ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\checks\caches.py", line 4, in <module> from django.core.cache import DEFAULT_CACHE_ALIAS, caches File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\cache\__init__.py", line 67, in <module> signals.request_finished.connect(close_caches) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^ File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\dispatch\dispatcher.py", line 87, in connect if settings.configured and settings.DEBUG: ^^^^^^^^^^^^^^ File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ val = getattr(_wrapped, name) ~~~~~~~^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'DEBUG' i tried uninstalling the existing Django the installing it again but all in vail -
How to store a `.shp` file to gisModel.GeometryField in model?
I have an example shp file and a model as follow class PolygonShape(models.Model): ... geometry = gisModel.GeometryField(null=False, srid=25832) ... def __str__(self): return self.name I want to upload the shp file and store it at GeometryField of the model. However, i dont know how to do it -
Polars Dataframe via Django Query
I am exploring a change from Pandas to Polar. I like what I see. Currently it is simple to get the data into Pandas. cf = Cashflow.objects.filter(acct=acct).values() df = pd.DataFrame(cf) So I figured it would be a simple change - but this will not work for me. df = pl.DataFrame(cf) What is the difference between using a Django query and putting the data inside Polars? Thank you. -
Django celery Revoke not terminating the task
i have a django celery on on my project and i have set everything and working well but i want to be able too terminate a tasks after it start processing.eg i backup my database through backend tasks and any time i can decide to cancel the tasks so it can terminate the process but when i use from project.celery import app res = app.control.terminate(task_id=task_id this is just returning None without teminating the task. the task still keep running. i have also use revoke which is still the same i am using this doc celery is there anyway to terminate it or i am missing so setting? -
Free hosting web site Django
Please any one know free web site for host deploy my Django small project with postgres db Naginex gunicorn Https domain My last use is digital Ocean but was 6 dollars for registration. Without visa you cant rigster Ok thanks for anyone share -
'charmap' codec can't encode characters in position 18-37: character maps to <undefined> error
I am trying to connect a ml model using django. In here I have loaded the model and necessary encoders. import joblib import os #from keras.model import load_model from keras.src.saving.saving_api import load_model from django.conf import settings import numpy as np def load_keras_model(): # Define the path to the model file model_path = os.path.join(settings.BASE_DIR, 'Ml_Models', 'football_prediction_model.h5') print("Keras model path:", model_path) try: # Load the model model1 = load_model(model_path) # Verify model loading by printing its summary print("Model successfully loaded.") print("Model Summary:") model1.summary() return model1 except Exception as e: # Handle exceptions and print error messages print(f"Error loading model: {str(e)}") return None def load_encoder(filename): encoder_path = os.path.join(settings.BASE_DIR, 'Ml_Models', filename) print(f"{filename} path:", encoder_path) # Debug path return joblib.load(encoder_path) # Load all necessary models and encoders model = load_keras_model() team_label_encoder = load_encoder('team_label_encoder.pkl') outcome_label_encoder = load_encoder('outcome_label_encoder.pkl') scaler = load_encoder('scaler.pkl') def predict_outcome(home_team, away_team, year, month, day, temperature): try: print(f"Home Team: {home_team}") print(f"Away Team: {away_team}") print(f"Year: {year}, Month: {month}, Day: {day}, Temperature: {temperature}") # Encode and scale the input data home_team_encoded = team_label_encoder.transform([home_team])[0] away_team_encoded = team_label_encoder.transform([away_team])[0] temperature_scaled = scaler.transform([[temperature]])[0][0] print(f"Encoded Home Team: {home_team_encoded}") print(f"Encoded Away Team: {away_team_encoded}") print(f"Scaled Temperature: {temperature_scaled}") # Prepare the input for the model input_data = np.array([[home_team_encoded, away_team_encoded, year, month, day, temperature_scaled]]) print(f"input date: … -
Email Verification tokens are not being properly verified
My code to verify users via their email after registering has a problem I can't pinpoint. Once successfully registered, a user receives an email with a link and a token attached. The token is then meant to be verified as valid, or flagged as invalid or expired. The emails are sent successfully. However, both expired and new tokens are also being flagged as invalid. What am I doing wrong? This is the user model in my models.py file: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = UserManager() def __str__(self): return self.email This is my serializers.py file: from rest_framework import serializers from .models import User class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=68, min_length=8, write_only=True) class Meta: model = User fields = ["email", "username", "password"] def validate(self, attrs): email = attrs.get("email", "") username = attrs.get("username", "") if not username.isalnum(): raise serializers.ValidationError( "The username should only contain alphanumeric characters" ) return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) class VerifyEmailSerializer(serializers.ModelSerializer): token = serializers.CharField(max_length=555) class Meta: model = User fields = ["token"] views.py import jwt from django.conf import settings … -
NoReverseMatch at /admin/ Reverse for 'app_list' with keyword arguments '{'app_label': 'admin_index'}' not found
i setup a custom admin page , where added link to page i want , the code worked fine until itried to utilize dajngo_admin_index leading to app_list not being detected , The project has only 1 app named myapp this my admin.py : # Customizing the Admin Interface class CustomAdminSite(admin.AdminSite): def get_urls(self): urls = super().get_urls() custom_urls = [ path('analytics/', self.admin_view(analytics_view), name='custom_analytics'), ] return custom_urls + urls custom_admin_site = CustomAdminSite(name='custom_admin') this my urls.py for admin : from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from myapp.admin import custom_admin_site urlpatterns = [ path('admin/', custom_admin_site.urls), # Register custom admin URLs path('', include('myapp.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this new admin template base_site.html : {% extends "admin/base.html" %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">SDM Administration</a></h1> {% endblock %} {% block user-tools %} <ul class="user-tools"> <li><a href="#">Test Link</a></li> <li><a href="{% url 'admin:password_change' %}">Change password</a></li> <li><a href="{% url 'logout' %}">Log out</a></li> </ul> {% endblock %} {% block nav-global %} <ul class="nav-global"> <li> <a href="{% url 'admin:custom_analytics' %}" class="reports-link">Reports and Analytics</a> </li> </ul> <style> /* Styling for nav-global and reports-link */ .nav-global { display: inline-block; margin-left: 30px; margin-top: 10px; /* Move the button down by 3px … -
How to do multiple users models authentication in django using jwt tokens?
I need a way to authenticate both models of my system with jwt tokens. One of the models is the User model, django built-in, and another is the a Ong model, which has a one-to-one relationship with User. My first approach is a endpoint which verify if the user passed has a ONG linked to it, if yes, return True, otherwise, return False, but im not sure if its secure or something "good" to do. I tried this way because i have no idea of how do this using JWT tokens for both models. My ong model: class ONG(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ong_name = models.CharField(max_length=40) custom_url = models.CharField(max_length=20, default=str(ong_name).replace(' ', ''), blank=True) ong_address = models.CharField(max_length=200, validators=[validate_address]) ong_cnpj = models.CharField(blank=True, validators=[validate_cnpj]) ong_phone_number = models.CharField(max_length=12) ong_email = models.CharField(validators=[EmailValidator]) class Meta: permissions = [("pet_creation", "can create pets")] def __str__(self): return f'ONG: {self.ong_name}' serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id", "username", "password"] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class ONGSerializer(serializers.ModelSerializer): user = UserSerializer(many=False) class Meta: model = ONG fields = ['user', 'ong_name', 'custom_url', 'ong_address', 'ong_cnpj', 'ong_phone_number', 'ong_email'] def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(username=user_data['username'], password=user_data['password']) ong = ONG.objects.create(user=user, ong_name = … -
How to Configure django-admin-tools for Multiple Admin Sites Without Affecting the Default Admin
I'm using django-admin-tools in my Django project to create a dashboard-like custom admin site. I've successfully set up django-admin-tools following the official documentation. My goal is to create a custom admin site and configure django-admin-tools to work exclusively for this site, without affecting the default Django admin site. Below is a simplified version of my code: # Custom Admin Site class AdminSiteDashboard(AdminSite): site_header = 'Dashboard' site_title = 'Dashboard Portal' index_title = 'Welcome to My Dashboard' admin_site_dashboard = AdminSiteDashboard(name='admin_dashboard') # url patterns urlpatterns = [ path('admin_tools/', include('admin_tools.urls')), path('admin/', admin.site.urls), path('dashboard/', admin_site_dashboard.urls), ... ] # settings ADMIN_TOOLS_MENU = { 'base.admin_site.admin_site_dashboard': 'base.admin_tools.base_admin_menu.CustomMenu', } ADMIN_TOOLS_INDEX_DASHBOARD = { 'base.admin_site.admin_site_dashboard': 'base.admin_tools.base_admin_dashboard.CustomIndexDashboard', } ADMIN_TOOLS_APP_INDEX_DASHBOARD = { 'base.admin_site.admin_site_dashboard': 'base.admin_tools.base_admin_dashboard.CustomAppIndexDashboard', } I expected that by configuring django-admin-tools only for admin_site_dashboard, the default admin site would remain unaffected. However, after setting it up as shown above, I can access the dashboard at dashboard/, but I encounter an error when trying to access the default admin site at admin/. The error is: ValueError at /admin/ Dashboard menu matching "{'base.admin_site.admin_site_dashboard': 'base.admin_tools.base_admin_menu.CustomMenu'}" not found,{% if user.is_active and user.is_staff and not is_popup %}{% admin_tools_render_menu_css %}{% endif %} Is there a way to configure django-admin-tools so that it only applies to the custom admin site … -
Can't able to get the id of the model instance in django when i connect the project to MongoDB
I am doing the simple CRUD in djnago project ,first i was working with sqlite that is by default in djnago ,every thing was working properly,but when i configure it with MongoDB ,now create and read operations are working properly ,but for update and delete ,i can't able to get the id of the instance to send it to url with request, getting the error ,, ValueError at /employe/update/None when i try this '<form action="{% url 'update' i.id %}" method="POST">' and when i try to use <form action="{% url 'update' i._id %}" method="POST"Field 'id' expected a number but got 'None'.> _id as it is identifier in mongoDB ,then the syntax arrive comes that attribute can't start with '_',, ValueError at /employe/update/None when i try this '<form action="{% url 'update' i.id %}" method="POST">' and when i try to use <form action="{% url 'update' i._id %}" method="POST"Field 'id' expected a number but got 'None'.> _id as it is identifier in mongoDB ,then the syntax arrive comes that attribute can't start with '_',, -
How to export to Excel Django object where every ForeignKey object a new column with import-export lib?
I have a model represents some item on stock: (Code has been simplified) class StockItem(models.Model): name = models.CharField() category = models.Charfield() stock = models.ForeignKey(Stock) # <- Here is few stocks quantity = models.IntegerField(default=0) So every StockItem may exist on different stocks but with different q-ty remained. Is there a way to create ModelResource to export quantity remained for every stock? Table example: +----+--------+----------+---------+---------+ | ID | Name | Category | Stock A | Stock B | +----+--------+----------+---------+---------+ | 1 | Item 1 | Cat 1 | 1 | 1 | | 2 | Item 2 | Cat 2 | 10 | 8 | | 3 | Item 3 | Cat 3 | 14 | 32 | +----+--------+----------+---------+---------+ My ModelResource: class StockItemsRemainingsResource(resources.ModelResource): class Meta: model = models.StockItem fields = ('name', 'category') def __init__(self): super().__init__() for item in self.get_queryset(): stock_name = item.stock.name self.fields[f"quantity_{stock_name}"] = fields.Field( attribute="quantity", column_name=stock_name, widget=widgets.ForeignKeyWidget( models.Stock, "pk" ) ) I was trying to override the __init__ method but probably did it wrong.