Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
All my fields are getting updated except the File Field
I am creating a django CRUD project. I am facing an issue where I am not able to update the File field. I am able to update the all the other fields except the File Field. Below is my models: class TestCase(models.Model): title = models.CharField(max_length=150) report_file = models.FileField(upload_to=user_directory_path,validators=[FileExtensionValidator(allowed_extensions=['xlsx'])]) date_posted = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, max_length=10, on_delete=models.CASCADE, null=True) increase_value = models.IntegerField(null=True, blank=True) total_test_cases = models.IntegerField(null=True, blank=True) category = models.CharField(max_length=10, choices=CATEGORY_CHOICES, null=True, blank=True) My form: class TestCasesForm(ModelForm): class Meta: model = TestCase fields = ['title', 'report_file','category'] and my update view: @login_required(login_url='my-login') def update_view(request, pk): testcase = get_object_or_404(TestCase, pk=pk, user=request.user) if request.method == 'POST': form = TestCasesForm(request.POST, request.FILES, instance=testcase) if form.is_valid(): form.save() return redirect('writer:my-testcases') else: form = TestCasesForm(instance=testcase) context = {'UpdateTestCaseForm': form} return render(request, 'writer/update-testcase.html', context) -
Namespace not solving NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name
I have this error and don't know exactly the source of it, if it's an error in the apps urls, or in the projects urls. The exact error is "NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name." The code is where the problem is: <li class="nav-item"> {% if not user.is_authenticated %} <a class="nav-link" href="{% url 'login' %}">Login</a> {% else %} <a class="nav-link" href="{% url 'logout' %}">Logout</a>` {% endif %} </li> Here is my urls: from django.contrib import admin from django.urls import path, include from . import views from django.contrib.auth import views as auth_views from .forms import * urlpatterns = [ path('', views.index, name="index"), path('admin/', admin.site.urls), path('register/', views.UserSignupView.as_view(), name="register"), path('login/', auth_views.LoginView.as_view(template_name="login.html", authentication_form=UserLoginForm)), path('logout/', views.logout_user, name="logout"), ] And my projects urls: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('templates.urls')), path('admin/', admin.site.urls), ] Disclaimer, I have tried adding the namespace, but this flags another issue, so wanted to see if there is any other issues with the code. I have tried to see if the problem is in the projects urls, but to no success. Have tried to see if it's a form problem, but the form has no … -
Getting default image when streaming a video onto the webpage through django
My moto:-* create a webpage which accepts a video file and once submitted through submit button, the video(in form of frames) will display within samepage in another div section. reason for displaying as frames is i need to process each frame. (Rendering frames onto webpage).* My django code:def gen(request): if request.method == 'POST': try: video_file = request.FILES["video"] if video_file: video_filename = "temp_video.mp4" video_filepath = os.path.join(settings.STATIC_ROOT, video_filename) with open(video_filepath, 'wb') as destination: for chunk in video_file.chunks(): destination.write(chunk) video_cap = cv2.VideoCapture(video_filepath) if not video_cap.isOpened(): print("Error: Could not open video file") return "Error in processing video." while True: ret, frame = video_cap.read() if not ret: break else: #cv2.imshow("output",frame) tried this too but not working. frame_bytes = frame.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n\r\n') else: print("no video file") except Exception as e: print("An error occurred:", e) return "An error occurred while processing the video." def process_video(request): return StreamingHttpResponse(gen(request),content_type='multipart/x-mixed-replace; boundary=frame') My javascript(in html file):-<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script> document.getElementById('uploadForm').addEventListener('submit', function (event) { event.preventDefault(); // Prevent default form submission behavior const formData = new FormData(this); fetch(this.action, { method: this.method, body: formData}) .then(response => { // Handle response // Define a function to handle each frame received function handleFrame(frameUrl) { // Create a new image … -
WebSocket Disconnect: No route found for path 'ws/chat_app/3wVCio/'
When I try to connect to handshake with my WebSocket, I'm getting the following error in Django terminal: python3.12/site-packages/channels/routing.py", line 134, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/chat_app/3wVCio/'. WebSocket DISCONNECT /ws/chat_app/3wVCio/ [192.168.0.11:58136] I found, that in previous Django versions, the problem was, that instead of path, for defining the urlpatterns in this case, it should be used url(). However, the url() is depricated and instead of it, the re_path should be used. Unfortunately it did not help me.. Here is the routing, I created - routing.py from django.urls import re_path from .consumers import ChatConsumer # The WebSocket URL pattern for chat rooms is defined by this code websocket_urlpatterns = [ re_path(r'chat_app/(?P<unique_id>\w+)/$', ChatConsumer.as_asgi()), ] This is the WebSocket consumer.py: import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from .models import Message from room_app.models import Room class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.unique_id = self.scope['url_route']['kwargs']['unique_id'] self.room_group_name = f'chat_{self.unique_id}' # Check if the room exists in the database if not await self.room_exists(): await self.close() return # Join room group self.channel_layer.group_add( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket def … -
No module named ‘application’` when deploying to AWS elastic beanstalk
I am trying to deploy a django project on elastic beanstalk, I have used this AWS official Doc for django deployment on EB: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html These are Steps i followed: eb init eb create put CNAME in ALLOWED_HOST eb deploy and when i try to see my website, i get ERROR: "502 Bad Gateway: nginx" So i checked web.stdout.log file and found this error: https://i.stack.imgur.com/iZzcG.png This is my django.config file (present in .ebextensions folder) This is my directory structure: This is my wsgi.py file: enter image description hereenter image description hereenter image description here I want to solve this error. I don't know what's the problem, and I really need someone to help me solve this error, Your help means a lot to me. if you need any additional information let me know. -
django-storage[s3]: using storage and upload_to field together on image field doesnt work
There are sevaral threads/blogs on how you can use django-storage library to upload files/images on different cloud platforms(in my case I'm concerned about only S3). I configured it by adding below settings in settings,py storages to INSTALLED_APPS, AWS settings AWS_ACCESS_KEY_ID = AWS_SECRET_ACCESS_KEY = AWS_STORAGE_BUCKET_NAME = AWS_S3_REGION_NAME = AWS_QUERYSTRING_AUTH = False STORAGES = { "default": { "BACKEND": "path.to.CustomStoragBackendsClass", }, "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage", }, } class CustomStoragBackendsClass(S3Boto3Storage): default_acl = 'public-read' Now in models, I'm trying to use this as below class MyModel(mdoel.Model): ... main_icon = models.ImageField( null=True, storage=CustomStoragBackendsClass(location="my_model/main_icons", uplaod_to=main_icon_upload_to_path, ) ... and here is the upload_to path function in the same model file def main_icon_upload_to_path(instance, filename): return f"{instance.pk}/{filename}" At first look all this looks fine but for some reason it's not working as expected. I'm still getting the path without instance id in it (basically it seems upload_to is not being used at all, only storage field is being used). My goal is to have a single bucket for all images/files in the app. and then in that bucket will have folders representing each models from where files have been uploaded. and with in model directory, I have another folder which represents the field name, and then id of that model … -
Python Admin Site with Through Parameter
I had the following Model class UserGroup(models.Model): name = models.CharField(max_length=255, unique=True) users = models.ManyToManyField(User, blank=True) def __str__(self): return self.name With my Admin.py below, The query set worked 100% (basically only showing users in the current group and users not in a group at all ) class UserGroupAdmin(admin.ModelAdmin): filter_horizontal = ('users',) def formfield_for_manytomany(self, db_field, request=None, **kwargs): if db_field.name == 'users': object_id = request.resolver_match.kwargs.get('object_id') kwargs['queryset'] = User.objects.filter( Q(usergroup=None) | Q(usergroup=object_id) ) return super().formfield_for_manytomany(db_field, request, **kwargs) admin.site.register(UserGroup, UserGroupAdmin) The output looked like the below Which was great but I changed my Model to use the Through parameter below. class UserGroup(models.Model): name = models.CharField(max_length=255, unique=True) users = models.ManyToManyField(User, blank=True, through='UserToUserGroup') def __str__(self): return self.name class UserToUserGroup(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) user_group = models.ForeignKey(UserGroup, on_delete=models.CASCADE) Now My admin site looks like the below. I am having a hard time getting the admin site to look same after my changes to the model. I am still getting use to working with the admin site. I tried some inlines but had no success. I do need to use the filter horizontal and have it look the same. -
filter city field (for each province) based on selected province field in django admin panel
class Province(models.Model): name = models.CharField( max_length=70, unique=True, null=True, blank=True,) def __str__(self): return self.name class City(models.Model): province = models.ForeignKey("election.Province", on_delete=models.CASCADE) name = models.CharField(max_length=70, unique=True, null=True, blank=True,) class Election(models.Model): province = models.ForeignKey("election.Province", on_delete=models.SET_NULL, null=True, blank=True,) city = models.ForeignKey("election.City", on_delete=models.SET_NULL, null=True, blank=True,) I have this models. in admin panel, when selecting a province I want to just see the cites that belonging to that province. I`m begginer ;) -
backend not responding with domain but responding with ip
I have setup 2 different servers for frontend and backend. frontend server is accessible with ip and the domain both. all api requests are being processed by backend long as it comes from the ip. but when i load the ui with domain name, the backend is not accepting requests. returns no response. I have already configured in my application, so this seems like some problem with some aws config.. please help. both are smallest aws ec2, frontend is nextjs backend is django -
Django Q2 - Setting Up A Basic Structure For Function Scheduling
I'm kind of new to using Django different then its basic scope. I scheduled a function that works every minute for trial purposes. I read the documentation many times it is still obscure for me that what is the right way of using the Django Q2 library for scheduling. Can you please provide a clarification for me. Note that, I'm using DjangoORM. In my attempt, I created schedule.py as below script and make it work somehow but I'm not sure what is the correct way to run 'setup_periodic_tasks'. Furthermore, earlier tasks that I run are still showing up everytime I run qcluster despite I deleted them from the Tasks object, so how can I delete them for good? def schedule_price_list_status(): print('PRICE LIST SCHEDULED') def setup_periodic_tasks(**kwargs): print('SETUP TASKS') schedule('my_app.schedules.schedule_price_list_status', schedule_type='I', repeats=2, minutes=1) setup_periodic_tasks() -
Parsing Excel File Raises "No such keys(s): 'io.excel.zip.reader'" Error
I'm attempting to parse an file type 'docx' in my Django application using pandas, but I'm encountering the error "No such keys(s): 'io.excel.zip.reader'". It seems like there's an issue with how the file is being read or with the file format itself. I've checked that the file is indeed an Excel file with the .xlsx extension then its working fine but when i m adding elif statement for file type 'docx' then i got that error. Can someone help me understand what might be causing this error and how to resolve it? Below is a snippet of the code I'm using: import pandas as pd import json from docx import Document if request.method == 'POST': form = UserPermissionForm(request.POST, request.FILES) if form.is_valid(): upload_template_instance = form.save() template_file = upload_template_instance.template_master # Check file extension to determine its type if template_file.name.endswith('.xlsx'): # Parse the Excel file using Pandas df = pd.read_excel(template_file) df.fillna('', inplace=True) df.columns = ["" if 'Unnamed' in str(col) else col for col in df.columns] columns = df.columns.tolist() data = df.values.tolist() elif template_file.name.endswith('.docx'): # Parse the Word document using python-docx doc = Document(template_file) data = [] for paragraph in doc.paragraphs: # Extract text from each paragraph text = paragraph.text # Split text into … -
Django Mysql Database Configuration and Security
Is there a way to access a MySQL database from Django without explicitly providing credentials such as USERNAME, DATABASE NAME, and PASSWORD? I've explored methods like using dotenv or storing credentials in separate files, but I'm interested in alternatives. Are there approaches such as utilising Unix sockets or other methods to achieve this? Could someone provide an example of how to implement such a solution? -
microsoft sso is not working in social-auth-app-django=5.4.0 in Django
We have used the social-auth-app-django=5.4.0 package for sso both Microsoft and google. The Google SSo is working properly but Microsoft SSO is not working. It shows the below error while trying to SSO. Backend not found Request Method: GET Request URL: http://0.0.0.0:9090/login/microsoft-oauth2/ Raised by: social_django.views.auth Using the URLconf defined in jenkins_mail.urls, Django tried these URL patterns, in this order: app/ [name='home'] admin/ login/<str:backend>/ [name='begin'] The current path, login/microsoft-oauth2/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.``` -
Python: Compare date and bulk update some fields
I created a refresh function for my Event Module, where if the Event date already passed, it will bulk update the status to 0. models.py class Events(models.Model): id = models.AutoField(db_column='id', primary_key=True) title = models.CharField(max_length=45, blank=True, null=True) venue = models.CharField(max_length=45, blank=True, null=True) date = models.DateTimeField(max_length=45, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) image = models.ImageField(upload_to=eventpath, blank=True, null=True) manager = models.CharField(max_length=100, blank=True, null=True) attendees = models.CharField(max_length=100, blank=True, null=True) date_posted = models.DateTimeField(max_length=45, blank=True, null=True) status = models.BooleanField(default=1) This is how I add an event. def uploadEvent(request): if request.method == "POST": item = Events() item.title = request.POST.get('title') item.venue = request.POST.get('venue') date = request.POST.get('date') date_object = datetime.datetime.strptime(date, '%a %b %d %Y %I:%M %p') item.date = date_object item.manager = request.POST.get('manager') item.attendees = request.POST.get('attendees') item.description = request.POST.get('description') date_posted = datetime.datetime.strptime(date, '%a %b %d %Y %I:%M %p') item.date_posted = date_posted if len(request.FILES) != 0: item.image = request.FILES['image'] item.save() return redirect('/amsai/events/') return render(request, 'admin/events_add.html') And this is how I want to update all events. I converted the obj.date to date() def refreshEvent(request): events = Events.objects.all() status = 0 date = datetime.datetime.today().date() if events: for obj in events: if obj.date.date() < date: Events.objects.filter(*****).update(status=status) return redirect('/amsai/events/') The problem is how can I filter those passed dates? I don't know what to … -
Django - how do I update the database with an expression of a field?
We are using Django for our website, and I want to remove personal information from one of the databases. For example I want to change email addresses to their id + "@example.com". I can do it with Python: for e in UserEmailAddress.objects.all(): e.email="{}@example.com".format(e.id) e.save() But it takes a long time if I have many users. Is there a way to do it with UserEmailAddress.objects.all().update(...) with one command that will do the same thing? I tried to use the F class but it didn't work, I probably didn't use it correctly. I also want to filter and exclude by these expressions - for example, query all users except users where their e.email=="{}@example.com".format(e.id). I tried both queries: from django.db.models import F el = UserEmailAddress.objects.all().filter(email="{}@example.com".format(F('id'))) print(len(el)) el = UserEmailAddress.objects.all().exclude(email="{}@example.com".format(F('id'))) print(len(el)) Both of them return incorrect results (not what I expected). -
Problems with Django Channels and signals
I have Vue script that retrieve notifications from Django and should display and update the notification count in a badge. I use Django channels, the Django version is 4.2.8, channels version 4, uvicorn 0.26 and websockets 12.0. To update the notification count I use a Django signal so when a new notification is added from the admin or another source, the post_save event gets triggered and the method update_notification_count in consumers.py should be called. Everything works fine from the browser, but when I add a new notification from the Django admin, the frontend does not get updated, that is, the update_notification_count is not called even if the event post_save gets triggered. Here is the code. First my config: # settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', 'CONFIG': { 'capacity': 1000, 'expiry': 60, }, } } Now asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from notifapi.routing import websocket_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproj.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter(websocket_urlpatterns), }) The signals.py file is coded that way from django.dispatch import receiver from django.db.models.signals import post_save from channels.layers import get_channel_layer from asgiref.sync import async_to_sync from .models import NotifyModel as Notification from .consumers import NotificationConsumer @receiver(post_save, sender=Notification) def notification_created(sender, … -
Is Django (especially Django Rest Framework) really synchronous?
I know some concepts that Django (DRF) is synchronous and it has some workers, but I know little about this. I tried to verify this and created this view at the address http://localhost:8000/my-view/: def my_view(request): # Simulate some time-consuming task time.sleep(10) return HttpResponse("Response after 10 seconds") I proceeded to open 7 terminals and execute the same command on each of them within a range of 1-2 seconds (almost simultaneously): curl http://localhost:8000/my-view/ -H 'Content-Type: application/json' --> and the result was that in each terminal I received response in 10-12 seconds. Here is the question, if Django is synchronous so why it did not take 70 seconds to execute these requests one by one? The only explanation I can think of is that it uses multithreading. -
Load Large JSON File in Django
I try to load large json file (250mb) and when i open in django and use len() the size is 1060000, but after i use for loop and save it to database, the total data is always changing sometimes 1052000 or 1057000. How could this happen ? -
django oscar order change page keeps loading. getting 502 Bad Gateway
I am getting 502 Bad Gateway. I am using a django oscar application. its running on docker. i also have nginx configured in a container. All the other pages work, except order change page. http://localhost:888/admin/order/order/60/change/ When i looked into gunicorn logs, it is showing [CRITICAL] WORKER TIMEOUT. Maybe a memory leak or an infinite loop? But i dont see any stack trace, or where it is getting this error. How do i debug this? Its a faily large application. Any help is appreciated. version: '3' services: web: restart: unless-stopped build: dockerfile: local.Dockerfile context: ./src working_dir: /opt/supplyme_core command: | sh -c " while ! timeout 1 bash -c 'cat < /dev/null > /dev/tcp/db/5432'; do sleep 1; done while ! timeout 1 bash -c 'cat < /dev/null > /dev/tcp/e_search/9200'; do sleep 1; done python manage.py collectstatic --noinput /usr/local/bin/gunicorn project.wsgi:application --timeout 300 -w 2 -b 0.0.0.0:888 & \ python service_runner.py api.web.service -c /opt/supplyme_core/api/conf/local_config.yml" ports: - "0.0.0.0:2220:22" volumes: - ./src/supplyme_core:/opt/supplyme_core - ./.pycharm_helpers:/root/.pycharm_helpers - public:/opt/public - ./src/scripts/local/freeze.py:/opt/freeze.py:ro - ./.ssh:/root/.ssh db: restart: unless-stopped build: context: ./pg/x64 environment: POSTGRES_PASSWORD: postgres expose: - "5432" ports: - "0.0.0.0:5432:5432" e_search: restart: unless-stopped build: ./elastic environment: - discovery.type=single-node - xpack.security.enabled=false - xpack.monitoring.enabled=false - xpack.watcher.enabled=false expose: - "9200" kibana: image: kibana:7.14.1 expose: … -
What is the best way to run a python file on a front end?
I am developing a medical app that uses sci-kit for machine learning. I have developed a Python file for the logic of my app. It takes input a couple of times from the command line and then uses the responses to predict what disease a user is suffering from. The problem I'm having is how to put it on a front-end so that anyone can use it. I have tried using Django, ReactJS, Flask, and PyScript so far, and the main problem I'm facing is that all tutorials are showing me how to support scripts in Python with only one input. My app predicts what symptoms the user might be suffering from next, and so needs to pass the next question to the front end while remembering what state it is in, requiring multiple inputs. I am looking for any frameworks, api's or general info that might be useful in my situation. Any help would be appreciated. -
django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied
while trying to connect my postgresql database with django i'm facing this error django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied this is my settings.py `DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_USER_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), } }` this is my .env file `export DB_NAME=demo export DB_USER=postgres export DB_USER_PASSWORD=12345678 export DB_HOST=localhost` -
Class() got an unexpected keyword argument 'unique_id', when trying to connect to a WebSocket
I'm trying to connect to my Django WebSocket, but I keep getting the following exception: TypeError: ChatConsumer() got an unexpected keyword argument 'unique_id' "GET /ws/chat_app/sjfAmH/ HTTP/1.1" 500 64965 I'm basically following a tutorial and that is how the guy does it in there. I have also looked at other implementations and I find it as the same way.. I'm new at using WebSockets, I would appreciate any kind of help. Thanks in advance! This is my ChatConsumer class: # chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from .models import Message from room_app.models import Room class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.unique_id = self.scope['url_route']['kwargs']['unique_id'] self.room_group_name = f'chat_{self.unique_id}' # Check if the room exists in the database if not await self.room_exists(): await self.close() return # Join room group self.channel_layer.group_add( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Save message to database Message.objects.create( room=self.unique_id, user=self.scope['user'], content=message ) # Send message to room group self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': self.scope['user'].username } ) # Receive message from room group def chat_message(self, event): message = event['message'] username = … -
Django PasswordResetView not Sending Email (Django 5, Gmail SMTP)
Problem: I'm facing an issue where the PasswordResetView in my Django project is not sending emails. I have tested my email configurations using the Django shell and a custom email route, and emails are sent successfully. However, the default PasswordResetView and the password reset page in the Django administration panel do not send emails. Environment: Django 5 Gmail SMTP Using a custom user model Email Settings (settings.py): EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD") DEFAULT_FROM_EMAIL = os.environ.get("EMAIL_HOST_USER") SERVER_EMAIL = os.environ.get("EMAIL_HOST_USER") # Custom User Model AUTH_USER_MODEL = "accounts.CustomUser" Views and URLs: I have tried using a custom view (custom_password_reset) and the default PasswordResetView, but both do not send emails. # views.py def custom_password_reset(request): return auth_views.PasswordResetView.as_view( template_name="accounts/password-reset.html", success_url=reverse_lazy("accounts:password-reset-done"), extra_email_context={"request": request}, )(request) # urls.py path("password-reset/", views.custom_password_reset, name="password-reset"), Additional Information: I have tested sending emails from the Django shell, and it works. I have allowed less-secure app access for my Gmail account. I appreciate any insights or suggestions on resolving this issue. Thank you! -
Unwanted whitespace in Django urls
I have an unwanted whitespace in my url pattern and I think this is making trouble when I try to handshake my Flutter app with my Django backend. I know there are similar questions in answered on this, but I could not find where this comes from or how to fix it.. These are my URL patterns and when I try to handshake with the WebSocket, I', getting the following error in Django terminal: Not Found: /ws/chat_app/sjfAmH "GET /ws/chat_app/sjfAmH HTTP/1.1" 404 4349 Those are my URL patterns I have an Django app called chat_app, where I have defined my WebSocket consumer class. Then I added the routing, pointing at that consumers class in my routing.py file: from django.urls import re_path from .consumers import ChatConsumer # The WebSocket URL pattern for chat rooms is defined by this code websocket_urlpatterns = [ re_path(r'chat_app/(?P<unique_id>\w+)/$', ChatConsumer.as_asgi()), ] Also, I have added the chat_app into settings.py installed apps and defined the URL path in my Django project urls.py: from django.contrib import admin from django.urls import include, path from chat_app.routing import websocket_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), ..., path('ws/', include(websocket_urlpatterns)), ] -
Customize a delete selected confirmation page in the Django admin site
I need to show an additional alarm message in the delete selected confirmation page. The message should not appear always. It shoud appear depending on certain conditions. I copied the delete_selected_confirmation.html template from the django/contrib/admin/templates/admin directory. I can now add an additional alarm message. But the message should appear depending on certain conditions. Which function inside class MyModelAdmin(admin.ModelAdmin) should I use? E.g., to set context for the delete_confirmation.html template I use def render_delete_form(self, request, context). Which function should I use for the delete_selected_confirmation.html template?