Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple Django Projects on Apache Server with mod_wsgi is trying to load wrong project libraries?
I'm trying to run multiple Django projects on one server. The server is Windows and I am using mod_wsgi with Apache. Normally, each project lives on it's own server and everything works great - but for dev/staging purposes I am trying to just serve them all from the same server (I've done this successfully with other groups of projects on another server, but they were Flask applications) My structure looks similar to this: ProjectA (this project contains the authentication / login / logout) - appa1 (shared templates / static files) - appa2 ProjectB - appa1 (shared templates / static files) - appb1 - appb2 ProjectC - appa1 (shared templates / static files) - appc1 - appc2 My VirtualHost setup is pretty straightforward: <VirtualHost dev.projecta.mydomain.com:80> ServerName dev.projecta.mydomain.com Redirect / https://dev.projecta.mydomain.com </VirtualHost> <VirtualHost dev.projecta.mydomain.com:443> ServerName dev.projecta.mydomain.com WSGIScriptAlias / "C:/projecta/projecta.wsgi" CustomLog "logs/projecta_access.log" common ErrorLog "logs/projecta_error.log" SSLEngine on SSLCertificateFile "C:/path/to/projecta_cert/cert.cer" SSLCertificateKeyFile "C:/path/to/projecta_cert/project.key" <Directory C:\projecta> Require all granted </Directory> </VirtualHost> <VirtualHost dev.projectb.mydomain.com:80> ServerName dev.projectb.mydomain.com Redirect / https://dev.projectb.mydomain.com </VirtualHost> <VirtualHost dev.projectb.mydomain.com:443> ServerName dev.projectb.mydomain.com WSGIScriptAlias / "C:/projectb/projectb.wsgi" CustomLog "logs/projectb_access.log" common ErrorLog "logs/projectb_error.log" SSLEngine on SSLCertificateFile "C:/path/to/projectb_cert/cert.cer" SSLCertificateKeyFile "C:/path/to/projectb_cert/project.key" <Directory C:\projectb> Require all granted </Directory> </VirtualHost> <VirtualHost dev.projectc.mydomain.com:80> ServerName dev.projectc.mydomain.com Redirect / https://dev.projectc.mydomain.com </VirtualHost> <VirtualHost dev.projectc.mydomain.com:443> ServerName dev.projectc.mydomain.com … -
Define how to print param
i wont to save in a db a int data, and print a string when i call it. i have a model like this: class Flats(models.Model): title = models.CharField(max_length=50, unique=True, verbose_name="Titolo") description = models.TextField(blank=True, verbose_name="Descrizione") floor = models.SmallIntegerField(blank=True, default=0, verbose_name="N° piano") i wont that when i call floor return not a number but a string. how it is possible?? -
Running a celery task outside the django framework
I have a django/celery application that is working fine. In normal operations tasks get created and inserted into the worker queues as expected. I am trying to create a separate python script that will be run manually, that is attempting to insert a task into the worker queue... and it is not working. The test function is simple: @shared_task() def testtask(num=100, tag=0): for i in range(num): print_log("in testtask {0} {1}".format(i, tag)) time.sleep(1) return From the python3 prompt, I do the following: >>> os.environ.setdefault("DJANGO_SETTINGS_MODULE", "raxakprotect.settings.dev") >>> import django >>> django.setup() >>> from test import testtask # test has other django dependencies hence the django.setup() >>> testtask(10) # This works fine... but >>> testtask.delay(10) # hangs indefinitely Don't know why this is the case. Do I have to connect separately to the celery broker somehow? Watching celery events screen shows no events or entries being created. Thanks --prasanna -
How to provide a simple download section with sub folders in Django
I am trying to provide a simple download section via Django that lists files and sub folders and allows for downloading. I am using pythonanywhere for this. Here is my Link with the error: https://futureforest.eu.pythonanywhere.com/download/ Application name: servedownload views.py in servedownload: from django.shortcuts import render import os from django.http import FileResponse, Http404 def download_folder(request, path=''): # Set the file path to the directory you want to serve for download folder_path = os.path.join('/home/futureforest/webinterface/media/download', path) # Check if the folder exists, and raise a 404 error if it doesn't if not os.path.exists(folder_path): raise Http404('Folder not found') # Get a list of all the files and directories in the folder contents = os.listdir(folder_path) # Create empty lists for files and subdirectories files = [] subdirectories = [] # Iterate through the contents of the folder for item in contents: item_path = os.path.join(folder_path, item) # If the item is a file, add it to the list of files if os.path.isfile(item_path): files.append(item) # If the item is a directory, add it to the list of subdirectories elif os.path.isdir(item_path): subdirectories.append(item) # Recursively retrieve files from subdirectories subfiles = [] for subdirectory in subdirectories: subfiles.extend(download_folder(request, os.path.join(path, subdirectory))) # Combine the files in the current directory with the … -
API call to django server in my React app is returning invalid Json
I'm trying to connect my frontend react with backend django apps. In django, I defined my model database: from django.db import models class Departments(models.Model): DepartmentId = models.AutoField(primary_key=True) DepartmentName = models.CharField(max_length=100) my serializer: from rest_framework import serializers from EmployeeApp.models import Departments class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Departments fields = ('DepartmentId', 'DepartmentName') and my views: from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from EmployeeApp.models import Departments from EmployeeApp.serializers import DepartmentSerializer @csrf_exempt def departmentApi(request, id=0): if request.method == 'GET': departments = Departments.objects.all() department_serializer = DepartmentSerializer(departments, many=True) return JsonResponse(department_serializer.data, safe=False) elif request.method == 'POST': department_data = JSONParser().parse(request) department_serializer = DepartmentSerializer(data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Added Successfully!", safe=False) return JsonResponse("Failed to Add...", safe=False) elif request.method == 'PUT': department_data = JSONParser().parse(request) department = Departments.objects.get(DepartmentId = department_data['DepartmentId']) department_serializer=DepartmentSerializer(department, data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Updated Sucessfully!", safe=False) return JsonResponse("Failed to update!", safe=False) elif request.method == 'DELETE': department = Departments.objects.get(DepartmentId=id) department.delete() return JsonResponse("Deleted Succefully!", safe=False) my urls: from django.urls import path from EmployeeApp import views urlpatterns = [ path('department', views.departmentApi), path('department/<int:id>', views.departmentApi) ] my django server runs on http://127.0.0.1:8000/, so I put it in my .env in the react app folder: REACT_APP_API_DEPARTMENT = http://127.0.0.1:8000/department and imported it to use on my Department.jsx component: … -
How to concat the django template variable in the jQuery html string for appending dynamically to the body
From the table, I can fetch the ID of the user, to get the first_name of the user, I have to get it from another table, to do this task I follow related_name method. for example, {{ data.custom_user.user_profile.first_name}} where user_profile is the related_name in the model. It works perfectly with html but how to do this if I am getting user ID from the ajax to jQuery ? Below is how I tried to concat the django variable in jQuery . jQuery(getElement).fadeOut(function () { jQuery(getElement).replaceWith("<p><span style='font-size: 15px; color: #008628;'><a href='#'>'"+{{res['new_comment'][0]['id'].master_user_profile.first_name}}+"'</a> – </span>"+res['new_comment'][0]['content']+"<span style='color: green;''><i class='la la-calendar-o'></i> Jan 16, 2016 07:48 am</span></p><p onclick='getInputElement(this);'id='{{question.id}}'>Add a comment</p>"); }).fadeIn(); } }); But it's not working. Please anyone let me know. -
Installing a version of Django REST framework that is compatible with Django 4+
I am in the process of upgrading from Django 3.2 to Django 4.0. When I do so, I get the following error: ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' And the error seems to stem from this import: from django.utils.translation import ugettext_lazy as _ in rest_auth/registration/serializers.py I'm currently running Django 4.0.10 with djangorestframework 3.13.0, and I'm a bit confused because according to Django REST framework's release notes v3.13.0 should support Django 4.0 (I also tried v3.14.0, same results). What am I missing here? -
combined use of RedirectView and i18n_patterns in Django 4.0.3
I am having problems using RedirectView inside i18n_patterns in my urls.py file. My current situation is this: urlpatterns = i18n_patterns( path('', RedirectView.as_view(url='/home/', permanent=True)), path('adm/', admin.site.urls), path('rosetta/', include('rosetta.urls')), path('home/', include(('home.urls', 'home'), namespace='home')), ) What happens is that if I connect to my site (for this example mysite.com) I am not redirected to mysite.come/home, nor even to mysite.com/en/home. If I remove i18n_patterns urlpatterns = [ path('', RedirectView.as_view(url='/home/', permanent=True)), path('adm/', admin.site.urls), path('rosetta/', include('rosetta.urls')), path('home/', include(('home.urls', 'home'), namespace='home')), ] and I connect to mysite.com I am correctly redirected to mysite.com/home and the site works correctly. I have recently implemented i18n for the first time so I am not familiar with the topic. I tried splitting urlpatterns into two but got no results: urlpatterns = [ path('', RedirectView.as_view(url='/home/', permanent=True)), ] urlpatterns += i18n_patterns( path('adm/', admin.site.urls), path('rosetta/', include('rosetta.urls')), path('home/', include(('home.urls', 'home'), namespace='home')), ) -
Passing Value to create initial value in form
I am trying to create a center of a project (foreign key). However, when I call the url to create a center the project which this center should belong to is not automaticly set. So the user has to choose the project. The goal is to prefill the form element 'Project' with the name of the Project the id of which is specified in the url, the last element of the url is the id of the project as seen here: http://192.168.10.84:8080/procure/centercreate/5 Therefore I have to look up the name of the project with id 5, fill the form element and make it none editable. what I have so far. model of center: class Center(models.Model): CenterName = models.CharField(max_length=60, null=False) Project = models.ForeignKey(Project,on_delete=models.CASCADE) def __str__(self): return self.CenterName in the url.py path('centercreate/<int:pk>', views.CenterCreate.as_view(), name='center_create'), in the views.py: class CenterCreate(CreateView): model = Center form_class = CenterCreateForm template_name = 'Procure/center_create.html' def get_success_url(self): return reverse('centers_sys', kwargs={'pk':self.object.Project_id}) connected form I use: class CenterCreateForm(forms.ModelForm): class Meta: model = Center fields = "__all__" template used: {% extends "base_generic.html" %} {% block content %} <div id="container" > {% if user.is_authenticated %} <p>Welcome to ProcEdu - developed by <em>BZG</em>!</p> <h3>You are adding a Center to Project: <!-- PROJECT -->> </h3> … -
Django web app. werid theme toggle button
I'm developing a Django web app. If I try to access to the admin site there is a new button for selecting theme color. This button is not displayed properly. Here a screenshot: I didn't add any third party plugin about admin themes and I don't know which part of code you need to investigate the problem. Here you can find the installed packages of my python virtual env: asgiref==3.6.0 autopep8==2.0.2 beautifulsoup4==4.11.1 black==23.3.0 certifi==2022.12.7 charset-normalizer==3.1.0 click==8.1.3 colorama==0.4.6 defusedxml==0.7.1 diff-match-patch==20200713 Django==4.2 django-address==0.2.8 django-crispy-forms==1.14.0 django-filter==22.1 django-import-export==3.0.2 et-xmlfile==1.1.0 idna==3.4 MarkupPy==1.14 mypy-extensions==1.0.0 numpy==1.23.5 odfpy==1.4.1 openpyxl==3.0.10 packaging==23.1 pandas==1.5.1 pathspec==0.11.1 platformdirs==3.5.0 psycopg2==2.9.5 psycopg2-binary==2.9.5 pycodestyle==2.10.0 PySimpleGUI==4.60.4 python-dateutil==2.8.2 python-decouple==3.8 pytz==2022.6 PyYAML==6.0 requests==2.29.0 scipy==1.9.3 six==1.16.0 soupsieve==2.3.2.post1 sqlparse==0.4.3 tablib==3.3.0 tzdata==2022.6 urllib3==1.26.15 xlrd==2.0.1 XlsxWriter==3.1.0 xlwt==1.3.0 Here you can find my settings.py without sensitive data: """ Django settings for warehouseproject project. Generated by 'django-admin startproject' using Django 4.1.3. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os from django.urls import reverse_lazy from decouple import config, AutoConfig from django.contrib.messages import constants as messages # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent config = AutoConfig(search_path=".env") # Quick-start development settings - unsuitable … -
Will a Django Webapplication work on a Hostpoint standard Webserver?
I can't seem to find any confirmation anywhere that the standard webhosting service for HostPoint will be able to host my Django project. They seem to suggest I need a Managed Server to run my project, is that the case? I'm kind of new to all of this so I'm sorry if this is a stupid question. I've rummaged through hostpoint's site and can't find anything that helps me further, I've even written an email to hostpoint themselves but still haven't gotten an answer. -
Matplotlib and mpld3: how to show the corresponding y value of line plot in a tooltip based on hover x value?
I'm creating a graph in which I would like to show the Y value of the plot in a tooltip based on the hover x value. For this I am using Python with libraries: Matplotlib and mpld3. In my current version I have the tooltip showing up when I hover the line in the graph but I want it to show up when I just hover over the graph. For your visual presentation: This is what I have now (mouse hovering in red circle): My mouse is hovering in the red circle But I would like it to already show up when I hover above or below it like you can see in next picture. If I hover here I want the tooltip also to show with current hover x value and corresponding y value of the blue line I used the plugins.PointHTMLTooltip and it's working but only when I hover over the blue line, not when I just hover over the graph. -
Getting error [password authentication failed for user] while encrypt DB credential in Django
Hi Everyone i am working on django framework my credential store in config.ini file but when i encrypt my db password and run server getting 500 error in log showing password authentication failed for user this will happen when i encrypt db password and store in same config.ini file bt i store new config.ini file it will work but i need to store db password encryption in existing config.ini file please help me out. settings.py from cryptography.fernet import Fernet key = Fernet.generate_key() with open('key.key', 'wb') as key_file: key_file.write(key) # Define encrypt def encrypt(value): with open('key.key', 'rb') as key_file: key = key_file.read() f = Fernet(key) return f.encrypt(value.encode()).decode() #Define decrypt functions def decrypt(value): with open('key.key', 'rb') as key_file: key = key_file.read() f = Fernet(key) return f.decrypt(value.encode()).decode() # Read config file:------------------------------------------------------------ config = RawConfigParser() config.read(os.path.join(config_path, 'config.ini')) DB_PASSWORD = config['db_setting']['DB_PASSWORD'] encrypt_db_password=encrypt(DB_PASSWORD) # update config.ini file with encrypt_db_password config.set('db_setting','DB_PASSWORD', encrypt_db_password) with open('utility\config.ini', 'w') as config_file: config.write(config_file) #decrypt db_password decrypted_db_password = decrypt(encrypt_db_password) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': DB_USER, 'PASSWORD': decrypted_db_password, 'HOST': DB_HOST, 'PORT': DB_PORT, 'CONN_MAX_AGE': MAX_CONNECTION_AGE, 'OPTIONS': {'options': '-c search_path=' + SCHEMA + ',public'} } try to encrypt decrypt db password i will work when db credential store new config.ini file … -
ProgrammingError at /tasks/ (1146, "Table 'database.tasks_task_parent_task' doesn't exist")
I'm trying to join a table to itself using many-to-many. I keep getting an error that the table does not exist Model class Task(models.Model): title = models.CharField(max_length=255) description = models.TextField() percentage_of_realization = models.IntegerField() parent_task = models.ManyToManyField("Task", default=None) Migration: migrations.CreateModel( name='Task', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('description', models.TextField()), ('percentage_of_realization', models.IntegerField()), ('parent_task', models.ManyToManyField(default=None, to='tasks.task')), ], ) I tried to write tasks in different ways like without "" or like tasks.task and modify with migrations, but nothing worked -
Displaying related data from two or more tables in a DetailView
I did not find information on how all named arguments **kwargs are passed in the overridden "get_context_data" method in the view call. There are 3 models: class User(models.Model): email = models.CharField(unique=True) company_id = models.IntegerField(blank=True, null=True) first_name = models.CharField(blank=True, null=True) last_name = models.CharField(blank=True, null=True) class Company(models.Model): logo = models.CharField(blank=True, null=True) name = models.CharField(blank=True, null=True) full_name = models.CharField(blank=True, null=True) address = models.CharField(blank=True, null=True) phone = models.CharField(blank=True, null=True) email = models.CharField(blank=True, null=True) kpp = models.CharField(blank=True, null=True) okved = models.CharField(blank=True, null=True) bik = models.CharField(blank=True, null=True) class Order(models.Model): user_id = models.IntegerField(blank=True, null=True) amount_total_cents = models.BigIntegerField() amount_mean_cents = models.BigIntegerField() created_at = models.DateTimeField() Communication between models: Company-User 1 to M, User-Order 1 to M There are no problems with direct output of data in the view without overriding the "get_context_data" method. However, there are no problems when overriding the method and linking two tables through the primary key: 1. company/urls.py urlpatterns = [ path('company/<int:pk>', CompanyShow.as_view(), name='company_show') ] company/views.py class CompanyShow(DetailView): model = Company template_name = 'company/company_show.html' context_object_name = 'company' def get_context_data(self, **kwargs): context = super(CompanyShow, self).get_context_data(**kwargs) context['users'] = User.objects.filter(company_id = self.kwargs['pk']) return context company_show.html <p>ID: {{ company.id }}</p> <p>Name: {{ company.name }}</p> <p>Members: {% for user in users %} <li> <a href="{% url 'user:user_show' user.id %}">{{ user … -
How to run a query with an inner query in it in Django?
I'm trying to run a query with an inner query in it as shown below: # Inner query Product.objects.filter(category__in=Category.objects.get(pk=1)) But, I got the error below: TypeError: 'Category' object is not iterable Also, I'm trying to run a query with an inner query in it as shown below: # Inner query Product.objects.filter(category=Category.objects.filter(pk=1)) But, I got the error below: ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. So, how can I run these queries above with inner queries in them? -
How to make form fill and submit in bootstrap modal?
I can't figure out what the problem is, please help. I have a button, when clicked, a modal window opens, in which a form for adding an entry is displayed, but when the "save" button is clicked, the page reloads, but nothing is saved. I added my code below. If I make a form on a new page (localhost:8000/add_department/7), then the form is saved and everything works, but not in the modal window. base.html: <button class="btn btn-success btn-add btn-padding-left btn-add-department" data-bs-toggle="modal" data-bs-target="#button-department-add" data-url="{% url 'department_add' 7 %}"><i class="fa fa-plus"></i> Add department</button> <div class="modal fade" id="button-department-add" tabindex="-1" role="dialog" data-bs-backdrop="static"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content modal-department"> </div> </div> </div> add_department.html: <form action = "" method = "post"> <div class="modal-header"> <h5 class="modal-title">Add department</h5> <button class="btn-close" type="reset" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" style="text-align: center;"> <b>Press "save".</b> <br> <br> {% csrf_token %} {{ form.as_p }} {{ answer }} </div> <div class="modal-footer"> <button type="submit" class="btn btn-success btn-save"><i class="fa fa-save"></i> Save</button> <button type="reset" class="btn btn-secondary btn-cancel" data-bs-dismiss="modal"><i class="fa fa-ban"></i> Cancel</button> </div> </form> views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Region, Department from .forms import * from django.forms.models import model_to_dict from .forms import * from django.db import models from django.contrib.auth.decorators import login_required … -
can't load image from model via css background-image in my html page
can't load image from model via css background-image in my html page , i want to load image from model that i upload it to my html page via background-image in css my model : class Home_options(models.Model): background_img = models.ImageField(upload_to='images/',null=True, blank=True) your_small_img = models.ImageField(upload_to='images/',null=True, blank=True) # Background img def get_background_img(self): if self.background_img and hasattr(self.background_img, 'url'): return self.background_img.url else: return '/path/to/default/image' # your_small_img def get_your_small_img(self): if self.your_small_img and hasattr(self.your_small_img, 'url'): return self.your_small_img.url else: return '/path/to/default/image'` my css : .header { background-image: -webkit-linear-gradient(bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('{{ home_options.get_background_img.url }}'); background-image: linear-gradient(to top, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('{{ home_options.get_background_img.url }}'); }` i tried to use home_options.get_background_img.url and home_options.your_small_img.url but they not work -
`FOREIGN KEY` on PlanetScale
I want to deploy a Django app on Vercel which uses PlanetScale as database. But since PlanetScale does not support foreign key and the Django works heavily with this constraint. So my question is there is any way that solves this problem ? I tried db_contraint setting to False like models.ForeignKey(Buses, on_delete=models.CASCADE, db_constraint=False) this for my models but this also not working. -
VARIABLE and DJANGO
I'm working on a project, in one function I make a random password, in another I want to send it. In the function where I generate a random password, I want to pick up a variable and put it in the function where I send it, but I know that Python does not allow this. Please tell me options on how to get around this and so that VIEW-PASSWORD can send a variable from VIEW-CONTACT def password(request): thepassword = '' for x in range(lenght): thepassword += random.choice(characters) return render(request, 'generator/password.html', {'password': thepassword}) MY CODE! (TWO VIEWS) VARIABLE "thepassword" i want give in func CONTACT def contact(request): sender = '\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*' password = '\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*' if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Subject: YOUR PASSWORD" body = { 'first_name': form.cleaned_data['first_name'], 'last_name': form.cleaned_data['last_name'], 'email': form.cleaned_data['email_address'], } message = "Your generated password is -\n" + "\n".join(body.values()) server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() try: server.login(sender, password) server.sendmail(sender, form.cleaned_data['email_address'], f"{subject}\n {---!!!I WANT RETERN HERE MY VARIABLE--- >>>'thepassword'}") except BadHeaderError: return HttpResponse('Incorrect title found') return redirect("home") form = ContactForm() return render(request, "generator/contact.html", {'form': form}) -
Exclude user from an annotation query
I'm trying to query the users presents in a certain conversation. I finally got it working with this annotation: products = products.annotate( conversation_users=Subquery( Conversation.objects.filter( product=OuterRef('pk') ).annotate( users_array=ArrayAgg('users__username') ).values_list('users_array', flat=True)[:1] ) ) This is returning a list with the user present in the conversation (in most cases only two). I need to exclude from there the request.user so I get always the value of the user who I am having the conversation with. I tried using this Q query trying to exclude the request.user: .filter(~Q(users=user)).values_list('users_array', flat=True)[:1] ) but it is making the field now return None. How can I accomplish that? Edit 1: Those are the relevant models, Product model: class Product(models.Model): creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name='anken') content = models.TextField(blank=True, null=True) date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) intouch = models.ManyToManyField( User, related_name='product_intouch', blank=True) And this is the Conversation model: class Conversation(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='conversations') users = models.ManyToManyField(User, related_name='conversations') def validate_unique(self, *args, **kwargs): super().validate_unique(*args, **kwargs) if Conversation.objects.filter(product=self.product, users__in=self.users.all()).exists(): raise ValidationError( 'A conversation with the same Product and user already exists.') -
Using sass preprocessor with a django+svelte project
I am creating a project using django and svelte framework mainly, I was wondering if it is possible to use sass preprocessor within my svelte components(not in the css files that are located in the static folder). I want to use it directly in the svelte component not in any other files. What is usually do is write code in svelte, build the code using "npm run build" then run the django server. Whenever I try to add sass by changing the rollupconfig, the command "npm run build" breaks and start giving error. Here is the files, in case you want to take a look. https://github.com/Ayush-vachhani/django_template/ -
Django Email Domain Validation with cleaned_email function works very slow after submitting
Hi i am trying to write email domain validation for sign up form in django syntax with following function code. I am using the function inside class meta: VALID_DOMAINS is a list = ['gmail.com', 'hotmail.com'] I am using Edge browser for test def clean_email(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) original_email = self.cleaned_data['email'] domain = self.cleaned_data["email"].split("@")[-1] if domain not in VALID_DOMAINS: raise ValidationError("E-mail addresses from %(domain)s are not allowed.", code="invalid", params={"domain": domain}) return original_email Problems are: After typing this function, sign up page works very slow when trying to check with any wrong domain (any outside of VALID_DOMAINS). (after submitting the form) After submitting sign up form with the wrong email domain, sign up from is not returning its original shape which is before submitting. There are also happening small corruptions, and password fields act as if passwords are not typed. I was not expecting to work very slow after submitting form. -
Celery console doesn't output a task result (Django / Redis)
While learning Celery stuck just on a running any task. My machine runs on Windows 11. To arrange a connection between Celery and Redis I've started a Docker container (using Docker desktop + WSL). Set Redis port for 6379. Created celery.py in project default app robot (same folder as settings.py) : import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'robot.settings') app = Celery('robot') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() In the settings.py line added : CELERY_BROKER_URL = 'redis://localhost:6379/0' In the project's default app robot __init__ added lines: from .celery import app as celery_app __all__ = ['celery_app'] In custom django app user created tasks.py and following func for test: from celery import shared_task @shared_task() def simple_task(): print("SOME RESULT") When I run command in PowerShell celery -A robot worker I only get a message: [2023-05-10 12:42:23,232: WARNING/MainProcess] C:\Users\kosan\Documents\Python\venvs\robot_dreams_study\django\Lib\site- packages\celery\fixups\django.py:203: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! Then I try to run a task (simple task with just printing a word) with Django Shell. As result I get an output in Django Shell: >>> simple_task.delay() <AsyncResult: a58d1627-7469-4a7a-b761-bca74dcb00c2> And that's all. No any output in celery consol or somewhere else. I have tried to run celery with celery -A robot … -
Celery beat cannot update currency exchange rates with django-money
I use django-money, then I ran celery beat to update currency exchange rates every 60 minutes with the code below. *I followed django-money doc: # "core/celery.py" import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('core') 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}') # "core/tasks.py" from celery import shared_task from djmoney import settings from django.utils.module_loading import import_string @shared_task def update_rates(backend=settings.EXCHANGE_BACKEND, **kwargs): backend = import_string(backend)() backend.update_rates(**kwargs) print("Successfully updated") # "core/settings.py" from celery.schedules import crontab OPEN_EXCHANGE_RATES_APP_ID = '5507ba2d9b8f4c46adca3169aef9c281' # Here CELERY_BEAT_SCHEDULE = { 'update_rates': { 'task': 'core.tasks.update_rates', 'schedule': crontab(minute='*/60'), 'kwargs': {} # For custom arguments } } But, I got the error below even though I set OPEN_EXCHANGE_RATES_APP_ID in settings.py as shown above: django.core.exceptions.ImproperlyConfigured: settings.OPEN_EXCHANGE_RATES_APP_ID should be set to use OpenExchangeRatesBackend So, how can I solve the error to update currency exchange rates every 60 minutes with celery beat?