Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error with making a facial recognizer matrix. how to fix?
File "./rastreamento_de_rosto.py", line 43, in recognizer.train(x_train, np.array(y_labels)) cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv_contrib\modules\face\src\lbph_faces.cpp:362: error: (-210:Unsupported format or combination of formats) Empty training data was given. You'll need more than one sample to learn a model. in function 'cv::face::LBPH::train' I am having a problem with this code, it is supposed to be reading images and making a resumed pixel per color matrix of said images for a facial recognizer. but once i run this code, it keeps giving me the error said in the title, even though before it reaches the line of that code it reads the images before. import cv2 import os import numpy as np from PIL import Image import pickle BASE_DIR = os.path.dirname(os.path.abspath(__file__)) image_dir = os.path.join(BASE_DIR, "images") face_cascade = cv2.CascadeClassifier('cascades/haarcascade_frontalface_alt2.xml') print("não e aqui em face_cascade") recognizer = cv2.face.LBPHFaceRecognizer_create() print(recognizer) current_id = 0 label_ids = {} y_labels = [] x_train = [] for root, dirs, files in os.walk(image_dir): for file in files: if file.endswith("png") or file.endswith("jpg"): path = os.path.join(root, file) label = os.path.basename(root).replace(" ", "-").lower() if not label in label_ids: label_ids[label] = current_id current_id += 1 pil_image = Image.open(path).convert("L") size = (550, 550) final_image = pil_image.resize(size, Image.ANTIALIAS) image_array = np.array(final_image, "uint8") faces = face_cascade.detectMultiScale(image_array,scaleFactor=1.5,minNeighbors=5) print(image_array) for (x,y,w,h) in faces: roi = … -
Django Queryset: Filter for subset of many to many relation
Let's assume the following model: class User(models.Model): clients = models.ManyToManyField(Client) How to query users by a list of clients, so that only those users are returned that have not other clients than those in the given list assigned. User.objects.filter(client__??=[client1, client2]) I had a look at Django's documentation of field lookups, but that did not help. Thanks in advance! -
TemplateDoesNotExist at / basicapp/index.html
`Hello friends,i tried creating basic forms with django from a direct example from Python and Django Full Stack Web Developer Bootcamp. i got the error below. TemplateDoesNotExist at / basicapp/index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.3 Exception Type: TemplateDoesNotExist Exception Value: basicapp/index.html Exception Location: C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\loader.py, line 19, in get_template Raised during: basicapp.views.index Python Executable: C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.0 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\ADMIN\Desktop\Django\Django_forms\basic_forms\templates,\basicapp\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\admin\templates\basicapp\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\templates\basicapp\index.html (Source does not exist) This is my **setting.py ** from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR,"templates,") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-bdh2@$^s84&+%qn^atqa+xjz8@7&g=(m2^!5j$f#$o=4+7jb5s' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "basicapp", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'basic_forms.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True,` … -
Django - How to use delete() in ManyToMany relationships to only delete a single relationship
I have a model Voucher that can be allocated to several users. I used a M2M relationship for it. I want, in the template, the possibility to delete the voucher allocated to the logged in user, and the logged in user only (not all relationships). The problem I have is that the current model deletes the entire model for all users, instead of the single user requesting "delete". The alternative would obvioulsy be to simply create a model Voucher on a ForeignKey, but something tells I can probably do it with a M2M in the views. Is there a way to focus my delete function specific to the user? In the example below, I tried to filter based on user.request which is not working. Looking at the data inside the model, users IDs are listed. Is it not what request.user does? models class Voucher(models.Model): user = models.ManyToManyField(User, blank=True) views def delete_voucher(request, voucher_id): voucher = Voucher.objects.filter(pk=voucher_id).filter(user=request.user) voucher.delete() return redirect('account') template <a class="button3 btn-block mybtn tx-tfm" href="{% url 'delete-voucher' voucher.id %}">Delete</a> url path('delete_voucher/<voucher_id>', views.delete_voucher, name='delete-voucher'), -
django app in cpaned doesn't upload pictures that I upload from django admistration page
after I deployed my django app to cpanel it doesn't save pictures that I upload it from django adminstration page Not: all data I enter it's save it and can return it to template but pictures not upload them How I can solve this problem? -
How to change the date of time instance using python?
I have start_time variable that stores a time string. start_time = '2022-12-21 22:00:00' Now Using python i want to change the date of start time to start_time = '2022-12-28 22:00:00' I have done this with very ugly approach. Please tell me easy and best way to do that. I tried with following code. #its not string its time instance replacing_date = 2022-12-28 00:00:00 #converting time into string replacing_date = datetime.strptime(replacing_date,'%Y-%m-%d %H:%M:%S') replacing_date =replacing_date.split(" ") start_time = start_time.split(" ") start_time = datetime.strptime(replacing_date[0]+start_time[1],'%Y-%m-%d %H:%M:%S') Basically i have to change date on many places. It doesn't seems to be good thing in that case. and it can break if time string format changes. i can also break if the years end. for example date change to. start_time = '2023-01-01 22:00:00' -
Why Django celery throws me a key error, not sure why?
Not sure why it throws this key error. My project/celery.py: import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') my project/init.py: from .celery import app as celery_app __all__ = ('celery_app',) My app/tasks.py from celery import shared_task from celery.schedules import crontab from project.celery import app @shared_task def my_test(): print('Celery from task says Hi') app.conf.beat_schedule = { 'my-task-every-2-minutes': { 'task': 'my_test', 'schedule': crontab(minute='*/1'), }, } when I run the command: celery -A project beat -l info I can see the trigger every 1 min there [2022-12-22 12:38:00,005: INFO/MainProcess] Scheduler: Sending due task my-task-every-2-minutes (celery_app.my_test) when running celery -A project worker -l info and triggers sends info I get KeyError: my_test It seems that it cannot find the task with that key but from my info everything running fine : -------------- celery@192.168.1.131 v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- macOS-10.13.6-x86_64-i386-64bit 2022-12-22 12:43:22 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: project:0x10c757610 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- … -
Django: Template doesn't exist but on production
I have started another app inside my django project, and i already have multiple apps inside but only one return template doesnt exit but on production only, my project is deployed on heroku. I have done million of searches but couldnt find the solution. my static files and database are hosted on AWS here is some of my settings.py BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'erecruit', 'compensation', 'PMS', 'crispy_forms', 'forms_fieldset', 'django_filters', 'storages', 'gunicorn', 'foundation_filefield_widget', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], # 'DIRS': [BASE_DIR + "/templates", ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AWS_ACCESS_KEY_ID = 'xxxx' AWS_SECRET_ACCESS_KEY = 'xxx' AWS_STORAGE_BUCKET_NAME = 'xxxxx' AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = "storages.backends.s3boto3.S3StaticStorage" DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False AWS_S3_VERIFY=False AWS_S3_USE_SSL = False STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') django_heroku.settings(locals()) here is the view.py @login_required(login_url='loginPage') def home(request): perm = 0 for i in request.user.groups.all(): if i.name == 'PMSupervisors': perm = 1 if perm == 0: context = {} return render(request, 'PMS/pms_home.html',context) if perm == 1: … -
Нужно получить данные из IMG для товара(Need to get data from IMG for a product)
В общем мне нужно достать текст ссылки фото, чтобы погружать карточки для товаров. Есть вот эти таблицы моделей Product и IMG. Я как только не пытался доставать IMG_Product (там текст(ссылка на локальный источник). Пробовал наверное все, но может ошибаюсь. Мне нужно чтобы из таблицы IMG забрались нужные IMG_Product для продуктов, у которых Subcategory_id = 4 (допустим это шуруповерты) Модель: ` lass Product(models.Model): id = models.AutoField(primary_key=True) Name = models.TextField() Price = models.IntegerField() # Гарантия в числовом выражении. 1 = 1 месяц Guarantee = models.IntegerField() Count = models.IntegerField() Description = models.TextField() Manufactur_id = models.ForeignKey(Manufacturer, on_delete = models.CASCADE) Subcategory_id = models.ForeignKey(Subcategory, on_delete = models.CASCADE) def __str__(self): return "%s"%(self.Name) class IMG(models.Model): id_Product = models.ForeignKey(Product, on_delete = models.CASCADE,related_name='Products') IMG_Product = models.TextField() def __str__(self): return "%s"%(self.id_Product) Недоделанный шаблон {% for i in Screwdriver_list %} {% for j in Img_Screwdriver_list %} <div class="card" > <div> <div class="Top_card"> <span>{{i.id}}</span> <!-- <span>Код товара:12345678</span> --> <img class="favorites_img" src="{% static "/img/LikeIt.png" %}" alt="В Избранное"> <img src="/{% static "img/Стрелки-Сравнения.png" %}" alt=""> </div> </div> <div class="Midle_card"> <img class="Midle_img" src="{{j.IMG_Product}}" class="card-img-top" alt=""> <!-- <img class="Midle_img" src="{% static "/img/img_catalog/cordless screwdriver/51106745.jpg" %}" class="card-img-top" alt="/img/img_catalog/cordless screwdriver/51106745.jpg"> --> </div> <div class="card-body"> <div class="Card_text"> <a class="card-text" href="#"><span>Импульсный винтоверт Ryobi 18 В ONE+ R18iD3-0 5133002613</span></a> </div> <div class="Bottom_Card"> <h3>5955 р.</h3> … -
custom authentication backend that can support non-unique usernames [closed]
How should I customize the authentication model to set unique=False in the field set in USERNAME_FIELD? # models/user.py class User(SafeDeleteModel, PermissionsMixin): id = models.UUIDField("아이디", primary_key=True, default=uuid.uuid4) email = models.EmailField("이메일", max_length=255) name = models.CharField("이름", max_length=255) provider = models.CharField("소셜 계정 제공 서비스", max_length=100, null=True, blank=True, default=None, editable=False) provider_id = models.CharField("소셜 계정 고유 식별자", max_length=255, null=True, blank=True, default=None, editable=False) [enter image description here](https://i.stack.imgur.com/nDev8.png) USERNAME_FIELD = "email" class CustomBackend(ModelBackend): def authenticate(self, request, password=None, **kwargs): username = kwargs.get("username", None) if username is None: username = kwargs.get("email") if username is None or password is None: return try: print("UserModel._default_manager : ", UserModel._default_manager) user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user def get_user(self, user_id): try: user = UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None # settings/base.py AUTHENTICATION_BACKENDS = ["app.settings.backend.CustomBackend"] https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELD According to the django official document above I inherited ModelBackend and created a custom backend. [wanrring]enter image description here -
How to get One object value from database in Django
The situation is I have a table named Status consists of two fields. one is id which is primary key and based on auto increment and second is status which is integer. Now, the scenario is that I only want to get the value of status not id. Here are the details: views.py: from cvs.models import status_mod field_object = status_mod.objects.get(status) print(field_object) models.py: class status_mod(models.Model): id = models.BigIntegerField status = models.BigIntegerField class Meta: db_table = "status" The issue is that I want to store status value in a variable and want to call him in my template. Any solvable solution please -
legacy-install-failure when installing mysqlclient on mac
In django project I set the database as the rds mysql database and after running the server I got thie error django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Naturally I tried to install mysqlclient package with pip3 install mysqlclient and I'm running into this error. I also tried pip3 install mysqlclient --use-pep517 but it results a different error [ -
How do I access static files using Jinja in Django
I am using Jinja templating within Django and I am having trouble getting static files to load. I have tried setting up the back end per this documentation (I've included the code below): https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.jinja2.Jinja2 However, I am getting an "Encountered unknown tag 'static'" if I include a {% load static 'path' %} tag. If I include a {% load static %} tag, I get "Encountered unknown tag 'load'." error. I have setup a "jinja2.py" file in the main folder with the following code: from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse from jinja2 import Environment def environment(**options): env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, }) return env settings.py has the following code: TEMPLATES = [ { "BACKEND": "django_jinja.backend.Jinja2", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "environment": 'valuation.jinja2.environment', } }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Any guidance is very much appreciated. See above code for what I tried. -
Django's CORS_ALLOWED_ORIGINS and CORS_ALLOW_ALL_ORIGINS not working
I have a very strange problem with Django's corsheaders. I have tried all sorts of permutations and combinations by playing with all the possible settings but of no use. My current settings look like this: ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = ['*'] CORS_ALLOW_ALL_ORIGINS = True This is still causing the following error when the frontend sends an API request: has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I am not sure what else needs to be added, please let me know if I am missing anything here. I have already added 'corsheaders' in INSTALLED_APPS and also 'corsheaders.middleware.CorsMiddleware'in the MIDDLEWARE list (on top) I have tried adding domains one by one in the lists and verified by loading the changes, but still nothing worked. Even though I have now allowed for any origin and any host to send cross-origin requests, it is still throwing the CORS error. -
Can I use pretty-errors with gunicorn
I work on a project where in development I run a django webapp in gunicorn on docker. I want to use pretty-errors or any other tool that gives me pretty stacktrace. I have installed it and it works in the docker container because I can use it when I start a python shell. However when I start gunicorn instead of python, the stacktrace doest use pretty-errors. So does gunicorn interfere with pretty-errors? -
How to get the CSS rules that a Django Template would use?
Let's just say I have a basic class-based view like: from django.views.generic import TemplateView class HomePage(TemplateView): template_name = "homepage.html" and in homepage.html of course we load some CSS, apocryphally: {% extends "base.html" %} {% load static %} {% block CSS %} <link rel="stylesheet" type="text/css" href="{% static 'css/default.css' %}" /> <link rel="stylesheet" type="text/css" href="some CDN based CSS file' %}" /> {% endblock %} Now I'd like the view to read/load the CSS that will be sent to the client. If we could just find the source files, we could parse them with cssutils. And of course it's technically possible to find and parse the template file too, but Django already implements that and has a template loader. Is there any way short of rendering the template into a string, and trying to parse the HTML to extract CSS rules? And even if that's the path we need to pursue, is there a package that will given rendered HTML, and return the CSS rules? An interesting problem arises from the need, server-side, to extract some CSS information, notably colours. -
Problem in creating dynamic form fields in Django App using crispy form
I have one Model Given as below:- class FeeItemAmount(models.Model): id = models.AutoField(primary_key=True) fee_item = models.ForeignKey(FeeItem, on_delete=models.CASCADE) class_obj = models.ForeignKey(Classes, on_delete=models.CASCADE) amount = models.IntegerField() For creating new item I wanted to populate the Classes objects from model and based on that we will show the Form fields. One amount field for each class. In code I am doing that by:- name = forms.CharField(label="Name", max_length=100) months_list = forms.MultipleChoiceField(label='Months', widget=forms.CheckboxSelectMultiple,choices=months_name_list) due_date = forms.IntegerField(label="Due Date",required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) classes = Classes.objects.all() for class_obj in classes: field_name = 'class_%s' % (class_obj.id,) self.fields[field_name] = forms.IntegerField(label=class_obj.name,required=False) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.form_tag = False self.helper.label_class = 'col-sm-3' self.helper.field_class = 'col-sm-9' self.helper.layout = Layout( Div( Div('name', css_class='form-group col-sm-6 mb-0 border border-secondary'), Div('due_date', css_class='form-group col-sm-6 mb-0 border border-secondary'), css_class='form-row'), Div( Div(InlineCheckboxes('months_list'), css_class='form-group col-sm-12 mb-0 border border-secondary'), css_class='form-row'), Div( HTML("<p> Provide Amount for following Classes for this Fee Item:</p>"), css_class='form-row'), ) Now the problem is that those dynamically created fields are not showing in the Form. If I remove the Layout part of the code than those fields are showing but than it is not in the format that i want. I am new to Django and crispy form. I searched on google for this. One … -
How to allow CORS from Axios get request in Django backend?
I've been looking for a solution to this problem but nothing seems to work. I've arrived at the django-cors-headers package but can't get it to work. I'm sending an axios request form my vue frontend: axios.get('data/') .then(res => { console.log(res) }) but it throws a 200 network error error: Access to XMLHttpRequest at 'http://localhost:8000/data/' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. GET http://localhost:8000/data/ net::ERR_FAILED 200 AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …} code : "ERR_NETWORK" config : {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Network Error" name : "AxiosError" request : XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …} stack : "AxiosError: Network Error\n Django backend I am redirecting the incoming request in myProject/urls.py: from django.urls import path, include urlpatterns = [ path('', include('myApp.urls')), ] to myApp/urls.py: from django.urls import path from . import views urlpatterns = [ path('data/', views.getData) ] which invokes myApp/views.py: from … -
DJANGO - The view location_form.views.Insertrecord didn't return an HttpResponse object. It returned None instead
I am having this error constantly - The view location_form.views.Insertrecord didn't return an HttpResponse object. It returned None instead. I have tried indenting it in all ways possible. And i have a created another view in similar manner and that worked. Can someone tell where am i going wrong? I want to store the data of this form in my database which is phpmyadmin (mysql) views.py from django.shortcuts import render from .models import Location from django.contrib import messages # Create your views here. def Insertrecord(request): if request.method=='POST': if request.POST.get('id') and request.POST.get('parent_id') and request.POST.get('name') and request.POST.get('status') and request.POST.get('added_by') and request.POST.get('updated_by') and request.POST.get('created_on') and request.POST.get('updated_on') : saverecord=Location() saverecord.id=request.POST.get('id') saverecord.parent_id=request.POST.get('parent_id') saverecord.name=request.POST.get('name') saverecord.status=request.POST.get('status') saverecord.added_by=request.POST.get('added_by') saverecord.updated_by=request.POST.get('updated_by') saverecord.created_on=request.POST.get('created_on') saverecord.updated_on=request.POST.get('updated_on') saverecord.save() messages.success(request,"Record Saved Successfully..!") return render(request, 'location.html') else: return render(request,'location.html') location.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Location Registration Form</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <nav class="navbar bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#"> <img src="https://img.freepik.com/premium-vector/customer-service-icon-vector-full-customer-care-service-hand-with-persons-vector-illustration_399089-2810.jpg?w=2000" alt="" width="30" height="24" class="d-inline-block align-text-top"> Location Registration Portal </a> </div> </nav> </head> <body background="https://img.freepik.com/free-vector/hand-painted-watercolor-pastel-sky-background_23-2148902771.jpg?w=2000"> <br> <h1 align="center">Location Registration Portal</h1> <hr> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <div class="container-sm"> <form method = "POST"> {% csrf_token %} <div class="row mb-3"> <label for="inputEmail3" class="col-sm-2 col-form-label">Country</label> <div class="col-sm-10"> <input type="text" name="name" class="form-control" id="inputEmail3"/> … -
How can I send E-Mails through python django frequently with a cronjob?
I try to run a function in django every 5 minutes. For this I user the django-crontab package. The function which should run, checks for some conditions in the database and if they are met, sends an e-mail to the user of the app. I have django 4 running on my linux ubuntu 20.04 server. I added the cronjob via python3 manage.py crontab add (in activated virtual environment). But then I wondered why the cronjob is not running. I tried to execute the job by hand and it worked. I think the problem boils down to this: When I'm in the activated virtual environment and run the crontab with "python3 manage.py crontab run " it works. But when I run it outside of the virtual environment I get the following error: Failed to complete cronjob at ('*/5 * * * *', 'evaluation_tool.scripts.cron.send_mail_if_classeval_ended') Traceback (most recent call last): File "/var/www/amadeus/lib/python3.10/site-packages/django_crontab/crontab.py", line 145, in run_job func(*job_args, **job_kwargs) File "/var/www/amadeus/evaluation_tool/scripts/cron.py", line 12, in send_mail_if_classeval_ended send_mail_time_over_class_evaluation(class_evaluation=class_evaluation.pk, File "/var/www/amadeus/evaluation_tool/scripts/email_handler.py", line 122, in send_mail_time_over_class_evaluation send_falko_mail("AMADEUS Evaluation abgeschlossen", message, to_email_address) File "/var/www/amadeus/evaluation_tool/scripts/email_handler.py", line 34, in send_falko_mail msg.send(fail_silently=False) File "/var/www/amadeus/lib/python3.10/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "/var/www/amadeus/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() File "/var/www/amadeus/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line … -
ModuleNotFoundError: No module named 'LS.settings'
ModuleNotFoundError: No module named 'LS.settings' LS is my project name File "C:\Users\user\Desktop\LS\venv\Lib\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'LS.settings' I tried to change my settings.py file and wsgi.py too.. but nothing worked In settings.py import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.Path.dirname(os.Path.dirname(os.Path.dirname(__file__))) -
"id" vs "pk" in django orm query [duplicate]
What is the actual difference between "id" and "pk" in Django, and which one is more preferable to use? Student.objects.get(id=20) Student.objects.get(pk=20) -
setting cookies with react-cookies to be read by DRF API
I want to set/remove a cookie on react web app when client switches between modes. I want the cookie to be sent with every request to the API which is using django rest framework, and use the value of the cookie to determine the kind of response. The web app and API are in different domains. I'm using react-cookie library to set the cookie which works fine on localhost but having issues setting it in other domains and will only let me use current domain for the cookie. setCookie('is_test',true,{domain:document.domain.match(/.[^.]*\.[^.]*$/)?.[0]||document.domain,path:'/'})} Thats the code I'm using to set the cookie, the regex is something I found to remove the subdomain (ex. www.testdomain.com converts to .testdomain.com) if there is any or just set the domain if its something like localhost but when it is deployed to the actual domain the cookie doesn't get set. Also will the backend API read the cookie if the domain is set with the client domain or does it need to be the server domain that is used for the request. It doesn't let me use other domains outside of the current(client) domain -
Passing HTML tag data- to Django with form submit
I am trying to pass data in HTML tag with a form submit to Django I currently have a template like this: {% for item in items %} <div class="product"> {{ item.item_name }} <form method="POST"> {% csrf_token %} <input type="submit" value="add to cart" data-pk="{{item.pk}}" class="add_product"/> <form> </div> {% endfor %} I want to pass data-pk with a Django form. How do I do that? Also I know, I can create a view to handle endpoint to do that, and include pk in the url, is that a better solution? I am new to Django, and I will be grateful for any input on how to do stuff the right way -
I can't Create Second Video in the Django-Rest-Framework
I'm using the Django and React to create YouTube clone. And when the user is creating second video, it giving the bad request error: <QueryDict: {'title': ['Edit Test56'], 'description': ['is It working1643'], 'user': ['3'], 'image': [<TemporaryUploadedFile: slackphot.png (image/png)>], 'video': [<TemporaryUploadedFile: video-for-fatube.mp4 (video/mp4)>]}> Bad Request: /api/admin/create/ When I tried to make post request in postman, it gave me views.py Views of the api. class CreateVideo(APIView): #permissions_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): print(request.data) serializer = VideoSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py Video Serailzier. class VideoSerializer(serializers.ModelSerializer): user_name = CharField(source="user.user_name", read_only=True) class Meta: model = Video fields = ["id", "title", "image", "video", "description", "date_added", "is_active", "user", "user_name", "likes"] models.py Model of the Video class Video(models.Model): title = models.CharField(max_length=50) image = models.ImageField(_("Image"), upload_to=upload_to, default="videos/default.jpg") video = models.FileField(_("Video"), upload_to=upload_to, default="videos/default.mp4") user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_channel" ) description = models.CharField(max_length=255) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='video_post', null=True, blank=True) date_added = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) If you want to look at the whole project, here is github: https://github.com/PHILLyaHI/diplom-work