Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set dict key as dynamic field name to add value m2m fields in Django
I want to set the m2m field name from the dictionary key dynamically so that I don't have to type each field name separately. Any help would be much appreciated. instance = ProductAttributes.objects.create(device_type=1, manufacturer=2, created_by=request.user) device_dict = { 'watch_series': WatchSeries.objects.get(series=mergedict['watch_series']), 'watch_size': WatchSize.objects.get(size=mergedict['watch_size']), 'color': Color.objects.get(id=mergedict['color']), 'band_color': BandColor.objects.get(color=mergedict['band_color']), 'watch_connectivity': 1 if mergedict['is_gps'] == True else 2 } This is how I'm trying to add m2m field name after instance for key, val in device_dict.items(): instance._meta.get_field(key).add(val) I'm getting this error: AttributeError: 'ManyToManyField' object has no attribute 'add' -
How to create Tree Survey in Django?
I need help You need to do a tree survey in jang Type : Question: Who do you work for? Answer options : Programmer, Welder If the user answers as a Programmer, they are asked questions about this profession If a welder answers, he is asked questions about this profession Well, and so on into the depths That is, the user's answers affect the next question But you also need to create a custom admin panel to add, edit and establish links between these issues I just can't figure out how to optimally configure the models so that the tree survey is normally implemented. Specifically, I do not understand how to store this connection, how to store it correctly and conveniently in models, and how to implement them so that quickly, beautifully and simply you can specify these links between questions and answers in the admin panel -
How can I automatically assign the current user as the author when creating a post?
How can I automatically assign the current user as the author when creating a post? forms: from django import forms from publication.models import Userpublication class PostForm(forms.ModelForm): content = forms.CharField(label='',widget=forms.Textarea(attrs={'class': 'content_toggle app-textarea', 'utofocus': 'true', 'maxlength': '250', 'placeholder': 'hello', 'required': True})) class Meta: model = Userpublication fields = ['content', 'author'] labels = { 'Content': False, } views: def create_post(request): if request.method == 'POST': form = PostForm(request.POST, initial={'author': request.user}) if form.is_valid(): form.save() return redirect('home') else: form = PostForm(initial={'author': request.user}) post_lists = Userpublication.objects.all() context = { 'form': form, 'post_lists': post_lists, } return render(request, 'twippie/home.html', context) enter image description here This is how it works. But as soon as I remove fields 'author' from the form, but 'content' remains, the following error appears: File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages django\db\backends\sqlite3\base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.IntegrityError: NOT NULL constraint failed: publication_userpubl ication.author_id the browser shows this error: IntegrityError at /feed/ NOT NULL constraint failed: publication_userpublication.author_id What could I have missed or overlooked? model if needed: from django.db import models from autoslug import AutoSlugField from django.urls import reverse from django.contrib.auth.models import User from django.conf import settings class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_published=1).order_by('-time_create') class Userpublication(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = AutoSlugField(max_length=255, unique=True, populate_from='content') content = models.TextField('', blank=True) … -
I am unable to use Django Filter for Related Foreignkey in Django model
I am unable to filter reverse Foreign key field in my filter. Here is My Main Model: class VendorService(models.Model): """ Class for creating vendor services table models. """ vendor_id = models.ForeignKey(CustomUser, null=False, blank=False, on_delete=models.CASCADE) service_id = models.ForeignKey(Service, null=False, blank=False, on_delete=models.CASCADE) business_name = models.TextField(null=True, blank=False) business_image = models.URLField(max_length=500, null=True, blank=False) working_since = models.TextField(null=True, blank=False) ... And Here is my second Model: class ServiceSubTypeDetail(models.Model): ''' Additional Service Details ''' title = models.CharField(max_length=255, null=True, blank=True) service_subtype = models.CharField(max_length=255, null=True, blank=True) service = models.ForeignKey(VendorService, related_name='subtypes', on_delete=models.CASCADE, null=True, blank=True) actual_price = models.FloatField(null=True, blank=True) ... My second model uses First Model as foreignkey And Here is my Filter Class using django-filter library: class ServiceFilter(filters.FilterSet): service_type = filters.CharFilter(field_name="service_id__service_type", lookup_expr='icontains') city = filters.CharFilter(field_name="city", lookup_expr='icontains') price = filters.RangeFilter(field_name="vendorpricing__discounted_price") subscription = filters.CharFilter(field_name="vendorplan__subscription_type", lookup_expr='iexact') property_type = filters.CharFilter(field_name="subtypes__title", lookup_expr='icontains') def __init__(self, *args, **kwargs): super(ServiceFilter, self).__init__(*args, **kwargs) # Dynamically add the price range filter based on the service_type service_type = self.data.get('service_type', None) if service_type == 'Venues': self.filters['price'] = filters.RangeFilter(field_name="venue_discounted_price_per_event") else: self.filters['price'] = filters.RangeFilter(field_name="vendorpricing__discounted_price") class Meta: model = VendorService fields = ['service_id__service_type', 'city', "vendorpricing__discounted_price", "venue_discounted_price_per_event", "subtypes__title"] all other filters are working properly, but property_type dosnt work at all. I tried using method as well. please help..!! -
Change style for filteredselectmultiple widget tooltip text
I have used help help-tooltip help-icon in that I want add bootstrap tooltip styles. But not able to do? For reference I have attached screenshot. Provide solution according to that.in following image that question mark shows tooltip text and i want add bootstrap tooltip style in that text . enter image description here Add bootstrap tooltip style for tooltip -
Django Media files is not displaying when debug=false on production in Render
I currently have two kind of files static files and media files.The static files contain my css,js and other static content. The media files contain stuff that the user uploads.The static folder is right next to the media folder.Now on my deployed machine. If I set the DEBUG = False my static files are presented just fine however my media content is never displayed `This my settings.py code were debug=false and included the code for the static but my media files is not displaying in the render hosting platform .I want to display my media files on production server when debug=False ` DEBUG = False ALLOWED_HOSTS = ["*"] This my static code but i get static files and it is displaying in the production .But the media files are not displaying in the production server is there any way to solve this problem STATIC_URL = '/static/' STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')] STATIC_ROOT=os.path.join(BASE_DIR,'assets') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") Im using Render hosting platform for the deployment of the application -
A p2p secure chat application need more ressources to establish the work
I want to do this so called p2p chat app project, and I need some clear guidance and ressources where I can find some good p2p documentation or courses so I can digest this notion, I'm not so familiar woth it even though I have some basic knowledge about it I hope u suggest some great ressources where I can find a p2p based book or documentation -
Referencing model in another model is displaying id and object instead of name. How can I fix this?
I have made two models. One of which references another. Here is my first model: Here is my second model.py. (I know it is weird). This is what I get. I have tried using: def __str__(self): return self.employee Abd I have tried using: def __str__(self): return self.employee.employee_name I am not sure what I am doing wrong or how to fix this. I have also set employee = models.ForeignKey(Employee, on_delete=CASCADE) to see if that would make a difference. I knew it wouldn't. >:( I honestly have never referenced another Model into another one before so I am a newbie at this. Any suggestions? Any help would be greatly appreciated. -
Django: Refresh captcha form
I have a registration form with multiple fields and captcha form. I'm new to django-simple-captcha, and I made a refresh button to only refresh the captcha alone. Is it possible to do that? How should I write the function? register.html <div><input type="text" name="studentId"></div> <div><input type="text" name="Name"></div> ... <div>{{ form.captcha }}</div> <button type="button" class="btn">Refresh</button> // refresh captcha <button type="submit" class="btn btn-primary">Submit</button> forms.py from captcha.fields import CaptchaField class MyForm(forms.Form): captcha = CaptchaField() views.py from .forms import MyForm def preRegistration(request): form = MyForm(request.POST) if request.method == 'GET': return render(request, 'registration_form.html', {"form": form}) if request.method == 'POST': studentId = request.POST.get('studentId') ... if form.is_valid(): Applicant.objects.create(studentID=studentID, ...) return render(request, 'login.html') else: messages.error(request, 'Wrong Captcha!') return render(request, 'registration.html', {"form": form}) def refreshCaptcha(): ... -
In container Podman with systemd cgroups v2, i get error: Error: runc create failed: unable to start container process: error during container init
In Django i'm using Podman as a subprocess, i'm trying to create a container to isolate a code that will be returned as a string. My system (ubuntu) uses systemd as its cgroups manager and is using cgroups v2 (cgroupVersion: v2), i.e. simply systemd with cgroups v2. I checked the configuration and I'm exactly using systemd with cgroups. I'm also using the latest updated version of Podman and have also tried uninstalling and updating. But when I open the app in Django, I get the error: Error: runc create failed: unable to start container process: error during container init: error setting cgroup config for procHooks process: openat2 /sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service/user .slice/libpod-a7fc0b085c40c19042d082.scope/cpu.max: no such file or directory: OCI runtime attempted to invoke a command that was not found Some of my code in Django is: podman_process = subprocess.Popen(['podman', 'run', #'--cgroup-manager=systemd', #'--cgroup-manager=cgroupfs', '-the', '--rm', '-to', 'stdin', '-to', 'stdout', '--user', 'nobody:users', '-m', '256m', '--cpus', '0.5', 'alpine'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) I've tried both using '--cgroup-manager=cgroupfs' and also '--cgroup-manager=systemd', but I still get the same error. How can I solve the problem? -
How would you use a website builder that operates with your Django backend?
I'm working on this app that basically manages users and projects for my company, and then potentially sell it to other companies wishing to do the same thing. I'm thinking that I'll use Django + Python in the backend, and I really want to use a website builder to design the UI. The reason for using a website builder is that I'd like to speed the development up a little bit. I'm newer to coding, so the HTML hurdle seems like it'll be a lot to manage. I'm good at designing websites with my background in design. I'm trying to avoid manual HTML entry since I'm already climbing a steep hill learning app structuring, Django and Python at the same time (not to mention JSON and whatever else I'll need). My question is how could I use a Wix website that has been built visually, with my Django backend? I'd use Django to process the information, sort, filter, etc. Then I'd use the Wix site to interact with the information. Any tools or tips would help. Like I said, I'm a beginner and the learning curve is huge. Thanks! I haven't really tried anything to be honest. I don't even … -
How do I serve specific and/or arbitrary static files from Django?
I'm building an extension to a SASS product. This extension requires: The / directory to contain index.html The / directory to contain config.json The / directory to contain customActivity.js The / directory to contain icon.png I'd like to keep my config.json and customActivity.js files in my projects static directory, and my icon.png file in the media directory. My index.html file should be via a template. So far, my urls.py file looks like: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] and my views.py looks like: from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def index(request): return HttpResponse("some stuff") // just an example How do write a url paths that will direct / to the index view, but /somefile.someextension to either the static or media directories? -
Cannot access local variable 'user' where it is not associated with a value
so, I'm trying to make a function in my django project that sends a confirmation key through email for the user so I tried to do this: views.py def createuser(request): form = MyUserCreationForm() if request.method == 'POST': form = MyUserCreationForm(request.POST) if form.is_valid(): return redirect('confirm-email') else: messages.error(request,'An error occured during your registration') context = {'form':form} return render(request, 'signup.html', context) def confirmemail(request): form = MyUserCreationForm() if request.method == 'POST': form = MyUserCreationForm(request.POST) page = 'confirm-email' subject = 'Confirm your email' # Erro from_email = 'adryanftaborda@gmail.com' email = request.user.email recipient_list = email return send_mail(subject, 'Use %s to confirm your email.' % request.user.confirmation_key, from_email, recipient_list) user.confirm_email(user.confirmation_key) if user.is_confirmed == True: user = form.save(commit=False) user.username = request.user.username.lower() user.save() login(request,user) return redirect('home') context = {'form':form} return render(request, 'emailconfirm.html', context) models.py from django.db import models from django.contrib.auth.models import AbstractUser from simple_email_confirmation.models import SimpleEmailConfirmationUserMixin class User(SimpleEmailConfirmationUserMixin, AbstractUser): name = models.CharField(max_length = 50) username = models.CharField(max_length = 50, null=True) email = models.EmailField(unique=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','username'] and I've got this error: UnboundLocalError at /confirm-email/ cannot access local variable 'user' where it is not associated with a value the error in this line: user.confirm_email(user.confirmation_key) I tried to add requests.user everywhere, but it didn't work. I have an … -
How do I configure a Django model against an agreggating postgres view?
Django 4.2.9, postgres 15.2 (server), Python 3.10 I have a view that does it's own aggregation and I want to map it into a Django Model. CREATE VIEW report_usage AS SELECT t.team_id, t.display_name, t.report_allowance", count(r.*) as "monthly_usage" FROM report r LEFT JOIN teams t ON t.team_id = r.team_id WHERE date_trunc('month', r.response_ts) = date_trunc('month', now()) GROUP BY t.team_id, t.display_name, report_allowance; This view works as promised; it counts the number of reports run by each team. Now that view is also used in other places so I want to simply incorporate it into a Django model for use in my app. So I built a Django Model around it: class ReportUsage(models.Model): class Meta: managed = False verbose_name_plural = 'Report Usage' db_table = 'report_usage' # Not really a key for this table.. just needed by django team_id = models.IntegerField(primary_key=True, db_column='team_id') display_name = models.CharField(db_column='display_name') report_allowance = models.IntegerField(db_column='report_allowance') report_usage = models.IntegerField(db_column='count') However It is not working: django.db.utils.ProgrammingError: column "report_usage.team_id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "report_usage"."team_id", "report_usage"."display_n... Which makes a total of zero sense to me. At a guess, Django saw the count() function and decided to take over. I have read everything I … -
Django - cPanel environment variable not working
While setting up a Django app in cPanel, I can assign environment variables. However, I am having trouble using them. For instance, I made an assignment as seen in the picture. But when I use it in my Django application as os.environ.get('EMAIL_PASSWORD_V'), It doesn't recognize the variable. How can i fix that? I know there are other methods to do this but if this method is can be used, I wonder how can it. Thank you already Django_Variable_in_cPanel -
Django DRF Viewset URL Reversing Issue - NoReverseMatch for 'orderitem-list
I'm encountering a perplexing issue while working with Django and the Django Rest Framework (DRF). Specifically, I have two viewsets, namely OrderViewSet and OrderItemViewSet, both registered with a DefaultRouter. The problem arises when attempting to perform URL reversing for the 'orderitem-list' endpoint, where I consistently encounter a NoReverseMatch error. Surprisingly, this issue is not present when reversing the URL for 'order-list'. urls.py `router = DefaultRouter() router.register(r"", OrderViewSet, basename="order") router.register(r"^(?P<order_id>\d+)/order-items", OrderItemViewSet, basename="orderitem") urlpatterns = [ path("", include(router.urls)), ]` test_orders.py `def test_create_order_for_anonymous_user(self, client, address): url = reverse("order-list") response = client.post(url, {}) assert response.status_code == 403 assert Order.objects.count() == 0` This test code works successfully `def test_create_order_item_for_anonymous_user(self, client, order): url = reverse("orderitem-list", kwargs={"order_id": order.id}) response = client.post(url, {}) assert response.status_code == 403 assert OrderItem.objects.count() == 0` The error message is: django.urls.exceptions.NoReverseMatch: Reverse for 'orderitem-list' with keyword arguments '{'order_id': 1}' not found. Any ideas on why this might be happening? The reverse for 'order-list' works without any issues. -
how to set CSRF token in nextjs for django
Noob in need. I'm building an app that takes an image on nextjs and send its to a django backend. I'm currently stuck on this error WARNING:django.security.csrf:Forbidden (CSRF cookie not set.) The problem is I'm not sure how to set the cookies in the header request. I'm especially confused about whether to do in on the nextjs frontend or nextjs backend. I have a page.tsx (/src/app/capture/page.tsx) file loaded on /capture route. (pastebin: https://pastebin.com/cceX0CEV ) When the picture is uploaded, it is sent to the nextjs route /api/capture route ( /src/app/api/capture/route.ts). (pastebin: https://pastebin.com/8M5ezzA2 ) You can see here I already have functionality to fetch the CSRF cookie from django and I'm trying to add it to the request header but that doesn't work. Here, the file is now sent to the django backend: localhost:8000 here's the relevant django backend function in my views.py (pastebin: https://pastebin.com/PPj9NR3k ) and the relevant settings in my settings.py (pastebin: https://pastebin.com/UVyMQvYR ) I came across this but it didn't change much (you can see parts of it in my route.ts) Please, any help here will be appreciated. How do I set the cookie in the header? (previous iteration of this question here. hoping to get better luck … -
How to debug memory leak on DigitalOcean App Platform
My Django application run perfectly fine on my local machine, memory usage fluctuate between 700MB and 800MB, but when I execute the exact same code on DigitalOcean App Platform the memory usage is constantly increasing until it reach 100%. Then the application reboot. What could cause the issue and how to find the root cause ? I have tried to isolate the problem with memory_profiler and the @profile decorator, but the memory increase isn't associated with any line of my code. I track memory usage like this : total = memory_usage()[0] logger.info(f"Memory used : {total} MiB") -
Nested transaction.atomic loops with locks
With a Django 5.0.2 and PostgreSQL 14 (Azure Database Flexible Server) setup, I have this piece of code which, basically, translates to: with transaction.atomic(): objects = ObjectModel.objects.all(): for object in objects: with transaction.atomic(): another_object = AnotherObjectModel.objects.select_for_update().get(id=1000) # ... I've been having quite a few crashes in my database and this has proven to be the point where the bottleneck happens. As it's legacy code (and forgive me the blame game) and I cannot trace any documentation or testimony as to why it was implemented like this, would anyone have a point of view of how this could or could not be a cause for the crash? Please forgive me if this is not too explicit or not compliant to the forum's rules, I'll be more than happy to try to elaborate. I have not tried anything so far, I'm afraid. -
How to create a user profile for; 'RelatedObjectDoesNotExist: User has no userprofile' in Django
I need to create agents for my leads but I'm facing a challenge. When I execute my code it works, but when I want to create an agent this error pop's up. leads.models.User.userprofile.RelatedObjectDoesNotExist: User has no userprofile This is my agents apps views.py from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import reverse from leads.models import Agent from .forms import AgentModelForm class AgentListView(LoginRequiredMixin, generic.ListView): template_name = "agents/agent_list.html" def get_queryset(self): return Agent.objects.all() class AgentCreateView(LoginRequiredMixin, generic.CreateView): template_name = "agents/agent_create.html" form_class = AgentModelForm def get_success_url(self): return reverse("agents:agent-list") def form_valid(self, form): agent = form.save(commit = False) agent.organisation = self.request.user.userprofile agent.save() return super(AgentCreateView, self).form_valid(form) The 3rd line from the bottom is what I believe brings the error message. This is the full error message Internal Server Error: /agents/create Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\base.py", line 143, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\edit.py", line 182, in post return super().post(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\edit.py", line 151, … -
CSS file not getting linked in Django project
I'm a beginner in the Django framework. I created a very simple page with one heading and tried to link the CSS with it. However, I'm not able to link it. I have seen tutorials also but no luck. [enter image descenter image description hereription here](https://i.stack.imgur.com/ZTr0c.png)enter image description here I was trying to just create a web page with some text on it -
How to create two postgres database when docker-compose up?
Dockerfile: FROM python:3.9 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get upgrade -y \ && apt-get install -y gcc gunicorn3 libcurl4-gnutls-dev librtmp-dev libnss3 libnss3-dev wget \ && apt-get clean \ && apt -f install -y WORKDIR /App COPY requirements.txt /App/ RUN pip install -r requirements.txt COPY . /App/ >! RUN pip install django~=4.1.1 RUN mkdir -p /App/data/db/ RUN chown -R 1000:1000 /App/data/db/ EXPOSE 7000 EXPOSE 8001 ` I have base-compose file that contain database image, here is file content: version: '3.3' networks: shared_network: driver: bridge services: testdb: image: postgres:latest volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_DB=develop_db - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - "5432:5432" networks: - shared_network volumes: postgres_data: Here is my docker-compose file: version: '3.3' include: - ./base-compose.yml services: test_develop: container_name: test_develop build: . command: python manage.py runserver 0.0.0.0:7000 ports: - "7000:7000" env_file: - ./environments/.env.develop depends_on: - testdb networks: - shared_network links: - testdb Here is my docker-compose-prod.yml file: version: '3.3' include: - ./base-compose.yml services: test_production: container_name: test_production build: . command: python manage.py runserver 0.0.0.0:8001 ports: - "8001:8001" env_file: - ./environments/.env.prod depends_on: - testdb networks: - shared_network links: - testdb when i run the docker-compose up --build it create develop_db but i want to create prod_db too. I try to create two … -
Code not working on IIS server but working on localhost - Exception Type: KeyError at / Exception Value: '_auth_user_backend'
I am struggling with the below error : Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'xx.middleware.LDAPAuthMiddleware', 'xx.middleware.UserLogMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware'] Traceback (most recent call last): File "C:\xx\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\xx\venv\Lib\site-packages\django\utils\deprecation.py", line 133, in __call__ response = self.process_request(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\xx\venv\Lib\site-packages\django\contrib\auth\middleware.py", line 71, in process_request if request.user.get_username() == self.clean_username(username, request): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\xx\venv\Lib\site-packages\django\contrib\auth\middleware.py", line 92, in clean_username backend_str = request.session[auth.BACKEND_SESSION_KEY] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\xx\venv\Lib\site-packages\django\contrib\sessions\backends\base.py", line 53, in __getitem__ return self._session[key] ^^^^^^^^^^^^^^^^^^ Exception Type: KeyError at / Exception Value: '_auth_user_backend' I don't really understand when this error is triggered and why. Working on localhost does not trigger the error but when trying to use the site on IIS it does trigger this error, so this is quite hard to debug. Below is my middleware : def get_client_user(self,request): username = request.META.get('REMOTE_USER') if username is None: username = request.META.get('HTTP_REMOTE_USER') if username is None: username = 'Anonymous' return username def __call__(self, request): auth = LDAPBackend() My_User_Test = self.get_client_user(request) My_User_ip = self.get_client_ip(request) username = My_User_Test.replace("MC-DOMAIN\\","") if not request.user.is_authenticated: print(username) user = auth.populate_user(username) request.user = user else: user = request.user context = {'metadata_user': username, 'request_user': My_User_Test, 'request_ip': My_User_ip,} if user is None: print("User not authenticated: ", username) return render(request, 'Not_Authorized.html',context) else: … -
Read the Docs compile failure
I want to compile the documentation of my Django project I made with Sphinx. Every things seems ok, I create the file with the command "make html", push to my github repository and finally connect Read the docs to this repository. I request the compilation which failed. I got this log that doesn't really help me to understand: Read the Docs build information Build id: 23529747 Project: python-p13 Version: latest Commit: None Date: 2024-02-22T16:16:57.891284Z State: finished Success: False [rtd-command-info] start-time: 2024-02-22T16:16:58.554108Z, end-time: 2024-02-22T16:17:00.943549Z, duration: 2, exit-code: 0 git clone --depth 1 https://github.com/th3x4v/Python_P13.git . Cloning into '.'... [rtd-command-info] start-time: 2024-02-22T16:17:00.980730Z, end-time: 2024-02-22T16:17:01.411216Z, duration: 0, exit-code: 0 git fetch origin --force --prune --prune-tags --depth 50 refs/heads/master:refs/remotes/origin/master [rtd-command-info] start-time: 2024-02-22T16:17:01.502170Z, end-time: 2024-02-22T16:17:02.569231Z, duration: 1, exit-code: 0 git checkout --force origin/master Note: switching to 'origin/master'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by switching back to a branch. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -c with the switch command. Example: git switch -c Or … -
Django / SendGrid - Password Reset - "The from address does not match a verified Sender Identity. "
I started integrating SendGrid into a django project. The integration seems to work, as when a user registers a welcome email is sent to the user with email@domain-name.com as the from_email However, if a user request a new password, this produces a 500 error: "The from address does not match a verified Sender Identity." The sender identify is obvioulsy verified because the other email signals work. Questionning SendGrid on the question, they say that the email is blocked because its coming from webmaster@localhost. Which I find a bit odd. I am confused, where in Django this default email address could be? Here is my current settings.py for email: EMAIL_FROM = "email@domain-name.com" EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.sendgrid.net" EMAIL_HOST_USER = "apikey EMAIL_HOST_PASSWORD = config('SENDGRID_API_KEY', default='') EMAIL_PORT = 587 EMAIL_USE_TLS = True I dont have a specific view setup for password change except the following: class PasswordsChangeView(PasswordChangeView): form_class = PasswordChangingForm success_url = reverse_lazy('home') and, just in case this is an example of of the signals.py that triggers the welcome email: @receiver(post_save, sender=UserProfile) def created_user_profile(sender, instance, created, **kwargs): if created: subject = "title" message = render_to_string("main/email/welcome_email.html",{ 'username':instance.user, 'email': instance.user.email, }) from_email = settings.EMAIL_FROM print(f'from_email - {from_email} ') to_email = [instance.user.email] print(f'to_email - {to_email} …