Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Transaction affects time of computation?
Consider: with transaction.atomic(): job = Job.objects.select_for_update().get(id=job_id) texts = pickle.loads(job.job_body) timer = Timer() print("Computing embedding for:", texts, flush=True) job.started = ms_now() result = get_embeddings_raw(texts) # no database communication. job.finished = ms_now() print("Done computing embedding for:", texts, timer.stop(), flush=True) job.result = pickle.dumps(result) job.save() The computation within the transaction does not communicate with the database. Nonetheless, when I do not use concurrency, this computation takes ~70ms, but when there are up to ten simultaneous workers, it takes ~4,000ms. Can transaction cause this slowing down in any way? - 
        
Redirection in Class Based Views Doesn't Completly Work
views.py: class LoveLetterCreateView(LoginRequiredMixin, CreateView): model = LoveLetter fields = '__all__' success_url = reverse_lazy('login') # NOT WORKING class SignUpView(CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') # WORKING template_name = 'love_letters/signup.html' Why it would work in one CreateView but not in the other? I tried: def get_success_url(self): - NOT WORKING. - 
        
I have restarted My Django for Other Project But it's still trying to load Previous project files
I have worked on Django Project where I create applications hello, newyear, and tasks. Now, I have to work on a different Project I got it's file from CMD I opened it in visual studio and then created a virtual environment and installed Django in it, but When I have run the server it's showing this output: in the image enter image description here it's trying to open the previous project files instead this project. However, the ip address given by django was same for both projects. Please help, I am new to programing. thank you very much I am trying to create django server for the project file I download online from a course cs50web So, I can run that project. - 
        
How to execute programs/commands in .net core webapp (like Django's manage.py)
I have been a Django developer for over 5 years now and am looking for creating new projects in .net. I have created a few hobby projects in .net and the experience was quite good. But I have a question, to which I haven't found the answer. To give an example: Django has built in management commands and options to write your own. One of the options is createsuperuser. For example, when you setup your django project, you can call python manage.py createsuperuser and it will create a superuser for you. You can create custom commands, which can be run locally and in production servers. How can I do this in .net if I have a webapp? How can I run commands/programs locally or on production server/kubernetes pod? Is this even possible? I know you can create multiple projects inside the solution beside webapp project. - 
        
Django Parametrize Test
I have a simple model factory: class SubjectFactory(factory.django.DjangoModelFactory): class Meta: model = Subject title = 'Mathematics' slug = 'mathematics' When I want to test the instance creation, my parametrization does not override default title and slug. It remains Mathematics. If I remove the line, I get an AttributeError: AttributeError: type object 'SubjectFactory' has no attribute 'title' Here is the instance test: import pytest from courses.models import Subject @pytest.mark.parametrize( 'title, slug, validity', [ ('Algebra', 'algebra', True), ('', '', False), ], ) def test_subject_instance(db, subject_factory, title, slug, validity): test = subject_factory( title=title, slug=slug ) item = Subject.objects.all().count() assert item == validity How can I run the test with these custom params? - 
        
How to use Django Messages field wise in template like Laravel's error in blade template
In Laravel I have a much finer control to show error related to each form field like we can write below in the blade template below respective fields <input name='username' placeholder='User Name' type='text' /> @error('username') <input name='email' placeholder='Email' type='text' /> @error('email') where within quotes are the form input field name. Now if there is a validation error, you can show error below that input field. And error contents are also out of the box basis the validation check of those fields in PHP Code Whereas in Django, it is more like all errors together in the Django Message Framework. Is there a way, from messages one can get errors by field. At least from the documentation I couldn't figure out. - 
        
A changed object is not reflecting in the database
Consider: jobs = Job.objects.bulk_create(jobs) ids = [job.id for job in jobs] # Wait for results (computed by another process) not_done = set(ids) while not_done: complete_jobs = Job.objects.filter( id__in=not_done, result__isnull=False) for job in complete_jobs: job.complete = ms_now() # the current timestamp in ms job.save() print(f"Removing from not_done: {job.id}", flush=True) not_done.remove(job.id) time.sleep(0.1) When the computation is finished, some jobs still have null in the complete attribute. When I look at the output, the line beginning with "Removing from not_done: appears for these jobs. Somehow, job.save() does not result in the new value of job.complete reflecting in the database. Why could this be happening and how do I fix it? - 
        
nginx django static files 403 forbidden error permission denied
ngnix.conf server_name _; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/megasoft/bots/hisoblovchibot/backend/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } 2023/09/01 10:41:20 [error] 11593#11593: *1 open() "/home/megasoft/bots/hisoblovchibot/backend/static/admin/js/core.js" failed (13: Permission denied), client: 192.168.1.30, server: _, request: "GET /static/admin/js/core.js HTTP/1.1", host: "195.158.26.12:9938" - 
        
Django save() with specified psycopg connection
I have made a class called Database that I use to manage a connection to a Postgres database via psycopg3. This enables me to do things like: db = Database(postgres_connection_data) class_one_instance.insert(insert_data, db) class_two_instance.insert(insert_data, db) db.commit() The exception handling in the insert methods is such that we only get to db.commit() if both inserts have worked, which is exactly what I want. I am exploring Django as an option in our stack and I would like to replace the implementation of class two's insert() with save() from models.Model. How can I use my Database object with save()? def insert(self, insert_data, db): self.save() - 
        
Django, gunicorn workers, scaling on Kubernetes
Kind of related to this post, we're in a similar position where we have a django application using gunicorn WSGI running on a Kubernetes cluster. I have read the official docs on how to configure num of workers (see design), but I still don't understand how this converts to a kubernetes pod running on a cluster utilising shared CPU? I have done various load tests on our test environment and the following is an idea of metrics I get and the resources in use: Django deployment containing 3 pods minimum but can scale to 20 Each pod has 1 CPU in Kubernetes config Each pod runs 3 gunicorn WSGI workers currently Pods run across Kubernetes nodes, each node has 4 CPUs Simple load testing suggests, we reach about 20-25rps maximum and then workers begin to restart, which seems quite bad! Scaling kicks in but its a lot slower than I'd like, despite optimisations, although we are slowed down a little by the istio-proxy side containers which have to start first before the app container Does anyone have any similar issues when it comes to scaling django apps? I know there can be a lot of differences depending on code, API … - 
        
Image Upload Django with Ckeditor Failed Undefined
I'm trying to create a blog page with Django. I'm using CKEditor to add text. When I upload images locally, I don't have any issues, but I encounter a problem when I deploy the project to the server. When I go to the image upload section in CKEditor and click "Send to Server," I receive an "undefined" error in the popup that appears. failed but I don't get this error when I start the project in my local. Ckeditor -v = django-ckeditor==6.7.0 Django -v = Django==4.2.4 CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_STORAGE_BACKEND = 'django.core.files.storage.FileSystemStorage' FILEBROWSER_REMOVE_DIALOG_TABS = 'image:Upload' CKEDITOR_CONFIGS = { 'default': { 'filebrowserUploadUrl': '/ckeditor/upload/', 'filebrowserBrowseUrl': '/ckeditor/browse/', 'toolbar': 'Full', # Toolbar ayarları düzeltildi 'toolbar_Full': [ ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['NumberedList', 'BulletedList'], ['Indent', 'Outdent'], ['Maximize'], {'name': 'about', 'items': ['CodeSnippet']}, {'name': 'tools', 'items': ['Maximize', 'ShowBlocks']}, ], 'tabSpaces': 4, 'fillEmptyBlocks': False, 'extraPlugins': 'justify,liststyle,indent,codesnippet,devtools,uploadimage', # Resim eklentisi eklendi 'uploadUrl': '/ckeditor/upload/', # Resim yükleme URL'si eklendi }, } Have you encountered this problem? I would like your comments on the topic. enjoy your work I didn't expect to run into a problem here. It is interesting that … - 
        
Sending email with Celery and Redis cloud
I am trying to send an email using celery queue @shared_task as below: # removed imports for clarity # For debugging @shared_task(bind=True, name="send_email", max_retries=3, default_retry_delay=10) def send_email(self, subject, message, from_email, to_email, **kwargs): """Send an email""" try: send_mail(subject, message, from_email, [to_email], **kwargs) except Exception as e: logger.error(e) # configured logger class Command(BaseCommand): help = "Send test email" def handle(self, *args, **options): try: send_email.delay( "Test email", "This is a test email", settings.EMAIL_HOST_USER, "validemail@examle.com", fail_silently=False, ) self.stdout.write(self.style.SUCCESS("Email queued successfully")) except Exception as e: raise CommandError(e) And I get ...celery stack trace raise SMTPRecipientsRefused(senderrs) smtplib.SMTPRecipientsRefused: {'validemail@example.com': (550, b'Please turn on SMTP Authentication in your mail client. 333.kpservers.com\n(altar56.supremepanel56.com) [cpanel_server_ip]:43036 is not permitted to\nrelay through this server without authentication.')} However when I use direct send_mail without shared_task it is successful (so it doesn't seem to be a server error) How do I resolve this error? I am using redis database redis://default:*******@********.cloud.redislabs.com:13122 - 
        
Django anon cart system not working on first visit to site
I wanted to implement an anonymous cart system to my django site. I saw on internet that I can achieve with the following javascript code: function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } let device = getCookie('device') if (device == null || device == undefined){ device = uuidv4() } document.cookie ='device=' + device + ";domain=;path=/" Which is embedded at the end of 'base.html' which is a template every other html uses. like this: <script src="{% static 'js/cookies.js'%}"></script> Followed by this home page code: class HomeView(ListView): template_name = "index.html" def get(self, *args, **kwargs): context = get_base_lists(self.request) ... return render(self.request, self.template_name, context) ... def get_base_lists(request): ... cart, created = … - 
        
Updating objects in queryset computed with filter clears the query
I have: jobs = Job.objects.filter(detected__isnull=True).order_by('submitted') print(f"Detected {len(jobs)} jobs") jobs.update(detected=ms_now()) try: print(jobs[0].id) except: print("No objects!") Output: Detected 865 jobs No objects! It seems like the filter is re-computed due to the update, but why does this happen? - 
        
correct response code for role management
I’ve a user model and have some roles through other models (admin , doctor , patient, manager models ... etc) . I’ve one login endpoint for all . the patient, doctor only login with mobile number (didn’t handle it yet “means if he has email can login too”). patient only uses mobile application ... doctors on the web. all endpoints of each role are guarded with it’s related model , Like all users can login successfully as long as they’ve a User model , But when they try to access the admin , doctor… etc, they must have a related relation of the role … like if a user need to access the doctor endpoints , he must have a doctor instance . A user can have many roles (can register as many roles). What’s the best response code for this case if a user tried to access doctor endpoints without having a doctor instance ? 404 (user not found ) or 403 (unauthorized) and why please give a detailed response . Thanks I've implemented the response as a 403 , but "considering the doctor can be a patient" when he (doctor) logins through mobile (as patient) while he doesn't … - 
        
I am trying to make website where users can see user specific data, but I can get the user's data in my in order to pass it my template
On my photo album website each user should see only the images that he uploaded, however when I specify user in my get_context_data method my context object becomes empty. I tried various methods that I found in the internet, but nothing works - 
        
How to show the video with mediapipe in html in django?
my html and views.py are refer to https://roytuts.com/upload-and-play-video-using-django/, but i want to change the display video to video with mediapipe,what should i do or change in my code? mediapipe code in views.py: def process_video(filename): input_video_path = filename output_video_path = f"processed_{filename}" cap = cv2.VideoCapture(input_video_path) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fourcc = cv2.VideoWriter_fourcc(*'MP4V') out = cv2.VideoWriter(output_video_path, fourcc, 20.0, (width, height)) while cap.isOpened(): ret, frame = cap.read() if not ret: break image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) results = holistic.process(image) # Draw landmarks and connections mp_drawing = mp.solutions.drawing_utils mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(121, 22, 76), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(121, 44, 250), thickness=2, circle_radius=2)) mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(80, 22, 10), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(80, 44, 121), thickness=2, circle_radius=2)) mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS, mp_drawing.DrawingSpec(color=(245, 117, 66), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(245, 66, 230), thickness=2, circle_radius=2)) out.write(image) cap.release() out.release() cv2.destroyAllWindows() - 
        
Can I be full stack with django in backend [closed]
everyone knows that in order to be a full stack, you need to have a frontend and a backend, in the backend you usually use php, java, c # and others. The question is can I be a full stack with Django read up read up read up - 
        
Migrate a django project to new server with already exists postgresql database of anotehr django project
I have 2 django apps on separate servers. Both have completely different models The database name of app1 is xxxx1 The database name of app2 is xxxx2 how to migrate xxxx2 to server1 without damage anything ? - 
        
Languages Selection process [closed]
I want to be a smart front ended web developer. In future, I will shift in full stack development journey. Now, I want to enter market place because I need to earn money immediately. I have completed following languages: HTML CSS vanila js Bootstrap So please suggest me, in this step which language I should shift now so that I can start earning. Thanks to all my lovely friends. I am looking for a market place to earn money. - 
        
Django ORM for custom python function
I have following two models class Membership(models.BaseModel): user = models.ForeignKey(User) package = models.ForeignKey(Package, on_delete=models.PROTECT, blank=True, null=True, related_name="package_membersips") benefit_end = models.DateField() benefit_start = models.DateField() class Package(models.BaseModel): name = models.CharField(max_length=40) description = models.CharField(max_length=200, null=True, blank=True) class PackageTier(BaseModel): package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='package_tiers') min_members = models.IntegerField() max_members = models.IntegerField() retail_price = models.DecimalField(max_digits=5, decimal_places=2) wholesale_price = models.DecimalField(max_digits=5, decimal_places=2) The wholesale_price and retail_price calculation consists of some logic, that is difficult to perform using ORM: def get_package_price(package_instance): count = package_instance.package_memberships.count() tier = package_instance.package_tiers.filter( min_members__lte=count + 1, max_members__gte=count + 1 ).first() if not tier: tier = package_instance.package_tiers.order_by('id').first() return tier.retail_price if tier else 0 def get_package_wholesale_price(package_instance): count = package_instance.package_memberships.count() tier = package_instance.package_tiers.filter( min_members__lte=count, max_members__gte=count ).first() if not tier: tier = package_instance.package_tiers.order_by('id').first() return tier.wholesale_price if tier else 0 These are business logic and I need to aggregate the result based on the year basis. # sample response: {"data": [ { "year": 2021, "commission": 1.0 }, { "year": 2022, "commission": 8.2 }, { "year": 2023, "commission": 11.0 }, ]} Is there any way that I can use get_package_price and get_package_wholesale_price inside Django ORM ? I used following ORM to get membership for each year: Membership.objects.all().annotate(year=ExtractYear('benefit_start')).values('year').order_by('year') The custom function need to be called in this ORM. - 
        
Why is caching not improving the performance in my django view?
I am trying to improve performance of a view by caching a given linear algebra expression and its corresponding result. I am using memcached and pymemcache but for some reason theres no performance gain. Heres my view: @api_view(['POST']) @login_required(login_url='/api/login/') @csrf_exempt def compute_lalg_expression(request): form = LinearAlgebraExpForm(request.POST) if form.is_valid(): new_expr = form.save(commit=False) data_expr = form.cleaned_data data_expr = data_expr['exp'] exp_hash = hashlib.md5(data_expr.encode()).hexdigest() alg_exp = cache.get(exp_hash) if not alg_exp: parsed_exp = parser.parse(data_expr) eval_data = evaluate(parsed_exp) expr_model = LinearAlgebraExpression(exp=eval_data) expr_model.save() create_action(request.user, 'computed an expression', expr_model) serializer = LinearAlgebraExpSerializer(expr_model) cache.set(exp_hash, serializer.data) return Response(serializer.data) return Response(alg_exp) And here is the client I am testing it with. I am testing it by removing the lines associated with caching above so I am removing exp_hash, alg_exp and so on so I remove the if statement that checks whether alg_exp is true or false and i remove cache_set. Anyways heres my client import aiohttp import asyncio import time async def make_request(session): url = 'http://127.0.0.1:8000/api/compute/' payload = {'exp': exp + '*' + exp2} # Replace with your POST data async with session.post(url, data=payload, auth=aiohttp.BasicAuth('jobpink', 'hello123')) as response: return await response.text() async def main(): # Adjust these values as needed num_requests = 5000 # Number of requests to send concurrency = 10 … - 
        
'403 Forbidden: CSRF verification failed. Request aborted.' in Django deployment with Railway
I am trying to deploy a Django app on Railway. I have {% csrf_token %} in each form, yet am still getting the '403 Forbidden: CSRF verification failed. Request aborted.' each time. I have inspected the page to verify the hidden csrf is being created (it is) and that the cookie exists (it does). Here is my settings.py and my full repo for reference """ Django settings for rpisite project. """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'rpiapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'rpisite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'rpisite.wsgi.application' # Database import dj_database_url DATABASE_URL = os.environ['DATABASE_URL'] DATABASES = { "default" : dj_database_url.config(default=DATABASE_URL, conn_max_age=1800) } # … - 
        
Django forms.ModelForm Failed lookup for key [form]
I'm getting error with forms.ModelForm Failed lookup for key or empty form, any suggestions, please? VariableDoesNotExist at /timesheets/ Failed lookup for key [form] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'view': <django.views.generic.base.TemplateView object at 0x00000201195B1F50>}] forms.py from django import forms from .models import TimeSheet from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row class TimeSheetForm(forms.ModelForm): class Meta: model = TimeSheet fields = "__all__" def __init__(self, *args, **kwargs): super(TimeSheetForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'AddNewEntry' self.helper.form_method = 'post' self.helper.layout = Layout( Row('date_time_start', 'date_time_end', 'project_code', 'user', 'milage', 'project_type', 'activities', 'expenses', Submit('submit', 'Submit') ) ) add_timesheet.html {% load crispy_forms_tags %} <div id="timesheet-form-container" class="d-none d-flex flex-row flex-nowrap justify-content-between"> <form id="timesheet-form" method="post" class="w-100"> {% csrf_token %} {% crispy form %} <button type="submit" class="btn btn-primary">Submit</button> </form> </div> views.py from django.contrib.auth.decorators import login_required from django.http import JsonResponse from django.shortcuts import render from .forms import TimeSheetForm from .models import TimeSheet def add_timesheet(request): if request.method == 'POST': form = TimeSheetForm(request.POST) if form.is_valid(): form.save() return {'success': True} else: form = TimeSheetForm() return render(request, 'timesheets/add_timesheet.html', {'form': form}) timesheets/urls.py from django.urls import path from django.views.generic import TemplateView from . import views urlpatterns = [ path('', TemplateView.as_view( template_name='timesheets/timesheets_main.html'), name='timesheets'), path('add_timesheet/', views.add_timesheet, name='add_timesheet'), path('get_timesheets/', views.get_timesheets, name='get_timesheets'), ] I`m tried … - 
        
Creating new filter in django
I would like to use a range filter in django. Something like this : <br> <table> <thead> <tr> <th>Revenue streams</th> <th>Units</th> <th>Description</th> {% for num in 2022|range:2027 %} <th>{{ num }}</th> {% endfor %} </tr> </thead> So I have created a templatetags folder in my app and added file custom-filters.py that contains : from django import template register = template.Library() @register.filter def range(start, end): return range(start, end + 1) but the page returns : Any idea of what is mising?