Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deep Learning Model calling through FAST API
Is it possible to call a deep learning model which is working on several GBs of data to be called through an api which is made by Fast API? Or would DjangoREST or Flask be a better approach? -
How to prevent race condition while working with sessions?
I’m working on an e-commerce website with a cart and products. A product’s primary key is added to the user’s session data in a dictionary 'cart_content'. I successfully reproduced a race condition bug by triggering a click() twice with an amount of product that will sold out for the next purchase. So the two requests increment twice the cart but there is not enough stock. How can I prevent race condition to happen like the example given above or in a multi-user case ? Does there is for example some sort of lock system that prevent add_to_cart() from being executed asynchronously ? core/models.py : class Product(models.Model): … number_in_stock = models.IntegerField(default=0) @property def number_on_hold(self): result = 0 for s in Session.objects.all(): amount = s.get_decoded().get('cart_content', {}).get(str(self.pk)) if amount is not None: result += int(amount) return result … cart/views.py : def add_to_cart(request): if (request.method == "POST"): pk = request.POST.get('pk', None) amount = int(request.POST.get('amount', None)) if pk and amount: p = Product.objects.get(pk=pk) if amount > p.number_in_stock - p.number_on_hold: return HttpResponse('1') if not request.session.get('cart_content', None): request.session['cart_content'] = {} if request.session['cart_content'].get(pk, None): request.session['cart_content'][pk] += amount else: request.session['cart_content'][pk] = amount request.session.modified = True return HttpResponse('0') return HttpResponse('', status=404) cart/urls.py: urlpatterns = [ … path("add-to-cart", views.add_to_cart, name="cart-add-to-cart"), … -
Cannot login on my website with a user I create in django admin
I have a login and signup page, where a user that signs up is able to login and i can view this user in the admin portal as shown in the screenshots below: Example User created through signup page: Username=usertest Password=pass123 Signup page Signed up user visible in admin portal (note: password is hashed) However, when i create a user in admin portal I cannot login with that user in login. This may be due to the password that is being stored as it is not hashed when viewing admin portal-not too sure: Example User created through django admin portal: Username=usertest2 Password=pass1234 User created via admin portal (note: password is not hashed) Login says invalid despite user present in admin view I have tried to have a look and think it might be the password is not hashed when creating a new user in admin portal and so when login is compared this might be causing the issue- not too sure. Below are my codes, I can share further code that can help solve this too: models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.CharField(max_length=50, unique=True) profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile-images") date_of_birth = models.DateField(null=True, blank=True) … -
How do i get these crsf token for a drf api without frontend?
Hi I am new to Django Rest frameworks and I am making a api for a mobile app which will make post request to the Backend so the thing is I am getting a response from the request which is { "error": "CSRF token missing" } And I tried to see BardAi and ChatGPT they said that it would only work if I have a front end framework dealing with these cookies so is that a solution to get the token without using the decorator which would exempt the token all in itself. I would like source code and any solutions. -
How to render in real-time one of the fields of the Django model?
I already set up the connection between the server side which are the asgi.py, consumers, and routing, that is already listening to client side using javascript. But I don't know how to render out, in real time, the field in that one model to my javascript that'll will be shown in HTML. I'm not trying anything for now since I do not know where to start, and what to do. But all I want to achieve is to render that one field from the model through the HTML in real time. -
Running django project using pm2 and gunicorn fails with syntax error I cant fix
I'm following these guides: https://david.dev/deploying-django-with-pm2-and-gunicorn https://www.umutsagir.com/how-to-properly-serve-python-apps-with-pm2-and-gunicorn-on-any-port-and-any-server/ and trying to get my django project to run using gunicorn and pm2. My ecosystem.config.js looks like this: module.exports = { apps: [ { name: 'projectname-django-live', script: '/root/.cache/pypoetry/virtualenvs/projectname-n-gjsKBO-py3.10/bin/gunicorn', args: [ '--chdir=/var/www/projectname/projectname', 'projectname.wsgi:application', '--bind=0.0.0.0:3200', // Replace with your desired port '--workers=1', // Adjust the number of workers based on your server's capabilities '--threads=3', // Adjust the number of threads based on your server's capabilities // Add any other Gunicorn options here ], error_file: '/var/log/projectname_live/pm2_django_err.log', out_file: '/var/log/projectname_live/pm2_django_out.log', }, ], }; The projectname is three times in the path, because the location of the wsgi.py file is /var/www/projectname/projectname/projectname/wsgi.py The error I get is: root/.cache/pypoetry/virtualenvs/projectname-n-gjsKBO-py3.10/bin/gunicorn:2 # -*- coding: utf-8 -*- ^ SyntaxError: Invalid or unexpected token at internalCompileFunction (node:internal/vm:73:18) at wrapSafe (node:internal/modules/cjs/loader:1178:20) at Module._compile (node:internal/modules/cjs/loader:1220:27) at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) at Module.load (node:internal/modules/cjs/loader:1119:32) at Module._load (node:internal/modules/cjs/loader:960:12) at Object.<anonymous> (/usr/local/share/.config/yarn/global/node_modules/pm2/lib/ProcessContainerFork.js:33:23) at Module._compile (node:internal/modules/cjs/loader:1256:14) at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) at Module.load (node:internal/modules/cjs/loader:1119:32) and I'm not sure how to fix this. I thought that perhaps I need to set the interpreter in the config file. Not sure, but since the gunicorn path is the full virtualenv path, it should be fine, right? Help pls. Alan. -
Multiform nested data
Hey there i am trying to serialize the multiform nested data but i have tried everything but nothing works for me and also i did not get any kind of help from internet. enter image description here and i am getting data from frontend like that: <QueryDict: {'product_name': ['aa'], 'category': ['electronics'], 'description': ['aaa'], 'price': ['12'], 'inventory': ['[{"size":"Small","color":"Black","quantity":"4"}]'], 'images': [<InMemoryUploadedFile: Screenshot 2023-11-16 131611.png (image/png)>]}> please give some solution I have tried different libraries for parsing nested multiparse data but did not get a solution -
AWS Django NGINX timeout and async errors
I have a view in which I try to upload an excel sheet via a form. The excel that I upload isn't that big but the processing of the data in that excel is causing nginx time out issues resulting in a 502 Bad Gateway error. I do not have this problem when testing locally but it pops up on AWS EC2 when testing it on that environment. I increased the time out periods in nginx via (as suggested here): proxy_read_timeout 300s; proxy_connect_timeout 300s; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; And that did improve things somewhat since I can see more results but it was not sufficient. Curiously it timed out again before the 300s were up. Incidentally, if it used all 300s it should complete the process. It was also suggested I use async to make the processing independent of the upload process and that it run the processing in the background. However in attempting I keep running into this error: "object HttpResponseRedirect can't be used in 'await' expression" This error occurs when I try to load the page even before I try to upload the excel file which is the only time I have a redirect, which … -
Why aren't media files autogenerated in Django?
So i create same project which accepts input from the user in the form of an image. I followed Django step documentation and this. The result I got was correct, I received input from the terminal if the 'POST' method was successful by returning status code 200. But why is the media folder in the root directory not created? I've changed the settings.py with this code cartoon/views.py from django.shortcuts import render, redirect from django.http import HttpResponseServerError, HttpResponse from .forms import CartoonImageForm import cv2 import numpy as np from django.http import JsonResponse def cartoon (request): return render(request, 'cartoon/cartoon.html') def image (request): if request.method == 'POST': form = CartoonImageForm(request.POST, request.FILES) if form.is_valid (): form.save() return redirect('success') else: form = CartoonImageForm() return render(request, 'cartoon/cartoon.html', {'form': form}) def success(request): return HttpResponse('successfully uploaded') This urls.py # cartoon/urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import path from .views import cartoon, image app_name = 'cartoon' urlpatterns = [ path('cartoon/', cartoon, name='cartoon_page'), path('result/', image, name='cartoon_result') ] ## MEDIA if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) cartoon/forms.py from django import forms from .models import CartoonImage class CartoonImageForm(forms.ModelForm): class Meta: model = CartoonImage fields = ['image_upload'] directory root settings.py # Build paths inside the project like this: … -
Model property object not showing up
I try to calculate the average rating for my user. I triede to define property so it calculates and shows automatically. Models.py class User(AbstractUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=40, unique=True, default='undefinedusername') email = models.CharField(max_length=255, unique=True,null=True,blank=True) @property def average_rating(self): return self.usercomments.all().aggregate(Avg('rate')).get('rate__avg', 0.00) class UserComment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) profile = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='usercomments') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='usercomments_author') rate = models.IntegerField(default='0') Serializers.py class UserSerializer(serializers.ModelSerializer): rating_count = serializers.SerializerMethodField(read_only=True) usercomments_set = UserCommentSerializer(source='usercomments', required=False, many=True) class Meta: model = User fields = '__all__' def get_rating_count(self, language): return language.usercomments.count() def validate(self, attrs): attrs = super().validate(attrs) if attrs.get('id') == self.context['request'].user.pk: return attrs raise ValidationError('Unauthorized Request') Here is my result: { "count": 1, "next": null, "previous": null, "results": [ { "id": "8b0efd7e-06ac-4d57-a347-e9ffe79c3c31", "usercomments_set": [ { "id": "61c5b21e-3456-4a13-83c4-4557cd621af6", "rate": 4, "profile": "8b0efd7e-06ac-4d57-a347-e9ffe79c3c31", "author": "f474d116-ec1d-498b-a166-7af3fa8cfd59" } ], "rating_count": 1, "username": "undefinedusername", "email": "testmail@gmail.com", }, } Everything else except average_rating shows up. What is the issue?Where did I make the mistake? -
In the file in Django, the venv file does not appear. Please respond\في الملف في دجانجو لا يظهر ملف venv ارجو الرد [closed]
The venv file is not supposed to appear as the first file?\ليس من المفترض ان يظهر ملف venv اول ملف ؟ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -
Issues with Django Import-Export: Validation Errors during CSV Import
I am currently working on a Django project where I'm using the django-import-export library to import CSV data into my models through the Django admin interface. I have set up resources, models, and made necessary changes in the admin, but I'm facing validation errors during the import process. I have the following structure in my Django project: models.py: Contains the definitions of various models like PlayStyles, Coaches, Stadiums, Leagues, Teams, Players, Matches, and Statistics. resources.py: Includes corresponding ModelResource classes for each model. admin.py: Configures the Django admin interface to use the ModelResource classes for data import/export. CSV Files: I have CSV files for each model with data to be imported. Despite setting up the resources correctly, I am encountering issues when importing CSV files for certain models, specifically for Teams. The error message mentions validation errors related to foreign key fields (stadium, coach, and league). Here's a snippet of my relevant code: models.py: # ... (models for PlayStyles, Coaches, Stadiums, Leagues, etc.) class Teams(models.Model): name = models.CharField(max_length=100) established_year = models.IntegerField() stadium = models.ForeignKey(Stadiums, on_delete=models.CASCADE) coach = models.ForeignKey(Coaches, on_delete=models.CASCADE) league = models.ForeignKey(Leagues, on_delete=models.CASCADE) number_of_titles = models.IntegerField() resources.py: # ... (resources for PlayStyles, Coaches, Stadiums, Leagues, etc.) class TeamsResource(resources.ModelResource): class Meta: model … -
You're accessing the development server over HTTPS, but it only supports HTTP.(DJANGO)
I have a Django app in which I make an object name Bin via forms. But when I try to POST the requested for the form it says '"GET /creatBin HTTP/1.1" 200 4503 [11/Dec/2023 10:29:01] code 400, message Bad request version ('ÚÚ\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x01\x00\x01\xad') [11/Dec/2023 10:29:01] You're accessing the development server over HTTPS, but it only supports HTTP. [11/Dec/2023 10:29:01] code 400, message Bad request version ('\x00\x02\x01\x00\x00') [11/Dec/2023 10:29:01] You're accessing the development server over HTTPS, but it only supports HTTP.' now my views function is: def creatBin(request): if request.user.is_authenticated: if request.method == 'POST': form = Bins(request.POST) if form.is_valid(): refresh_stats = form.cleaned_data['refreshStats'] last_refresh = form.cleaned_data['lastRefresh'] fill_up = form.cleaned_data['fillUp'] area = form.cleaned_data['Area'] city = form.cleaned_data['City'] qr_data = form.cleaned_data['qr_data'] print(qr_data) qr_data_json = json.loads(qr_data) lat = qr_data_json['Lat'] lon = qr_data_json['Lon'] bin_id = qr_data_json['BinID'] if fill_up >= 70: status = 'HIGH' form.refreshStats = 'Due' elif fill_up >= 40: status = 'MID' form.refreshStats = 'Due' else: status = 'LOW' form.refreshStats = 'Done' # Now you have individual variables for each form field # You can use these variables as needed, for example, save them to the database bin_instance = BinsStats( BinID=bin_id, status=status, refreshStats=refresh_stats, lastRefresh=last_refresh, fillUp=fill_up, Lat=lat, Lon=lon, Area=area, City=city, ) bin_instance.save() messages.success(request, 'Bin added successfully!') else: messages.error(request, … -
Django template next item show with infinite scroll
i have some code wrong and run nex item show with infinite scroll,How to resolve.TKs i made a countdown on the template var eventBox = document.getElementById('event-box') console.log(eventBox.textContent) var countdownBox = document.getElementById('countdown-box') console.log(countdownBox.textContent) var eventDate = Date.parse(eventBox.textContent) setInterval(()=>{ var now = new Date().getTime() var diff = eventDate - now var d = Math.floor(eventDate / (1000 * 60 * 60 * 24) - (now / (1000 * 60 * 60 * 24))) var h = Math.floor((eventDate / (1000 * 60 * 60 ) - (now / (1000 * 60 * 60 ))) % 24 ) var m = Math.floor((eventDate / (1000 * 60 ) - (now / (1000 * 60 ))) % 60 ) var s = Math.floor((eventDate / (1000) - (now / (1000))) % 60 ) if (diff>0) { countdownBox.innerHTML = d + " 天, " + h + " 時, " + m + "分, " + s + "秒" } else { } }, 1000) def all_emp(request): emps = Employee.objects.filter(end_date__gt=Now()).all() context = { 'emps': emps } print(context) return render(request, 'view_all_emp.html', context) enter image description here -
Reverse Relationship in Django Rest Framework
I have Course and CourseComment models. In Course details view I should return details of Course, and also comments by user. I've made serializer for Course details and Course comments. But coursecomment_set field is empty. I wrote several comments for Course. Here is my models, serializers and models # views.py ---> Course Details API View class CourseDetailsView(generics.RetrieveAPIView): queryset = models.Course.objects.select_related('category') serializer_class = serializers.CourseDetailSerializer lookup_field = 'slug' # models.py ---> Course model class Course(BaseModel): LEVEL_TYPES = ( ('beginner', 'Beginner'), ('intermediate', 'Intermediate'), ('advanced', 'Advanced'), ) LANGUAGES = ( ('uz', 'O`zbek tili'), ('en', 'Ingliz tili'), ('ru', 'Rus tili'), ) title = models.CharField(max_length=128) author = models.CharField(max_length=128) price = models.PositiveIntegerField(default=0) level = models.CharField(choices=LEVEL_TYPES, max_length=16) description = models.TextField() category = models.ForeignKey('CourseCategory', on_delete=models.CASCADE) lessons_count = models.PositiveIntegerField(default=0) language = models.CharField(choices=LANGUAGES, max_length=2, default='uz') rating = models.DecimalField(max_digits=2, decimal_places=1, default=0) slug = models.SlugField(unique=True, blank=True) # Comments model class CourseComment(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) body = models.TextField() rating = models.DecimalField(decimal_places=1, max_digits=2) # serializers.py ---> Course Comments Serializer class CourseCommentSerializer(serializers.ModelSerializer): class Meta: model = CourseComment fields = ('user', 'body', 'rating') # Course details class CourseDetailSerializer(serializers.ModelSerializer): coursecomment_set = CourseCommentSerializer(many=True, read_only=True) class Meta: model = Course fields = "__all__" View returning response, but comments are empty, I've several comments in database … -
Restrict user access to pages
I want users to be able to see only their profile information and not have acccess to others users information. I am using a test_func to check if the user login trying to access the profile information is the owner of the information. The problem is that for some reason it always returns true, and when i go to my page an change the id on the link trying to access others users information it somehow automatically login with the user due user account and then return the information, it is, if i'm logged in as "lerton" with id 1 and i try to access the information of user "maguia" with id 2 it automatically log in as "maguia" and return me the information of "maguia" urls.py path('profile/<int:pk>/', ProfileView.as_view(), name='profile'), View.py class ProfileView(LoginRequiredMixin, DetailView, UserPassesTestMixin): model = get_user_model() template_name = 'profile.html' context_object_name = 'user' def test_func(self): user = self.get_object() return user == self.request.user I tried to compare in the test_func the other properties like id, username, etc, of the users but didn't work -
Show only the seasons related to the current course in Django Admin Panel
hi guys i have a 3 model: class Course(models.Model): title = models.CharField(max_length=30) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="courses") class Season(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course_season") name = models.CharField(max_length=40) class CourseVideo(models.Model): title = models.CharField(max_length=30) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course_videos") season = models.ForeignKey(Season, on_delete=models.CASCADE, related_name="season", null=True, blank=True) video = models.FileField(upload_to="vid/course_video") and this is my admin file : class DetailAdmin(admin.TabularInline): model = models.CourseVideo class SeasonAdmin(admin.TabularInline): model = models.Season @admin.register(models.Course) class CourseAdmin(admin.ModelAdmin): inlines = (SeasonAdmin, DetailAdmin) list_display = ("title", "price") now my problem is in the django`s admin panel when i have created forexample 2 seasons for each course and i want to create some videos when i wanna choose a season for a video , it shows all the seasons which is created but i just want it to show the seasons who are related to the course . what should i do ? -
Create django filter choices based on current queryset
I have a table with a number of category columns and I want to provide a choice filter for each category column based on the current set of values, not based on all possible values. year category_a category_b 2020 x a 2021 y b 2022 z b Given the above the initial choices for category_a would be x,y,z and category_b would be a,b. This I can achieve by using something like self.parent.queryset.distinct('category_a'). However once the user applies a filter like category_b=b, the choices should only be y,z, i.e. something like self.parent.qs.distinct('category_a'). This however runs into recursion. I'm looking through the execution path of FilterSets, since it seems to me that they must be used twice in a request, once to apply the current filter data and a second time to render the filter widgets for the response, but choices is evaluated as part of the initial set validation, hence the recursion. Is there a way to defer the computation of choices until the widget is rendered? -
How to read csv file into django project?
I'm using csv(txt) file to make graphs, but Django doesn't want to find it. So I can't understand, where should I create a file. def get_plot(): df = pd.read_csv('jobibi.txt', sep=',', encoding='utf-8') And the output on the web page: FileNotFoundError at /analytics/ [Errno 2] No such file or directory: 'jobibi.txt' -
How to send nested array of object using formdata from react js and save in django rest framework
when i send array of object in json it work perfectly but it was not work using form data.. when isend this {"name":"arijit","age":"30","singerimg":null,"songs":[{"title":"abc","duration":"5"}]} it work perfectly but var formData = new FormData(); formData.append('name', $('#name').val()) formData.append('age', $('#age').val()) formData.append('singerimg', $('#image')[0].files[0]? ($('#image')[0].files[0]):("")) formData.append('songs[0][title]', 'abc') formData.append('songs[0][duration]', '50') it's not work model.py class singer(models.Model): name = models.CharField(max_length = 25, null=True, blank = True) age = models.CharField(max_length = 4, null=True, blank = True) singerimg = models.ImageField(upload_to="photos", max_length = 100, null = True, blank = True ) def __str__(self): return self.name class songs(models.Model): singer = models.ForeignKey(singer,related_name = 'songs', on_delete=models.CASCADE) title = models.CharField(max_length = 25, null=True, blank = True) duration = models.CharField(max_length = 25, null=True, blank = True) serializers.py class soSerializer(ModelSerializer): class Meta: model = songs fields = ['id', 'title', 'duration'] class singerSerializer(ModelSerializer): songs = soSerializer(many=True) class Meta: model = singer fields = ['id', 'name', 'age','singerimg', 'songs'] def create(self, validated_data): song = validated_data.pop('songs') sin = singer.objects.create(**validated_data) for song_data in song: songs.objects.create(singer=sin, **song_data) return sin -
remove /admin in admin panel url of django project and access to pdf file in browser
Good Day! I can not acces to a uploaded file in browser through admin panel, after removing /admin in urls.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) files are kept in /media/ which is shown in setting.py of project #STATIC_URL = 'static/' STATIC_URL = '/static/' import os STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Admin panel view url If I try to open this file by clicking in browser it is not openening it is showing this error on page But if I return admin/ in urls.py as it was before, it is opening a file in browser urlpatterns = [ path('admin/', admin.site.urls), ] can anyone help on this please? -
Sending Email in Django Fail without any Error
Hello I am begginer with django and I tring to send email with my django app and i use my domain Email in my console i see Email is Sending Without any Error iam Sure my Email information is correct i see this in the console: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject of the email From: my host email To: my email Date: Mon, 11 Dec 2023 05:19:39 -0000 Message-ID: <170227197998.14276.5037629317653964065@DESKTOP-V6VG9GG> Test email i use this settings in setting.py : EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = "bahman.pws-dns.net" EMAIL_PORT = 465 EMAIL_USE_TLS = True EMAIL_HOST_USER = "my domain email" EMAIL_HOST_PASSWORD = "my password" DEFAULT_FROM_EMAIL = EMAIL_HOST_USER and i use this function to send Email : from django.core.mail import EmailMessage, get_connection def send_email(user): try: with get_connection( host=settings.EMAIL_HOST, port=settings.EMAIL_PORT, username=settings.EMAIL_HOST_USER, password=settings.EMAIL_HOST_PASSWORD, use_tls=settings.EMAIL_USE_TLS ) as connection: subject = 'Subject of the email' email_from = settings.EMAIL_HOST_USER recipient_list = [user.email] message = "Test email" email = EmailMessage(subject, message, email_from, recipient_list, connection=connection) email.send() except Exception as e: # Log the exception logging.error(f"Error sending email to {user.email}: {e}") where is the problem -
Hello. I can't upload pictures in my django project using Pydroid3. The picture file is uploaded in my 'media/images' folder but they all show 0kb [closed]
The error message that arrise is File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.11/site-packages/django/core/files/locks.py", line 126, in unlock fcntl.flock(_fd(f), fcntl.LOCK_UN) OSError: [Errno 38] Function not implemented I tried to upload images in my project to show on my website, but the images do not show. The images are loaded in the 'media/images' folder in my project root directory, but they all show 0kb. -
Django 4 by examples - Blog - send email issues
I was working on Django by Examples. Under Blog/share I am unable to send the email. Sharing all relevant blocks of code here. This is a copy paste of the code provided in the book, but I am still getting an error This is the views.py file def post_share(request, post_id): post = get_object_or_404(Post, id = post_id, status = 'Post.Status.PUBLISHED') sent = False if request.method == 'POST': form = EmailPostForm(request.POST) if form.is_valid(): cd = form.cleaned_data post_url = request.build_absolute_uri( post.get_absolute_url()) subject = f"{cd['name']} recommends you to read " \ f"{post.title}" message = f"Read {post.title} at {post_url}\n\n" \ f"{cd['name']}\'s comments: {cd['comments']}" send_mail(subject, message, 'anupam.iitm@gmail.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent}) url patterns from django.urls import path from . import views app_name = 'blog' urlpatterns = [ # post views path('', views.post_list, name = 'post_list'), ## path('', views.PostListView.as_view(), name='post_list'), ## this is the same as above but using classes. However, some error and it is not working as expected path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name = 'post_detail'), path('<int:post_id>/share/', views.post_share, name = 'post_share'), ] share.html {% extends "blog/base.html" %} {% block title %}Share a post{% endblock %} {% block content %} {% if sent %} <h1>E-mail successfully … -
cannot install mod_wsgi on windows over wampserver 3.3.2 6rbit
I have been trying to install mod_wsgi using pipenv install mod_wsgi on windows machine over a wampserver, but I get this error. I searched google for info on proceeding getting a Django app hosted over Apache, but couldn't find any information (or a resolution). They all mention to install mod-wsgi using "pip install mod-wsgi", as it is tried and tested, but each time I try it, I get this error below. Any suggestions to overcome this would be helpful. Thanks. (spolls-JBTzETyl) C:\spolls\polls>pipenv install mod_wsgi Installing mod_wsgi... Resolving mod_wsgi... Added mod-wsgi to Pipfile's [packages] ... Installation Succeeded Installing dependencies from Pipfile.lock (d0acbf)... [pipenv.exceptions.InstallError]: Collecting mod-wsgi==5.0.0 (from -r c:\users\ti-main1\appdata\local\temp\pipenv-lo438x_j-requirements\pipenv-itch8i1s-hashed-reqs.txt (line 1)) [pipenv.exceptions.InstallError]: Using cached mod_wsgi-5.0.0.tar.gz (497 kB) [pipenv.exceptions.InstallError]: Preparing metadata (setup.py): started [pipenv.exceptions.InstallError]: Preparing metadata (setup.py): finished with status 'done' [pipenv.exceptions.InstallError]: Building wheels for collected packages: mod-wsgi [pipenv.exceptions.InstallError]: Building wheel for mod-wsgi (setup.py): started [pipenv.exceptions.InstallError]: Building wheel for mod-wsgi (setup.py): finished with status 'error' [pipenv.exceptions.InstallError]: Running setup.py clean for mod-wsgi [pipenv.exceptions.InstallError]: Failed to build mod-wsgi [pipenv.exceptions.InstallError]: error: subprocess-exited-with-error [pipenv.exceptions.InstallError]: [pipenv.exceptions.InstallError]: × python setup.py bdist_wheel did not run successfully. [pipenv.exceptions.InstallError]: │ exit code: 1 [pipenv.exceptions.InstallError]: ╰─> [33 lines of output] [pipenv.exceptions.InstallError]: running bdist_wheel [pipenv.exceptions.InstallError]: running build [pipenv.exceptions.InstallError]: running build_py [pipenv.exceptions.InstallError]: creating build [pipenv.exceptions.InstallError]: …