Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Removing subdomains from my multitenancy app
I have a working multitenancy app in Django with isolated databases that currently uses a subdomain for each tenant and threading. The subdomain prefix is used to make a connection to the corresponding database, so: client1.mysite.com access the database client1 client2.mysite.com access the database client2 And so on. This is the current code I have: middleware: import threading from app.utils import tenant_db_from_the_request Thread_Local = threading.local() class AppMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): db = tenant_db_from_the_request(request) setattr(Thread_Local, 'DB', db) response = self.get_response(request) return response def get_current_db_name(): return getattr(Thread_Local, 'DB', None) utils: def hostname_from_the_request(request): return request.get_host().split(':')[0].lower() def tenant_db_from_the_request(request): hostname = hostname_from_the_request(request) tenants_map = get_tenants_map() return tenants_map.get(hostname) def get_tenants_map(): return dict(Tenants.objects.values_list('subdomain', 'database',)) routers: class AppRouter: def db_for_read(self, model, **hints): return get_current_db_name() def db_for_write(self, model, **hints): return get_current_db_name() def allow_relation(self, *args, **kwargs): return True def allow_syncdb(self, *args, **kwargs): return None def allow_migrate(self, *args, **kwargs): return None Using subdomains is not exactly ideal, so I'm trying to switch the subdomain prefix to a suffix that will be added to the username of each tenant. With that, every tenant will access the same URL: mysite.com And the suffix will be added to the username like that: user@client1 access the database client1 user@client2 … -
how to set up DJANGO_SETTINGS_MODULE with absolute path of the settings.py file
I need to write some scripts for django and trying to set up the DJANGO_SETTINGS_MODULE environment variable at the beginning of each script. The scripts, manage.py and myproject directory are in the same parent directory. Additionally, settings.py file is in myproject directory. Therefore, following code works correctly #test_script_header.py import os os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings" import django django.setup() But following code doesn't work #test_script_header.py import os os.environ["DJANGO_SETTINGS_MODULE"] = "/home/<username>/workspace/djangoapp/src/myproject/settings.py" import django django.setup() I get the error ModuleNotFoundError: No module named '/home/<username>/workspace/djangoapp/src/myproject/settings.py' Here is the complete error message Traceback (most recent call last): File "/home/<username>/workspace/djangoapp/src/test_script_header.py", line 22, in <module> django.setup() File "/usr/lib/python3/dist-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named '/home/<username>/workspace/djangoapp/src/myproject/settings' However, I want to eventually move … -
How to make user in Django choose the workshop he added to make a service record for his own car?
im struggling with same problem for 3 days now, im trying to make my finish project which is some kind of online servicebook for cars we own, i have models vehicle, workshop, filter, servicerecord and i cant add servicerecord to the car i have added is there anyone who could help me? Here comes a little bit of code i have problems with from forms.py and views.py: class ServiceRecordCreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): `super().__init__(*args, **kwargs) all_workshops = Workshop.objects.exclude(name="Other Workshop") workshop_choices = [(workshop.id, workshop.name) for workshop in all_workshops] workshop_choices.insert(0, (0, 'Other Workshop')) self.fields['workshop'].widget = forms.Select(choices=workshop_choices) self.fields['workshop'].choices = workshop_choices all_filters = Filter.objects.all() filter_choices = [(filter.id, filter.name) for filter in all_filters] self.fields['filters_changed'].widget = forms.CheckboxSelectMultiple() self.fields['filters_changed'].choices = filter_choices def clean_workshop(self): workshop_id = self.cleaned_data.get('workshop') if workshop_id == 0: # Obsługa przypadku "Other Workshop" workshop = Workshop.objects.filter(name="Other Workshop").first() if not workshop: raise forms.ValidationError("Other Workshop is not available.") else: workshop = Workshop.objects.get(id=workshop_id) return workshop class Meta: model = ServiceRecord fields = ['workshop', 'date', 'mileage_at_service', 'filters_changed'] widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), } class ServiceRecordCreateView(LoginRequiredMixin, CreateView): model = ServiceRecord form_class = ServiceRecordCreateForm template_name = 'create_service_record.html' def get_success_url(self): vehicle_id = self.kwargs['vehicle_id'] return reverse_lazy('service_record_list', kwargs={'vehicle_id': vehicle_id}) def form_valid(self, form): service_record = form.save(commit=False) service_record.vehicle_id = self.kwargs['vehicle_id'] service_record.save() form.save_m2m() return redirect(self.get_success_url()) i … -
serve django staticfiles with nginx inside docker
I have problem with staticfiles for django admin panel. for rest framework frontend panel the files are served without problem settings.py STATIC_URL = "/static/" STATIC_ROOT = BASE_DIR / "staticfiles" STATIC_ROOT.mkdir(exist_ok=True) Dockerfile: FROM python:3.10-slim-buster ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 RUN python manage.py collectstatic --noinput docker-compose: version: '3.8' services: web: build: . command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/app # - static_volume:/usr/share/nginx/html/static ports: - "8000:8000" nginx: image: nginx:1.19-alpine ports: - "80:80" - "443:443" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./nginx/conf.d:/etc/nginx/conf.d - ./certbot/conf:/etc/letsencrypt - ./certbot/www:/var/www/certbot # - static_volume:/usr/share/nginx/html/static # Ensure this matches the alias in nginx.conf - static_volume:/app/staticfiles volumes: static_volume: nginx/conf.d.default.conf server { listen 80; server_name localhost; location /static/ { alias /usr/share/nginx/html/static; # Ensure this matches the volume mapping in docker-compose.yml autoindex on; # Optionally enable to troubleshoot file listing } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } It's my first time building app using django, gunicorn, nginx my config files are from chatgpt and tutorials. if i'm doing some mistake and someone will point it it'd great -
How to add results to a test in Django quiz app?
I'm just learning Django and trying to create a test. I watched the video on YouTube, but I didn't quite understand how to add the test results to the page. I created the test and in the SQLite database, I can create categories, questions, answers, and answer scores. How can I withdraw the points for the answers after sending the answers.I would like the answers to appear on the quiz_detail page. In the form of correct/incorrect (under each question) or in the form of a "Total score". Quiz_detail.html {% extends "base.html" %} {%block content%} <div class="parent-div"> <div class="centered-div"> <h3 class="title">{{quiz.title}}</h3> <form method="post" id="quizform" action="{% url 'quiz_submit' quiz.id %}"> {%csrf_token%} {%for question in questions%} <h2> {{question.text}}</h2> <h2 class="white-container">{{question}}</h2> <h3 class="grey-container"> {%for choice in question.choices.all%} <input type="radio" id="choice_{{choice.id}}" name="question_{{question.id}}" value="{{choice.id}}" /> <label for="choice_{{choice.id}}">{{choice.text}}</label> <br /> {%endfor%} {%endfor%} </h3> <button type="submit">Submit quiz</button> </form> {% block title %}Result{% endblock %} </div> </div> {%endblock%} models.py class Question(models.Model): text = models.CharField(max_length=225) quiz = models.ForeignKey(Quiz, related_name="questions", on_delete = models.CASCADE) def __str__(self) -> str: return self.text class Choice(models.Model): text = models.CharField(max_length=225) question = models.ForeignKey(Question, related_name="choices", on_delete = models.CASCADE) score = models.FloatField(default=0) is_correct = models.BooleanField('Correct', default=False) comment = models.CharField('comment', default=False, max_length=225) def __str__(self) -> str: return self.text class UserResponse(models.Model): … -
Graphene django. Get error: String cannot represent value '(value, )' after mutation attempt
I'm new to graphene library and make updating mutation as was in documentation. Also I looked at this video about CRUD : https://youtu.be/C-EfYVXShLE?si=uksgjJEuavU1k9GW I thought, that problem was in mutate arguments, I tried to make it with kwargs, but result was the same. Unfortunatly, most guides was using django-rest to write crud, but I would like to make it without others dependecies. Here's the code: class UpdateAddress(graphene.Mutation): address = graphene.Field(AddressType) class Arguments: address_id = graphene.ID(required=True) index = graphene.String() street = graphene.String() house = graphene.String() flat = graphene.String() locality = graphene.Int() @classmethod def mutate(cls, root, info, address_id, index=None, street=None, house=None, flat=None, locality=None): address = Address.objects.get(pk=address_id) try: entry = Locality.objects.get(pk=locality) except Locality.DoesNotExist: entry = None address.index=index, address.street=street, address.house=house, address.flat=flat, address.locality=entry address.save() return UpdateAddress(address=address) When i try to update some field with this query: mutation { updateAddress( addressId: "1", index: "41204" street: "Shevchenko", house: "1", flat: "15", locality: 1 ) { address{ id, street, index, house, flat, locality{ id } } } } I recieve errors: "errors": [ { "message": "String cannot represent value: ('41204',)", "locations": [ { "line": 12, "column": 7 } ], "path": [ "updateAddress", "address", "index" ] } ], Somehow it sets all string values to a tuple and I … -
not able to connect to external mysql db in django
i am again and again failing to connect to external mysql db on phpmyadmin db as my django keeps connnecting to its localhost database i have tried many things but not getting success can you guys help me please #db conf in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', "USER": "user", "PASSWORD": "password", "host": 'host_ip', 'PORT': 3306, } } i have already installed packages like mysql and mysqlclient but still not able to connect to external db, and when i do migration i get errors like localhost target machine actively refused connection -
why my content is not showing between blockcontent and endblock in django?
i have build an other app in my django project and have a template in my templates folder and i am including the base.html from my other app but the problem is in when i want to write html in my block content tags its showing it below the footer not in between the navbar and the footer {% include 'webapp/base.html' %} {% load static %} {% block content %} Patient Info {% endblock %} the screenshot is below why i am getting this below my footer its working perfect in my firstapp in project all the other things like statics are loading but when i write anything in block tags its showing it in below the footer of my base.html this is happening only in my patients app not in webapp in webapp i also extending my base.html and its showing the block content in the block contents tag of base.html but in patients app its not showing inbetween the blockcontents -
I can't add an image through object.create in Django
Good afternoon, I'm trying to insert an image into the database through object.create, but it's not being inserted in any way, everything else is inserted until the other image. The image is being created that I have already tested, and is being loaded correctly as jpg. But I'm not able to use it other than through the path, but I want it to be automatically inserted. Insertion code I'm using: stringRegisto = RegistoString.objects.create(string=string_registro,rostosDetectados=frame_io, ecra=estacao_trabalho.owner.photo) way by path that is working: stringRegisto = RegistoString.objects.create(string=string_registro, rostosDetectados="/rostos/frame_io.jpg", ecra=estacao_trabalho.owner.photo) Views.py def run_recognition(self, request, frame): print("Executando reconhecimento facial...") rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Encontra as localizações das faces no frame face_locations = face_recognition.face_locations(rgb_frame) # Captura as caracteristicas faciais face_encodings = face_recognition.face_encodings(rgb_frame, face_locations) face_names = [] last_face_names = request.session.get('last_face_names', []) _, frame_encoded = cv2.imencode('.jpg', frame) cv2.imwrite('frames/frame_io.jpg', frame) frame_io = ContentFile(frame_encoded.tobytes()) if len(face_encodings) >= 2: # Se houver mais de um rosto no frame self.no_face_count = 0 print("Dois rostos na imagem.") face_names = [] for face_encoding in face_encodings: matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding) name = "Unknown" if True in matches: first_match_index = matches.index(True) name = self.known_face_names[first_match_index] face_names.append(name) estacao_trabalho = EstacaoTrabalho.objects.get(uuid=self.uuid) # Ordena os nomes por ordem alfabética face_names.sort() print("Rostos reconhecidos:", ", ".join(face_names)) estacao_owner_name = estacao_trabalho.owner.name # Verifica se … -
Django Reverse for '' not found. '' is not a valid view function or pattern name
I am getting an error "Django Reverse for '' not found. '' is not a valid view function or pattern name.". I was searching for a way to fix this but couldn't find anything the urls.py and views.py, home.html and atrakcja_details.html are in the same App the same folder. urls.py: from django.urls import path from . import views urlpatterns = [ path('atrakcja_details/int:atrakcja_id/', views.atrakcja_details, name='atrakcja_details'), path('about/', views.about_page, name='about'), ] views.py: from django.shortcuts import render, get_object_or_404 from .models import Atrakcja from django.http import HttpResponse def atrakcja_details(request, atrakcja_id): # Add atrakcja_id parameter if atrakcja_id: atrakcja = get_object_or_404(Atrakcja, id=atrakcja_id) return render(request, 'atrakcja_details.html', {'atrakcja': atrakcja}) else: return HttpResponse("Atrakcja not found.") def about_page(request): return render(request, 'about/about.html') home.html: I tried everything but it still doesnt work:(( please help me -
Django form saving wrong information to database
So in my form, when I select a time choice, for example "8 PM" it stores in the database as a different time, I've checked the form submission and it is being submitted as the correct time, but not being saved as such, is there anything wrong with the code? from django.core.exceptions import ValidationError from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now from django.core.validators import MinValueValidator, MaxValueValidator class Booking(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) special_occasion = models.CharField(max_length=11, choices=[('None', 'None'), ('anniversary', 'Anniversary'), ('date', 'Date'), ('business', 'Business')]) meal_day = models.DateField() number_of_guests = models.PositiveIntegerField( null=True, validators=[MinValueValidator(1), MaxValueValidator(6)] ) customer_name = models.CharField(max_length=50) TIME_CHOICES = [ ('13:00', '01:00 PM'), ('14:00', '02:00 PM'), ('15:00', '03:00 PM'), ('16:00', '04:00 PM'), ('17:00', '05:00 PM'), ('18:00', '06:00 PM'), ('19:00', '07:00 PM'), ('20:00', '08:00 PM'), ] meal_time = models.CharField(max_length=5, choices=TIME_CHOICES) def clean(self): if self.meal_day and self.meal_day < now().date(): raise ValidationError("Cannot make a booking in the past.") existing_bookings = Booking.objects.filter(meal_time=self.meal_time, meal_day=self.meal_day) if self.pk: existing_bookings = existing_bookings.exclude(pk=self.pk) if existing_bookings.exists(): raise ValidationError("A booking already exists at this time on this day.") super().clean() # Call parent's clean method for remaining validations def save(self, *args, **kwargs): if not self.pk: available_times = [choice[0] for choice in self.TIME_CHOICES] booked_times = Booking.objects.filter(meal_day=self.meal_day).values_list('meal_time', flat=True) available_times = … -
KeyError: '__reduce_cython__' when trying to import sklearn package into Django app
When attempting to run my Django app with python manage.py runserver, I am getting the following error relating to a scikit-learn module import: File "sklearn\\metrics\\_pairwise_distances_reduction\\_argkmin.pyx", line 1, in init sklearn.metrics._pairwise_distances_reduction._argkmin KeyError: '__reduce_cython__' This is the last line in a larger error message, listed below. I have tried everything I've found online, including: upgrading all packages uninstalling and reinstalling related packages checking package dependencies are satisfied using pipdeptree to ensure package versions aren't conflicting restarting vscode, laptop etc. Despite this, every time I run python manage.py runserver I get the same error appearing. I'm using pip to install packages. Here are my current package versions in this venv: |asgiref |3.7.2| |Cython |3.0.10| |Django |5.0.5| |django-cors-headers |4.3.1| |django-environ |0.11.2| |djangorestframework |3.14.0| |joblib |1.4.2| |numpy |1.26.4| |packaging |24.0| |pandas |2.2.1| |pip |24.0| |pipdeptree |2.19.1| |psycopg |3.1.18| |psycopg2-binary |2.9.9| |python-dateutil |2.9.0.post0| |pytz |2024.1| |scikit-learn |1.4.2| |scipy |1.13.0| |six |1.16.0| |sqlparse |0.4.4| |stringcase |1.2.0| |threadpoolctl |3.5.0| |typing_extensions |4.9.0| |tzdata |2024.1| Interestingly from sklearn.feature_extraction.text import TfidfVectorizer causes no issues, but from sklearn.metrics.pairwise import cosine_distances is the line causing the issue. Please help! Have been stuck on this for a few days now. Full error message: Exception in thread django-main-thread: Traceback (most recent call last): File "C:userpath\AppData\Local\Programs\Python\Python312\Lib\threading.py", … -
Page not found (404) appears when performing tutorial
I get the following error after many tries Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls, didn’t match any of these. 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. The code is written as follows, as shown in the tutorial mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("polls", include("polls.urls")), path("admin/", admin.site.urls), ] polls/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] polls/views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") mysite/setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ] I asked questions to chatGPT and Llama3 and they told me to ask them here. Repeatedly restarting the server and copying and pasting the code did not solve the problem. Cache removal and re-installation of Python, Django, and virtual environments have also been performed. Let me know if there is anything else I should check. -
How do I customize Djoser endpoint '/users/me/' to return all custom user fields?
from djoser.serializers import UserCreateSerializer, UserSerializer from django.contrib.auth import get_user_model User = get_user_model() class UserSerializer(UserSerializer): class Meta(UserSerializer.Meta): model = User fields = ('id','email','name','phone_number','address') The endpoint only returns id, email and name. I want it to return all other fields. -
How to display dropdown menu in javascript
I'm using a javascript to display a table in a django template. If the receipt's is_disbursed value is True and the paid_status is Settled, I want the dropdown menu to contain Print only. If is_disbursed is False and the paid_status is Settled, it should display the Print, Disburse and the Reverse options. If is_disbursed is True and paid_status is Partially Paid, I want to display the Print, Collect Balance, and the Reverse options. If is_disbursed is False and the paid_status is Unpaid, the dropdown should contain Print, Collect Balance, and Reverse #html <div class="card-body"> <div id="table-receipts" data-rent-receipt-url="{% url 'agency_rent_receipt' pk='PLACEHOLDER' %}" data-disburse-rent-url="{% url 'disburse_rent' pk='PLACEHOLDER' %}" data-rent-bal-url="{% url 'rent_balance' receipt_id='PLACEHOLDER' %}"></div> </div //js <script> document.addEventListener("DOMContentLoaded", function () { const table = document.getElementById("table-receipts"); if (table) { const printReceiptUrl = table.getAttribute("data-rent-receipt-url"); const rentDisbursementUrl = table.getAttribute("data-disburse-rent-url"); const rentBalanceUrl = table.getAttribute("data-rent-bal-url"); fetch('/accounting/receipts_data/api') .then(response => response.json()) .then(receipt_data => { new gridjs.Grid({ columns: [ { name: "Receipt Number", width: "180px" }, { name: "Date", width: "120px" }, { name: "Address", width: "120px" }, { name: "Tenant", width: "120px" }, { name: "Status", width: "120px" }, { name: "Action", width: "100px", formatter: function (cell, row) { const receiptId = row.cells[5].data; const finalprintReceiptUrl = printReceiptUrl.replace('PLACEHOLDER', receiptId); const finalrentDisbursementUrl … -
Django 4.2 how to display deleted object failure in modeladmin page?
Code used to override the delete_queryset in the modeladmin: def get_actions(self, request): actions = super().get_actions(request) del actions['delete_selected'] return actions def really_delete_selected(self, request, queryset): ''' # 1. Update the group-mailbox relation: `goto` values if mailbox(es) are deleted # 2. Sending a mail to the current user with CSV of mailboxes deleted # 3. Used domain space will reduce by the maxquota of mailbox ''' response = None print('delete from mailbox queryset called') try: mbox_list = [] failed_deletions = [] print(queryset) for obj in queryset: mdomain = None # COMPLETE MAILBOX DELETION OF FOLDERS, DOVECOT ENTRY, ADMIN PANEL PERMANENTLY api_delete_status = call_purge_mailbox_api(request,obj) response = api_delete_status print('response---------',response, response['status_code']) if response['status_code'] == 200: # Set the quota value after deletion of mailbox(es) mdomain = Domain.objects.get(id=obj.domain.pk) mdomain.quota -= obj.maxquota mdomain.save() mbox_list.append(obj.email) # Remove the user from the group mailing lists # master_grp_list = GroupMailIds.objects.exclude(goto=None) removed_from_groups :bool = remove_from_group_lists(obj.email,mbox_list) print('mailbox deletion completed.....') # TODO: List for sending a mail to the currently logged in user with CSV of # mailboxes deleted else: print('Failed to delete mailbox:', obj.email) failed_deletions.append(obj.email) print(failed_deletions, len(failed_deletions)) if mbox_list: # Check if any mailboxes were successfully deleted self.message_user(request, f"Successfully deleted {len(mbox_list)} mailbox(es).",level='success') for email in failed_deletions: # Display error message for each failed … -
I want to convert the python data structure into yaml format
@require_http_methods(["POST"]) @csrf_exempt @api_view(['POST']) @permission_classes([IsAuthenticated]) def SetAlertRules(request): try: if not request.body: return Response({'error': "Data for setting alert not provided"}, status=http_status.HTTP_400_BAD_REQUEST) payload = json.loads(request.body) if not payload: return Response({'error': "Data for setting alert not provided"}, status=http_status.HTTP_400_BAD_REQUEST) vm = payload.get('vm') connector = payload.get('connector') panel = payload.get('panel') threshold = payload.get('threshold') notification_channel = payload.get('notification_channel') # for now, we are only focusing on email user = payload.get('user') # user will be the email id if not vm or not connector or not panel or not threshold or not notification_channel or not user: return Response({'error': "Required data for setting alert not provided"}, status=http_status.HTTP_400_BAD_REQUEST) # establish a ssh connection with the vm ssh=None try: username="" password="" vault_path = f'secret/{str(vm).strip()}' response= read_vault_data(vault_path) status_code = response.status_code data = response.data if status_code == 200: username = data['username'] password = data['password'] ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(vm, username=username, password=password) sftp = ssh.open_sftp() # --------- START -> Alert addition in prometheus rules.yml file ----------- ######### # checking if prometheus_rules.yml file is present or not, if yes, then appending the alert rule/s, else creating and adding alert rule/s prometheus_rules_config_path = '/usr/APM/script_data/prometheus-2.44.0.linux-amd64/prometheus_rules.yml' # to check if file exists, of not create it try: sftp.stat(prometheus_rules_config_path) except FileNotFoundError: log_info(f"prometheus_rules.yml is created now----") ssh.exec_command("sudo touch /usr/APM/script_data/prometheus-2.44.0.linux-amd64/prometheus_rules.yml") stdin, stdout, stderr … -
how to add email sending port to the security group in AWS ec2 instance
I'm trying to send an email from my back end that is hosted on an ec2 instance on amazon web services , but the function that runs this part takes a very long time to start the request that it gives me back a timeout error , so i think i need to add the port in the security group but am not aware how to set this up !! here is how my email server settings looks like : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.bizmail.yahoo.com' EMAIL_USE_TLS = True EMAIL_PORT = 465 EMAIL_HOST_USER = "my email here" EMAIL_HOST_PASSWORD = "my password here" -
Validation error doesn't render on the template with 2 form
I have in my template with a form in which data is collected in 2 Django forms but sent to the view in the same post like this: <form> {{ form1 }} {{ form2 }} </form> The data is collected in the view and validated. To validate, I have validations declared in both forms. In case the validations fail because the data is incorrect, they return a raise (depending on which one or ones have failed). This raise is what should be shown on the screen to the user as an error. If the failed validation is in the second form, it displays the error correctly and without problems. Now, in the case that the failure is in the first form, the page simply reloads and does not show the error. The data already entered in the form is not lost and can be corrected, but the error is not displayed. My view is something like this: def create(request): form1 = Form1(request.POST or None) form2 = formset_factory(Form2, extra=0) form2Set = form2(request.POST or None, prefix='participant') context = { 'form1': form1, 'form2Set': form2Set, } if request.method == 'POST': if form1.is_valid() and form2Set.is_valid(): # Logic else: context['form1'] = form1 context['form2Set'] = form2Set return … -
Django + Celery logging configuration on Heroku
TLDR; I deployed a django + celery app on heroku but I'm unable to see Celery logs on heroku logs. django==5.0.1 celery==5.3.4 Here are the relevant files Procfile web: daphne ecom_proj.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: celery -A ecom_proj.celery_app worker -E -B --loglevel=INFO settings.py LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "base": { "()": "django.utils.log.ServerFormatter", "format": "[{server_time}] {name} {levelname} {module} {message}", "style": "{", } }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "base", "level": "INFO", }, }, "loggers": { "": { "handlers": ["console"], "level": "INFO", }, "django": { "handlers": ["console"], "level": "INFO", "propagate": False, }, "celery": { "handlers": ["console"], "level": "INFO", "propagate": False, }, }, } celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecom_proj.settings") celery_app = Celery("ecom_proj_celery") celery_app.autodiscover_tasks() myapp/tasks.py import logging from celery import shared_task logger = logging.getLogger(__name__) @shared_task def my_task(): logger.info("task has started") # Do something.... With all these files, I deploed the django project on heroku and able to see web process's log messages however for worker process (Celery), I can't see any logs that are in task functions. although I'm able to see all celery logs on local machine with same configuration. I went through different SOF questions and most of them are … -
Ordering in the Django admin by related manytomany field
This is my models.py: class Person(models.Model): surname = models.CharField(max_length=100, blank=True, null=True) forename = models.CharField(max_length=100, blank=True, null=True) class PersonRole(models.Model): ROLE_CHOICES = [ ("Principal investigator", "Principal investigator"), [...] ] project = models.ForeignKey('Project', on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) person_role = models.CharField(choices=ROLE_CHOICES, max_length=30) class Project(models.Model): title = models.CharField(max_length=200) person = models.ManyToManyField(Person, through=PersonRole) @admin.display(description='Principal investigator') def get_PI(self): return [p for p in self.person.filter(personrole__person_role__contains="Principal investigator")] I would like to order the column of 'principal investigator' in the django Admin backend for the projects page. How can I do that? This is my attempt, which is not working: admin.py class ProjectAdmin(ImportExportModelAdmin): ordering = ('title','get_principal_investigator') def get_principal_investigator(self, obj): return self.get_PI get_principal_investigator.admin_order_field = "get_PI" get_principal_investigator.short_description = "Principal investigator" -
When i try to display on front-end the variavel "face_names" he always come empty
I have a facial recognition webapp in django, and I'm trying to show the user through a variable "face_names" which names are being captured on the screen, but it is always empty even when it has values inside. I've already tried just putting the value, you always have to search for a different value and it still didn't work, I just wanted to show it in text form. Views.py class FaceRecognition: ... def run_recognition(self, request, frame): ... response_data = { "face_names": face_names, } print("response_data:", response_data) # Vamos retornar esse dicionário. return JsonResponse (response_data) HTML <h1 class="titulo">Camera</h1> <div id="error-message" style="display: none;"> <p>Error aaccessing Camera </p> </div> <video id="video" autoplay></video> <canvas id="canvas" width="640" height="480" style="display: none;"></canvas> <div id="processing-message" style="display: none;">Running</div> <div id="face-names"></div> <button id="capture-button" onclick="captureFrame()">Capture Frame</button> JavaScript function sendFrameToServer(blob) { showProcessingMessage(); hideButton(); const data = new FormData(); data.append('frame_data', blob, 'frame.jpg'); fetch('/processar_reconhecimento_facial/', { method: 'POST', headers: { 'X-CSRFToken': getCookie('csrftoken') // Adicione o token CSRF }, body: data }).then(response => { if (response.ok) { // Se a resposta for bem-sucedida, capture o próximo frame console.log(response); captureFrame(); } if (response.headers.get('Content-Type') === 'application/json') { console.log("json response"); console.log(data); return response.json(); } else { console.log("blob response"); return response.blob(); } }) .then(data => { if (data.message === 'redirecionamento') { … -
How to access attribute of a foreign key model inside serializer django rest framework?
I have two models named Market, Exchange class Exchange(models.Model): name = models.CharField(max_length=20) class Market(models.Model): exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE) price = models.FloatField(default=0.0) What I need to do is get name field in Exchange Model inside MarketSerializer -> class MarketSerializer(serializers.ModelSerializer): class Meta: model = Market fields = ('exchange_name', 'price', ) How can I do that? -
Django Project Stuck at Login Page
I'm very new to Django and I am trying to create an booking website. I want that after login it should redirect to my booking.html page, but instead, I had this login page always keep heading back to login page over and over again This is my login.html : {% extends 'base.html' %} {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/signin.css' %}"> <!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Bootstrap Bundle with Popper --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script> <div class="row justify-content-center"> <div class="col-md-4"> <div class="login-container"> {% if session.success %} <div class="alert alert-success alert-dismissible fade show" role="alert"> {{ session.success }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endif %} {% if session.loginError %} <div class="alert alert-danger alert-dismissible fade show" role="alert"> {{ session.loginError }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endif %} <div class="row justify-content-center"> <div class="wow fadeInUp" data-wow-delay="0.1s"> <main class="form-signin"> <div class="wrapper"> <div class="logo"> <img src="{% static 'img/logo.png' %}"> </div> <br> <div class="text-center mt-4 name"> Login Dulu Yuk </div> <br> <form id="loginForm" action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="p-3 mt-3"> <div class="form-floating form-field d-flex align-items-center"> <input type="text" name="username" class="form-control rounded {% if form.errors.username %}is-invalid{% endif %}" id="username" placeholder="Username" autofocus required> <label for="username">Username</label> {% if … -
django - is UniqueConstraint with multi fields has same effect as Index with same field?
I wrote a django model that you can see below, I want to know having the UniqueConstraint is enough for Search and Selecting row base on user and soical type or I need to add the Index for them. if yes what is the different between them becuse base on my search the UniqueConstraint create an Unique Index on DB like posgresql. model: class SocialAccount(Model): """Social account of users""" added_at: datetime = DateTimeField(verbose_name=_("Added At"), auto_now_add=True) user = ForeignKey( to=User, verbose_name=_("User"), db_index=True, related_name="socials", ) type = PositiveSmallIntegerField( verbose_name=_("Type"), choices=SocialAcountType, ) class Meta: constraints = UniqueConstraint( # Unique: Each User Has Only one Social Account per Type fields=( "user", "type", ), name="user_social_unique", ) # TODO: check the UniqueConstraints is enough for index or not indexes = ( Index( # Create Index based on `user`+`type` to scan faster fields=( "user", "type", ), name="user_social_index", ), ) base on the above description I searched but I can't find any proper document to find how django act and we need extra index for them if they are a unique togher already? Note: I know there are some other questions that are similar but they can't answer my question exactly