Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
email login: authentication function doesn't work
def EmailLoginVerify(request): if request.method == 'POST': if 'token' in request.POST: try: submitted_token = int(request.POST['token']) except ValueError: return HttpResponse('Invalid token format', status=400) if submitted_token == request.session.get('login_token'): email = request.session.get('email') try: target = MyUser.objects.get(email=email) print('user is', target.username, 'and password is', target.password) #export: #>>>>>>>user is maziar and password is pbkdf2_sha256$720000$CY5sjiqAL1yScKzGhzYBp9$2tUx8ScBbbuZlj+u0YfMxwTIRfz5Vfmv+58piWCAjKM= except MyUser.DoesNotExist: return HttpResponse('User Not Found', status=404) user = authenticate(request, username=target.username, password=target.password) print(user) #export: #>>>>> None if user is not None: login(request, user) return HttpResponse('good') else: return HttpResponse('Authentication failed', status=401) else: return HttpResponse('Invalid token', status=403) else: return HttpResponse('Token not provided', status=400) else: return render(request, 'login_verify.html') in the end it return 'Authrntication Failed' this code get an email from the user if a user with that email exists it send a code to the email and if user enter the correct code it should authenticate the user and log it in but it return 'Authentication Failed' enter image description here -
django.db.utils.NotSupportedError: (1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'") in Django
I am building a Django application and trying to implement pagination on a large dataset for a report. When querying the database, I encounter the error: django.db.utils.NotSupportedError: (1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'"). I'm using MySQL as the database backend. order_queryset = ProformaHeader.objects.filter(process_this_order=True, status=ACTIVE) page_obj = pagination(request, order_queryset.order_, per_page=10) order_queryset = page_obj.object_list podetails = PODetail.objects.filter(proforma__in=order_queryset, po_header__is_vconfirmed=True, status=ACTIVE).select_related('proforma_detail') podetail_map = {p.proforma_detail_id: p for p in podetails} # I encounter the error this line Error occurs on this line: podetail_map = {p.proforma_detail_id: p for p in podetails} # I encounter the error this line The error is raised when attempting to create a dictionary mapping proforma_detail_id to the corresponding podetail object. It seems to be related to the combination of LIMIT and IN in the query generated by Django when retrieving the podetails. Expected Outcome: I expected this line to build a dictionary mapping proforma_detail_id to podetail without triggering an error, allowing me to reference the podetail object for each proforma_detail in the subsequent processing loop. -
Get Client IP address in Django from nginx proxy
I have the following setup to run my Django server and I want to get a client IP address in Django server but it is giving me wrong IP address Nginx proxy conf events { worker_connections 1024; } http { log_format custom_format '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /first_access.log custom_format; client_max_body_size 50M; server_tokens off; upstream backend { server backend:8000; } server { listen 80 default_server; server_name _; return 301 https://$host$request_uri; } server { listen 443; server_name www.$ENV-api.in $ENV-api.in; ssl on; ssl_certificate /certs/server.crt; ssl_certificate_key /certs/server.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256'; location / { 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_pass http://backend; add_header X-Frame-Options "DENY" always; add_header Content-Security-Policy "frame-ancestors 'self';" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "no-referrer" always; } } } This above conf forward request to following nginx conf vents { worker_connections 1024; } http { log_format custom_format '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /second_access.log custom_format; client_max_body_size 50M; server { include "/etc/nginx/mime.types"; listen 8000; server_name django; gzip on; gzip_min_length 1000; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript; … -
How to Enhance Fingerprint Images Without Blurring Ridges? i am using django
How to Enhance Fingerprint Images Without Blurring Ridges? i am using django. I'm currently working on a fingerprint enhancement project using OpenCV, and while my code is producing results, the ridges in the fingerprint images are coming out blurred. here is my code import cv2 import numpy as np import math import fingerprint_enhancer # Ensure this module is available from django.shortcuts import render from django.core.files.base import ContentFile from .forms import HandFingerForm from .models import ThumbImage import base64 MAX_IMAGES = 10 def remove_green(img): empty_img = np.zeros_like(img) RED, GREEN, BLUE = (2, 1, 0) reds = img[:, :, RED] greens = img[:, :, GREEN] blues = img[:, :, BLUE] # Create a mask for the areas to keep tmpMask = (greens < 35) | (reds > greens) | (blues > greens) img[tmpMask == 0] = (0, 0, 0) # Remove background from original picture empty_img[tmpMask] = (255, 255, 255) # Mask with finger in white return img, empty_img def detect_nail(gray_mask_finger): # Find contours in the mask image contours, _ = cv2.findContours(gray_mask_finger, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: # Only consider large enough contours as nails if cv2.contourArea(contour) > 100: # Adjust this threshold as needed x, y, w, h = cv2.boundingRect(contour) # … -
Open Local Outlook Client with Attachments from Backend Using Frontend File Selection
I'm working on a web application where users can select files in the frontend, and those files are fetched from the backend. After selecting the files, I want the user's local Outlook client to open with a pre-drafted email that includes the selected attachments, allowing the user to review and send the email manually. Here’s what I’m trying to achieve: Scenario: The user selects files in the frontend. After clicking the "Send Mail" button, the local Outlook client should open with a new email, including the files (fetched from the backend) attached. Requirements: The email should be opened in the user's local Outlook client before sending (instead of being sent programmatically). Attachments should be dynamically fetched from the backend based on the user’s selection in the frontend. I am aware of how to send emails programmatically using the Microsoft Graph API, but I need a solution that opens the local Outlook client instead. I’m considering whether Outlook add-ins could help, but I haven't figured out how to pass attachments from the backend. -
401, Auth error from APNS or Web Push Service using FCM using firebase_admin
i have APNS device ID, but i got this error from when sending message def send_push_notification_legacy(device_tokens, title, body): service_account_file = os.getcwd() + '/show-coach-firebase-adminsdk-rpuoz- b40c95a3c2.json' credentials = service_account.Credentials.from_service_account_file( service_account_file, scopes=["https://www.googleapis.com/auth/firebase.messaging"] ) # Obtain an OAuth 2.0 token credentials.refresh(Request()) access_token = credentials.token url = 'https://fcm.googleapis.com/v1/projects/show-coach/messages:send' headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json', } payload = { "message": { "token": device_tokens[0], "notification": { "title": "Breaking News", "body": "New news story available." }, } } response = requests.post(url, json=payload, headers=headers) print(response.status_code, response.json()) ERROR Details { "error" : { "code" : 401, "message" : "Auth error from APNS or Web Push Service", "status" : "UNAUTHENTICATED", "details" : [ { "@type" : "type.googleapis.com/google.firebase.fcm.v1.FcmError", "errorCode" : "THIRD_PARTY_AUTH_ERROR" }, { "@type" : "type.googleapis.com/google.firebase.fcm.v1.ApnsError" } ] } } -
How to connect custom storage to django
I am writing a custom storage module to use a remote seafile-server as storage for a django (django-cms) installation. File seafile.py is located in the project-folder: The storage class has been tested with jupyter notebook and is working. The problem: I am failing to connect my storage to django (local, development-server), it is still saving pictures local in the media-folder and not using my storage at all. In settings.py from .seafile import MyStorage ... Things I have tried: DEFAULT_FILE_STORAGE = "MyStorage" DEFAULT_FILE_STORAGE = "seafile.MyStorage" DEFAULT_FILE_STORAGE = MyStorage DEFAULT_FILE_STORAGE = MyStorage() For sure I have seen and tried the suggested solution (https://docs.djangoproject.com/en/5.1/howto/custom-file-storage/#use-your-custom-storage-engine) but failed too. What am I missing? Thank you in advance! -
How to use custom headers for passing session_id and csrf_token in Django with database-backed sessions?
I'm using Django with a database-backed session storage, and as a result, the session_id is stored in cookies. However, we're using a Caddy server that removes cookies from the request headers. I need to: Pass the session_id and csrf_token via custom headers (instead of cookies). Use these custom headers for session validation and CSRF protection in Django. Additionally, I am storing values in the session that are used to validate the request and fetch data from the session during API calls. Is it possible to configure Django to accept and validate these custom headers (session_id and csrf_token) rather than reading them from cookies? If so, how can this be achieved? Any advice or code examples would be much appreciated. Attempting to include a custom header to retrieve the session ID. -
Error while migration after installation of rest_framework_api_key
I am trying to use this library. But I am getting below error while trying to run python manage.py migrate command. Operations to perform: Apply all migrations: admin, auth, contenttypes, rest_framework_api_key, sessions Running migrations: Applying rest_framework_api_key.0001_initial... OK Applying rest_framework_api_key.0002_auto_20190529_2243...Traceback (most recent call last): File "/home/foysal/.local/lib/python3.10/site-packages/django/db/models/options.py", line 676, in get_field return self.fields_map[field_name] KeyError: 'revoked' During handling of the above exception, another exception occurred: And File "/home/foysal/.local/lib/python3.10/site-packages/django/db/models/options.py", line 678, in get_field raise FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: APIKey has no field named 'revoked' -
GET request from the Database wash away the localStorage
I am currently building "To Do" web app, using ReactJS as Frontend and Django as Backend, and use axios to fetch requests. I want a feature into my app that stores the "ToDo tasks" locally as the user updates them, and not lose it whenever the browser got refreshed or accidentally got exited. I am using hooks and useEffect to store data locally. Whenever the browser is refreshed, the local data are washed by the database. This is snippet of my code. OR you can review the code here const [taskEdits, setTaskEdits] = useState({}); useEffect(() => { const storedEdits = JSON.parse(localStorage.getItem("taskEdits")) || {}; axios .get("/tasks/") .then((res) => { const fetchedTasks = res.data; const mergedTasks = fetchedTasks.map((task) => { if (storedEdits[task.id]) { return { ...task, title: storedEdits[task.id] }; } return task; }); setTasks(mergedTasks); }) .catch((err) => console.error("Error fetching tasks:", err)); }, []); useEffect(() => { localStorage.setItem("taskEdits", JSON.stringify(taskEdits)); }, [taskEdits]); -
Running daphne in Docker without supervisor
Currently, I'm running daphne using supervisor. This is my supervisor config: [supervisord] user = root nodaemon = true [fcgi-program:daphne] socket=tcp://api:9000 directory=/home/docker/api ommand=./.docker/services/api/files/startup-operations.sh && daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --proxy-headers main.asgi:application numprocs=2 process_name=asgi%(process_num)d autostart=true autorestart=false stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 redirect_stderr=true killasgroup=true startsecs=0 exitcodes=0 Here, the channels docs give exactly one example, and it's using supervisor: https://channels.readthedocs.io/en/latest/deploying.html However, I have read this: https://advancedweb.hu/supervisor-with-docker-lessons-learned/ ...which advocates for not using supervisor in docker, and I would agree with the article. One problem with using supervisor that the article doesn't discuss is that I have an in-memory database that I need to be available for the main application. The above config file is just one program that runs a startup-operations.sh script, but before, it used to be two programs: One program loaded the data into memory, and the other program ran the main application. Of course, I could load that data into memory in startup-operations.sh and be done with it, but that doesn't remove supervisor from my image. It seems that if I'm just running one series of commands, I should be able to not use supervisor in my image. This resulted in the first program's memory not being available to the main application. I also had … -
Submit button doesn't refresh page and send POST request
I'm doing registration on Django. I made a form, added a button that should refresh the page and send a POST request. But the button does not update the page and does not send the request. I doesn't have any scripts on JavaScript. My views.py code: `from django.shortcuts import render, redirect from .models import User from .forms import UserForm from django.views import View def index(request): return render(request, 'index.html') def inn(request): return render(request, 'in.html') class PostCreate(View): def up(self, request): form=UserForm(request.POST) if form.is_valid(): form.save() return redirect('home') def down(request): return render(request, 'up.html')` My forms.py code: `from .models import User from django.forms import ModelForm class UserForm(ModelForm): class Meta: model=User fields=['NickName', 'Email', 'Password']` And HTML: HTML I'm tried to search any information on internet, but I'm found only about event.preventDefault() and type='button'. But I doesn't have any scripts and my type is 'submit' -
Modelformset_factory including an empty list object as part of the management_form data displayed on screen
When rendering a formset created using modelformset_factory I am experiencing differing results between the local running instance of my application compared to the version running on my server. On both versions the application the files below are included the following: forms.py class NewCourseHoleForm(ModelForm): class Meta: model = CourseHole fields = [ 'hole_number', 'hole_name', 'par', 'stroke_index', 'length', ] def __init__(self, *args, **kwargs): super(NewCourseHoleForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.form_show_errors = True self.helper.form_show_labels = False self.helper.form_class = 'form-inline' self.helper.use_custom_control = True self.helper.layout = Layout( Div( Div( Div(Field('hole_name', css_class='text-center'), css_class="col-3"), Div( Field('hole_number', css_class='d-none'), css_class="d-none"), Div(Field('length', min=50, max=800), css_class="col-3"), Div(Field('par', min=3, max=5), css_class="col-3"), Div(Field('stroke_index', min=1, max=18), css_class="col-3"), css_class='row', ), css_class='col-12' ), ) hole_formset = modelformset_factory( CourseHole, form=NewCourseHoleForm, min_num=18, max_num=18, # validate_max=True # extra=18, # can_delete=False, ) views.py class CourseDetailView(LoginRequiredMixin, DetailView): login_url = '/login/' redirect_field_name = 'redirect_to' model = Course slug_field = 'uuid' slug_url_kwarg = 'uuid' template_name = 'courses/course_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) course = Course.objects.filter( uuid=self.kwargs.get('uuid')).first() context['title'] = f'{course.name} - Detail' teebox_check = CourseTeeBox.objects.filter( course=course).order_by('-course_length') context['teeboxes'] = teebox_check context['teeboxForm'] = f.NewCourseTeeBoxForm( prefix='teebox', course=course) holes = [{'hole_number': n, 'hole_name': f'Hole {n}'} for n in range(1,19)] context['holes_formset'] = f.hole_formset( queryset=CourseHole.objects.none(), prefix='holes', initial=holes) return context def get_queryset(self): queryset = super(CourseDetailView, self).get_queryset() return … -
How to change/filter option list in TreeNodeChoiceField
How to change the option/choice list of conto field, based on value gruppo_id? conto is a ForeignKey to model.ContoCOGE(MPTTModel). For each gruppo there is a tree, which develops to a certain depth. How to filter among all the tree roots and, in TreeNodeChoiceField, list only those with a group_id? In debug, formfield_for_foreignkey(self, db_field, request, **kwargs) overriden returns the correct tree. But the browser renders the page with the select field with all the trees. #model.py from mptt.models import MPTTModel, TreeForeignKey from multigroup.models import Gruppo class ContoCOGE (MPTTModel): gruppo = models.ForeignKey(Gruppo, on_delete=models.CASCADE,related_name='contoCOCGE_gruppo') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class PncGen (models.Model): gruppo = models.ForeignKey(Gruppo, on_delete=models.CASCADE) #other stuff class PncRighe (models.Model): gruppo = models.ForeignKey(Gruppo, on_delete=models.CASCADE) idPnc = models.ForeignKey(PncGen,on_delete=models.CASCADE) #puntatore alla testata conto = models.ForeignKey(ContoCOGE,on_delete=models.CASCADE,blank=True, null=True) #other stuff #admin.py from django_mptt_admin.admin import DjangoMpttAdmin class PncRigheInline(admin.TabularInline): model = PncRighe autocomplete_fields = ['partitarioRiga','conto'] extra = 1 def filter_tree_queryset(self, queryset,request): qs = queryset.filter(gruppo_id=int(request.session['gruppo_utente'])) return qs def get_changeform_initial_data(self, request): return {'gruppo': int(request.session['gruppo_utente'])} def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'gruppo' or db_field.name == 'idRiga' or db_field.name == 'idPnc': kwargs['widget'] = forms.HiddenInput() if db_field.name == 'conto': db = kwargs.get("using") qs = self.get_field_queryset(db, db_field, request) kwargs['queryset']=qs.filter(gruppo_id = request.session['gruppo_utente'] ) @admin.register(PncGen) class PncGenAdmin(admin.ModelAdmin): #... inlines = (PncRigheInline,) -
I do not receive information from the template
My footer doesn’t use any view I need to get information to save it I used parcel rendering package to render but I don’t get any information to save it even if it’s a small tip I can find it views code: def footernews(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return render(request, 'includes/footer.html', {'myformmews': form}) else: raise ValidationError('sorry infomations dont save...') else: form = ContactForm() return render(request,'includes/footer.html',{'myformmews':form}) models code: from django.db import models class MassageNewsFoot(models.Model): email=models.EmailField(max_length=32) date=models.DateField(auto_now_add=True) def __str__(self): return f'email: {self.email}---date: {self.date}' forms code: from django import forms from home_app.models import MassageNewsFoot from django.core.exceptions import ValidationError class ContactForm(forms.ModelForm): class Meta: model = MassageNewsFoot fields = '__all__' #style form footer in widget widgets ={ 'email': forms.TextInput(attrs={'class':'form-control bordered bottom-only' ,'placeholder':'enter your email'}), } urls code: from django.urls import path from . import views app_name = 'home_app' urlpatterns = [ path("", views.Homepage.as_view(), name='home'), path("footer", views.footernews, name='footerrenderded'), ] template code: <form action="" method="post"> {% csrf_token %} <div class="subscribe-form"> <div class="head"> news this site </div> <div class="input-wrap"> {{ myformmews.email }} <button class="btn btn-primary" type="submit"> <span class="outer-wrap"> <span data-text="share"> share </span> </span> </button> </div> </form> And finally I gave it to template home: {% extends 'base.html' %} {% load static %} … -
How do i properly implement image uploads without harming the API's performance
I am currently working on a fashion marketplace app that enables designers to upload pictures of their clothes and accessories. At this stage, I'm using Django and trying to figure out how to properly implement image uploads without harming the API's performance. I am also concerned about the use of large images because of the possible repercussions in terms of user experience and costs for storage. Is it wiser to use the likes of Amazon S3 for this purpose or are there better alternatives in optimizing images on Python web frameworks? I haven't tried, I just want to know if anyone has experience of the best approach without reducing API performance -
Django cookiecutter error while trying to create a project
I'm trying to use cookiecutter for the creation of my Django projects but it is not working. My OS is: Ubuntu 24.04.1 LTS Python version: 3.12.3 I follow these steps: python3 -m venv venv source venv/bin/activate pip install Django pip install cookiecutter cookiecutter gh:cookiecutter/cookiecutter-django [1/27] project_name (My Awesome Project): car [2/27] project_slug (car): car [3/27] description (Behold My Awesome Project!): Car project [4/27] author_name (Daniel Roy Greenfeld): A V [5/27] domain_name (example.com): car.com [6/27] email (a-v@car.com): car@mail.com [7/27] version (0.1.0): 0.1.0 [8/27] Select open_source_license 1 - MIT 2 - BSD 3 - GPLv3 4 - Apache Software License 2.0 5 - Not open source Choose from [1/2/3/4/5] (1): 1 [9/27] Select username_type 1 - username 2 - email Choose from [1/2] (1): 1 [10/27] timezone (UTC): Italy [11/27] windows (n): n [12/27] Select editor 1 - None 2 - PyCharm 3 - VS Code Choose from [1/2/3] (1): 2 [13/27] use_docker (n): n [14/27] Select postgresql_version 1 - 16 2 - 15 3 - 14 4 - 13 5 - 12 Choose from [1/2/3/4/5] (1): 1 [15/27] Select cloud_provider 1 - AWS 2 - GCP 3 - Azure 4 - None Choose from [1/2/3/4] (1): 4 [16/27] Select mail_service 1 … -
Dependencies issues in docker container
I'm using a Django Based Web Application. The application is using Multiple containers which includes Redis, Postgres, ElasticSearch, Kibana and Application container. When I run "docker-compose up -d --build", all containers are started but application containers is exited, When I checked logs for this container I found this " presshook-web-app-1 | honcho start & python manage.py qcluster presshook-web-app-1 | /bin/sh: 1: honcho: not found presshook-web-app-1 | Traceback (most recent call last): presshook-web-app-1 | File "/app/manage.py", line 49, in presshook-web-app-1 | from django.core.management import execute_from_command_line presshook-web-app-1 | ModuleNotFoundError: No module named 'django' presshook-web-app-1 | make: *** [Makefile:31: run] Error 1 " I checked my requirement.in fike and it contains all the dependencies. I tried to again install them by mentioning into dockerfile. but when i run command, I still found the same error. I tried to add these packages in dockerfile manually in spite of they're also being used in requirement.in file. But I found the same issues on repeating again and again. -
Can't send mail in dockerized Django application, if email settings are set from docker environment
I'm working on dockerized django store project with Celery and Redis. When customer makes an order, Celery sends him email about it. When I set django email settings directly, everything works fine: EMAIL_USE_SSL = True EMAIL_HOST = "smtp.yandex.ru" EMAIL_HOST_USER = "mymail@yandex.ru" EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST_PASSWORD = "password" EMAIL_PORT = 465 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_ADMIN = EMAIL_HOST_USER But when I set same variables from docker-compose environment: EMAIL_USE_SSL = os.getenv("EMAIL_USER_SSL") EMAIL_HOST = os.getenv("EMAIL_HOST") EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER") EMAIL_BACKEND = os.getenv("EMAIL_BACKEND") EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD") EMAIL_PORT = os.getenv("EMAIL_PORT") DEFAULT_FROM_EMAIL = os.getenv("EMAIL_HOST_USER") SERVER_EMAIL = os.getenv("EMAIL_HOST_USER") EMAIL_ADMIN = os.getenv("EMAIL_HOST_USER") I get the following error from Celery: celery-1 | [2024-09-23 12:48:48,816: ERROR/ForkPoolWorker-2] Task orders.tasks.send_order_email[243058c7-6fc2-47a2-9f36-7e0e1b00cd9d] raised unexpected: AttributeError("'NoneType' object has no attribute 'rsplit'") celery-1 | Traceback (most recent call last): celery-1 | File "/usr/local/lib/python3.11/site-packages/celery/app/trace.py", line 453, in trace_task celery-1 | R = retval = fun(*args, **kwargs) celery-1 | ^^^^^^^^^^^^^^^^^^^^ celery-1 | File "/usr/local/lib/python3.11/site-packages/celery/app/trace.py", line 736, in __protected_call__ celery-1 | return self.run(*args, **kwargs) celery-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^ celery-1 | File "/usr/src/bookstore/orders/tasks.py", line 7, in send_order_email celery-1 | send_mail( celery-1 | File "/usr/local/lib/python3.11/site-packages/django/core/mail/__init__.py", line 77, in send_mail celery-1 | connection = connection or get_connection( celery-1 | ^^^^^^^^^^^^^^^ celery-1 | File "/usr/local/lib/python3.11/site-packages/django/core/mail/__init__.py", line 51, in get_connection celery-1 | klass = … -
What is the difference between request.GET.get('username') and request.META.get('HTTP_X_ USERNAME') in DRF
I want to know the difference between this two methods of getting data Just tried to figure it out for the object concepts of this data fetching... I saw request.GET.get('username') used in customauth.py at the time of custom authentication and request.META.get('HTTP_X_ USERNAME') saw in DRF documentation where the custom authentication example is given. -
Can I create a custom client/customer end dashboard in squarespace?
So basically I am designing this website and want to deal with clients using forms submissions which I can see I can do that by create projects and invoicing from the squarespace dashboard. Send proposals and stuff like many options for me and the admin accounts but the problem is clients/customers account where there are not many options like he/she cant see the number of form submissions they did, the proposals sent to them by admins or look at the status for those proposals, invoices, previous orders submitted or rejected etc. So how can i make a proper dashboard for my clients as well to come and see all the details of services, orders, forms, proposals, previous orders etc. Currently there are only address, order option available and the order will work if I create a products page or service only can you please guide me through if there are any options where I can create a custom account dashboard for my clients as well? So like as a owner/admin I dont want to make a store as I want to sell my services through form submissions and stuff. Squarespace provides many options for admins but not much for customers … -
how to find near objects in django?
I have a service provider model . it has two fields named : lat & lon class Provider(models.Model): name = models.CharField(max_length=100) lat = models.CharField(max_length=20) lon = models.CharField(max_length=20) address = models.TextField(null=True , blank=True) def save(self, *args, **kwargs): try: data = getaddress(self.lat , self.lon) self.address = data['formatted_address'] except: pass super(Provider, self).save(*args, **kwargs) How can i get a location from user and find some service providers that are near to my user? and it must be from the lat and lon field beacuse it is possible to service provider is located on another city ! also the speed of proccesse is important! -
Generating models from old Microsoft sql server 2005 database
I am currently trying to use inspectdb to generate models from a very old Microsoft sql server 2005 database. I have not written the database. Now the error I'm getting is that 'SYSDATETIME' is not a recognized built-in function name. So I know it's because that database uses a much older function methods for time and date. How can I solve this problem thanks. -
Solr Search Not Returning Expected Results in Django with Haystack
I'm working on a Django project using Haystack for search functionality with Solr as the backend. I've set up everything, but when I perform a search, the results are not returned as expected. Problem Description: I have a search view that queries Solr for products based on a search term. While the search query executes without errors, the returned results do not contain any products, even though I have verified that products exist in the database. views.py: from haystack import indexes from haystack.query import SearchQuerySet from django.shortcuts import render def search_view(request): query = request.GET.get('q') results = SearchQuerySet().filter(content=query) if query else [] print(f"Search Query: {query}, Results: {results}") context = { 'results':results, 'query':query, } return render(request, 'core/search.html', context) Search_indexes.py: from haystack import indexes from core.models import * class Solr_Model_Index (indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Product def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() Steps Taken: Rebuilt the Index: I ran python manage.py rebuild_index to ensure all products are indexed. Checked Solr Admin Interface: I confirmed that products are visible in Solr under the "Documents" tab. Debugging: Added print statements in the search view to check the query and results. Current Output: Search … -
My request cookie not working on server but works locally (Azure Web Appservices)
I am using my web cookie from chrome to log onto a web using python requests. This works very fine on localhost http://127.0.0.1:8000/ but when I deploy this on to azure App Services, this does not work any more and shows "WARNING: Login Failed!!" class MySpider(scrapy.Spider): def __init__(self, link, text): self.link = link self.cookie = 'my_cookies' self.user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36' self.text = text def login(self, url): headers = { 'User-Agent': self.user_agent, 'Cookie': self.cookie, } session = requests.Session() response = session.get(url, headers=headers) response.text.encode('utf-8') if response.status_code != 200: print('WARNING: Login Failed!!') return response I tried to change cookies and inbond IP but still get WARNING: Login Failed!!