Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my nginx is active and gunicorn is active, but i got "ERR_CONNECTION_REFUSED" when i access to my domain, and even with ip
I am now using aws ec2 to deploy my django project, and route 53 as DNS server. At first time, i everything works fine. i can access to my website via ip or my domain. But i wanted to change some appearance of my blog site, and changed from local machine, pushed to main branch, and pulled it from my instance, and did sudo systemctl restart gunicorn which made disaster for me. When doing sudo systemctl status nginx sudo systemctl status gunicorn it gives me failed results. However i eventually make them active again, but if i try to access my website via public ip or domain, it giving me "ERR_CONNECTION_REFUSED" followings are my configuration for nginx, and gunicorn. server { listen [::]:80; server_name mydomain.com www.mydomain.com <public-ip-address>; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/ultraviolet/ultraviolet_dev/ultraviolet_dev.sock; } location /static/ { root /home/ubuntu/ultraviolet/ultraviolet_dev/; } location /media { root /home/ubuntu/ultraviolet/ultraviolet_dev/; } } server { listen [::]:443; server_name mydomain.com www.mydomain.com <public-ip-address>; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/ultraviolet/ultraviolet_dev/ultraviolet_dev.sock; } location /static/ { root /home/ubuntu/ultraviolet/ultraviolet_dev/; } location /media { root /home/ubuntu/ultraviolet/ultraviolet_dev/; } } [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/ultraviolet/ultraviolet_dev ExecStart=/home/ubuntu/ultraviolet/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/ultraviolet/ultraviolet_dev/ultraviolet_dev.sock ultraviolet_dev.wsgi:application [Install] WantedBy=multi-user.target i made nginx configuration file … -
getting django cors error for subdomain but is working on different domain
I've a django app running with gunicorn and nginx. While making request from [ALL https] project.vercel.app to backend.domain.com works correctly. But when i make request from domain.com (Devtools>RequestHeader>Origin : www.domain.com) to backend.domain.com, it gives CORS error "has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.". Django CORS_ALLOWED_ORIGINS=("www.domain.com", "project.vercel.app") BOTH ARE HTTPS Both project.vercel.app and www.domain.com should work and cors error shouldn't be seen cause it's similar approach! -
"applicant": [ "This field may not be null."]
serializers.py from django.core.exceptions import ObjectDoesNotExist from rest_framework import serializers from .models import FieldUser, BaseApplicant, Applicant, CoApplicant, Guarantor class VerificationMobileSerializer(serializers.Serializer): mobile_number = serializers.CharField(max_length=15) class FieldUserSerializer(serializers.ModelSerializer): class Meta: model = FieldUser fields = ['id', 'username', 'first_name', 'last_name', 'email', 'mobile_number', 'profile_photo', 'address', 'pin_code', 'city', 'state'] profile_photo = serializers.ImageField( required=False) def update(self, instance, validated_data): validated_data.pop('profile_photo', None) instance.username = validated_data.get('username', instance.username) instance.first_name = validated_data.get( 'first_name', instance.first_name) instance.last_name = validated_data.get( 'last_name', instance.last_name) instance.email = validated_data.get('email', instance.email) instance.mobile_number = validated_data.get( 'mobile_number', instance.mobile_number) instance.address = validated_data.get('address', instance.address) instance.pin_code = validated_data.get('pin_code', instance.pin_code) instance.city = validated_data.get('city', instance.city) instance.state = validated_data.get('state', instance.state) instance.save() return instance class ApplicantSerializer(serializers.ModelSerializer): class Meta: model = Applicant fields = '__all__' class CoApplicantSerializer(serializers.ModelSerializer): class Meta: model = CoApplicant fields = '__all__' class GuarantorSerializer(serializers.ModelSerializer): class Meta: model = Guarantor fields = '__all__' class ApplicantSubmissionSerializer(serializers.Serializer): applicant = ApplicantSerializer() coApplicants = CoApplicantSerializer(many=True) granters = GuarantorSerializer(many=True) def to_internal_value(self, data): # Extract applicant data applicant_data = data.pop('applicant') # Extract applicant ID applicant_id = None if 'id' in applicant_data: applicant_id = applicant_data['id'] # Prepare co-applicants data with the applicant field populated with ID co_applicants_data = [] for co_applicant_data in data.get('coApplicants', []): co_applicant_data['applicant'] = applicant_id co_applicants_data.append(co_applicant_data) # Prepare guarantors data with the applicant field populated with ID granters_data = [] for granter_data in data.get('granters', … -
What is the Bearer token set in Authorization header, why it is so important?
Im using Django-rest-framework where the authorization is being done using bearer access token. The thing is, I want to do auth using the access token stored in cookie storage with HTTP-only. I'm using JWT, How can I handle the auth in django backend? -
am getting this error django.views.static.serve
am working on my django project , after uploading my file,picture or documents , when i try to download or view a file , I get error django.views.static.serve . my project is django project is connected to postgresql .i expect to be able to view or download an uploaded -
Django csrf token cannot be read
I am writing a website with Vue as a frontend framework and django as a backend framework. I have included the csrf token in every single request from my frontend to my backend to ensure that I dont get a 403 Forbidden error. All requests are ok and function normallu. Now here is where things are not working. I sent my code as a zipped file to someone else for them to run it. The frontend and backend both run with no issues, its just that no requests to the backend can be performed. Every request returns a 403 Forbidden error, and that is due to the csrf token not being included in the request. bear in mind that is is the same code that works on one laptop but doesnt on the other. What can I do to fix this? request from frontend to backend: try{ const response = await fetch('http://127.0.0.1:8000/logout', { method:'POST', headers:{ 'Content-Type': 'application-json', 'X-CSRFToken': Cookies.get('csrftoken'), } , credentials: 'include', }) Value of csrf token when attempting to print it on laptop that doesnt work: undefined Django settings.py file: Django settings for api project. Generated by 'django-admin startproject' using Django 5.0.1. For more information on this file, … -
Python + JavaScript good? [closed]
I learned python and I'm good on python but is python good choice to use it with JavaScript(React + Next.js) And I use Python(Django + FastApi) as a backend lib Is JavaScript(React+Next.js) good with Python(Django + FastApi) as freelancer I tried to search about that thing and every web and video say "everything is good" but I need to search it for a free lance work -
How do i accept a list of base64 images in django rest framework
So i am trying to accept multiple base64 images through an endpoint to create a post and this is the object dummie data i want to send. { "user": "username of the user", "caption": "Reasons why my Husky got mad at me today.", "location": "location of the post", "tags": [], "hashtags": [{"name":"Husky"}, {"name":"Angry_husky"}], "images": [ { "image_name": "image.png", "image_base64": "base64_string" }, { "image_name": "image2.png", "image_base64": "base64_string" } ] } Here are my models: class Hashtag(models.Model): name = models.CharField(max_length=100, unique=True) class Post(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) caption = models.TextField(_("Caption"), max_length=5000, null=True) location = models.CharField(_("Location"), blank=True, max_length=255) is_deleted = models.BooleanField(_("Is Deleted"), default=False) likes = models.ManyToManyField( CustomUser, related_name="liked_posts", blank=True, verbose_name=_("Liked By") ) tags = models.ManyToManyField( CustomUser, related_name="tagged_users", blank=True, verbose_name=_("Tagged Users"), ) hashtags = models.ManyToManyField( Hashtag, related_name="posts", blank=True, verbose_name=_("Hashtags") ) date_posted = models.DateTimeField(_("Date Posted"), auto_now_add=True) class Meta: ordering = ["-date_posted"] class Image(models.Model): post = models.ForeignKey( Post, null=True, on_delete=models.CASCADE, related_name="images" ) image_name = models.CharField() image = models.ImageField(_("Image"), upload_to="post_images/", null=True) Here are my serializers: class HashtagSerializer(serializers.ModelSerializer): class Meta: model = Hashtag fields = ["name"] class ImageSerializer(serializers.ModelSerializer): image = Base64ImageField() class Meta: model = Image fields = "__all__" class PostCreateSerializer(serializers.ModelSerializer): user = serializers.CharField() hashtags = HashtagSerializer(many=True) images = ImageSerializer(many=True, read_only=True) class Meta: model = Post fields = … -
How can I integrate AJAX infinite Scroll with Django View
I have a Django view that originally displays a list of applicants, and using the filter by session, it is expected to display list of applicants by the selected academic session. And using pagination, user is expected to scroll through pages using AJAX. The problem I am currently having is that records are been repeated in the list as the user scroll through the list and serial numbers are also repeated too. See Django view code: `@login_required(login_url='accounts_login') def application_list_by_session(request): logged_user = request.user if not (logged_user.profile.role == 'ADMISSION-OFFICER' or logged_user.profile.role == 'Admin' or logged_user.profile.role == 'Super Admin' or logged_user.is_superuser): messages.warning(request, 'Something Went Wrong') return redirect('accounts_login') # Log user activity UserActivityLog.objects.create(user=logged_user, action='Visited Application List by Academic Session Page') # Academic Session Form form = ApplicationlistBySessionForm(request.GET or None) if request.method == "GET" and form.is_valid(): academic_session = form.cleaned_data['academic_session'] # Filter Application by Academic Session submitted_application_list = ApplicationSubmission.objects.filter(academic_sess=academic_session) count_submited_applications = submitted_application_list.count() # Log user activity UserActivityLog.objects.create(user=logged_user, action=f' Generated Application list for {academic_session} Academic Session with {count_submited_applications} Applicants ') paginator = Paginator(submitted_application_list, 2) # Change 10 to your desired number of items per page page = request.GET.get('page') try: submitted_applications = paginator.page(page) except PageNotAnInteger: submitted_applications = paginator.page(1) except EmptyPage: submitted_applications = paginator.page(paginator.num_pages) context = { 'count_submited_applications': count_submited_applications, … -
How do i get the uploaded file from the dropzone hidden input and send it to the socket?
I have a chatting application. I downloaded its template online (HTML, CSS, JS) and It uses Dropzone for file uploads, but I’m having a problem retrieving the file. When I upload the file, it creates a hidden input and previews it. but, when I unhide the input, no file is selected. I’m not sure if I should edit its JS file, but I don’t understand it since I barely know JavaScript. I just want to get the file and send it to my Django consumer. I don’t have any ideas on what to do // Messenger.js function toggleGroupConversation(group_id) { const conversationThread = document.getElementById('group-conversation-thread-' + group_id); const wsProtocol = window.location.protocol === "https:" ? "wss://" : "ws://"; const wsURL = wsProtocol + window.location.host + '/' + 'ws/messenger/group/' + group_id + '/'; offcanvasElements.forEach(element => { element.style.visibility = 'hidden'; element.classList.remove('show'); }); groupThreads.forEach(thread => { thread.classList.add('d-none'); }); conversationThreads.forEach(thread => { thread.classList.add('d-none'); }); if (conversationThread) { conversationThread.classList.remove('d-none'); } if (chatSocket !== null && chatSocket.readyState !== WebSocket.CLOSED) { chatSocket.close(); } chatSocket = new WebSocket(wsURL); chatSocket.onopen = function (e) { console.log('WebSocket connection established.'); }; chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); const senderId = conversationThread.dataset.senderId; if (data.action === 'send_message') { let MessageContainer = conversationThread.querySelector('.py-6.py-lg-12'); let chatEmpty … -
configuring django with apache2
I have been working on my first django, which is a portfolio website. The site was working as intended when running on the django server, however when configuring it with apache on the linux server I few things have stopped working. I think it is is the way I have configure default.conf. this inculdes a button for downloading a rtf files and the CSS styling for the admin pages has not loaded. I have duplicated the 000-default.conf and called it django_project.conf and disabled the former and enabled the later. this is whats in that file: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/bashaar/rp-portfolio/static <Directory /home/bashaar/rp-portfolio/static> Require all granted </Directory> Alias /uploads /home/bashaar/rp-portfolio/uploads <Directory /home/bashaar/rp-portfolio/uploads> Require all granted </Directory> <Directory /home/bashaar/rp-portfolio/personal_portfolio> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/bashaar/rp-portfolio/personal_portfolio/wsgi.py WSGIDaemonProcess django_app python-path=/home/bashaar/rp-portfolio python-home=/homebashaar/. rp-portfolio/venv WSGIProcessGroup django_app I have also given apaches permission to these files: bashaar@portfolio:~$ ls -la total 52 drwxr-xr-x 6 bashaar bashaar 4096 Apr 23 10:19 . drwxr-xr-x 3 root root 4096 Apr 16 14:42 .. -rw------- 1 bashaar bashaar 9669 Apr 24 09:00 .bash_history -rw-r--r-- 1 bashaar bashaar 220 Apr 16 14:42 .bash_logout -rw-r--r-- 1 bashaar bashaar 3771 Apr 16 … -
Build a pre-decorated class with override_settings for faster client.login?
This makes a Django test using the test client run very much faster, where login security is not an important part of the test from django.test import TestCase, Client, override_settings @override_settings( PASSWORD_HASHERS = [ "django.contrib.auth.hashers.MD5PasswordHasher" ]) class Test2(TestCase): ... Is there any way to create my own TestCase subclass with the decorator built in, so I can code like this? (I keep having to look up that setting to override when I find my new test running slow! ) from myproject.utils import FastLoginTestCase class Test2( FastLoginTestCase): ... -
Trying to connect Django api to my local sql server databse but it returns the table as empty when testing it in insomnia
I have an sql server database that has mainly 3 tables and I want to create a crud web interface to manage it and I started with creating a Django api for the backend I followed some online guides to do it since I have never done something like this and after successfully getting the Django server running without errors I sent a GET request with insomnia to fetch a specific table named "memoire" and I got an empty string as a result when that table is filled with some data in my database and I don't where the problem might be I will attach the database settings in settings.py, the model.py file and views.py and if any further details are needed I will add them. this is database settings: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'MyDatabase', 'USER': 'django', 'PASSWORD': 'rayen1', 'HOST': 'localhost', # 'PORT':'', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'Trusted Connection': 'yes', }, } } this is models.py from django.db import models class NdfItem(models.Model): OrgShortName = models.CharField(max_length=255, null=True) prod_long_name = models.CharField(max_length=255, null=True) prod_short_name = models.CharField(max_length=255, null=True) pack_description = models.CharField(max_length=255, null=True) Category = models.CharField(max_length=255, null=True) Sub_Category = models.CharField(max_length=255, null=True) ret_price = models.FloatField(null=True) ImageSrc = … -
'DeferredAttribute' object has no attribute
im newbie in django.. i dont know why it's raise an error its models.py codes class PublishManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Post.Status.Draft) # Create your models here. # First Model class Post(models.Model): class Status(models.TextChoices): Draft = 'Dr', "Draft" Released = 'RL', "Released" Rejected = 'RJ', "Rejected" # Managers objects = models.Manager() Publishedss = PublishManager() # Author Author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="up") # information title = models.CharField(max_length=200) description = models.TextField(max_length=9000) Slug = models.SlugField(max_length=250) # Timing published = models.DateTimeField(timezone.now) created = models.DateTimeField(auto_now_add=True) Updated = models.DateTimeField(auto_now=True) # Status Status = models.CharField(max_length=2, choices=Status.choices, default=Status.Draft) # Sorting class Meta: ordering = ["-published"] indexes = [ models.Index(fields=['-published']) ] def __str__(self): return self.title raise an error and it's detail codes def post_detail(request, id): print(id) posts1 = get_object_or_404(Post, id=id, status=Post.Status.Draft) context = { "Post": posts1 } return render(request, "blog/detail.html", context) AttributeError at /blog/post/1 'DeferredAttribute' object has no attribute 'Draft' Request Method: GET Request URL: http://127.0.0.1:8000/blog/post/1 Django Version: 5.0.4 Exception Type: AttributeError Exception Value: 'DeferredAttribute' object has no attribute 'Draft' Exception Location: D:\Python\Python\Projects\project1\blog\views.py, line 24, in post_detail Raised during: blog.views.post_detail Python Executable: D:\Python\Python\Projects\project1\venv\bin\python.exe Python Version: 3.11.7 Python Path: ['D:\Python\Python\Projects\project1', 'C:\Program Files\JetBrains\PyCharm ' '2023.3.5\plugins\python\helpers\pycharm', 'D:\Python\Python\Projects\project1', 'C:\msys64\ucrt64\lib\python311.zip', 'C:\msys64\ucrt64\lib\python3.11', 'C:\msys64\ucrt64\lib\python3.11\lib-dynload', 'D:\Python\Python\Projects\project1\venv\lib\python3.11\site-packages'] Server time: Thu, 25 Apr 2024 08:14:02 +0000 -
views takes the values from template before making the post method
I'm creating a odd one out game. Basically user are presented with four pics , one being the odd one when user selects the odd picture score gets increased by 1. The problem I'm having is I'm sending 4 pics with one odd picture to the template . the template picks the same ids of 3 pictures but the id of odd picture is random (i want odd picture's id to be same as odd picture id). view.py is: def odd_one_out_game(request): # Get a random country country = random.choice(Country.objects.all()) print("Selected country:", country) # Get three random pictures from the selected country pictures = list(Picture.objects.filter(country=country).order_by('?')[:3]) print("Pictures from selected country:", pictures) # Get one random picture from a different country other_country = random.choice(Country.objects.exclude(pk=country.pk)) other_picture = random.choice(Picture.objects.filter(country=other_country)) other_picture_id = other_picture.id print(other_picture_id) print("Random picture from other country:", other_picture) # Add the other picture to the list of pictures pictures.append(other_picture) print("All pictures:", pictures) # Shuffle the pictures to mix up the order random.shuffle(pictures) print("Shuffled pictures:", pictures) #get the ids of the pictures picture_ids = [picture.id for picture in pictures] print("Picture IDs:", picture_ids) odd_score = request.session.get('odd_score', 0) total_guesses = request.session.get('total_guesses', 0) message = "" # Initialize message variable print("Initial score:", odd_score, "Initial total guesses:", total_guesses) if … -
For Django, 'sql_server.pyodbc' isn't an available database backend or couldn't be imported
I'm new to Django and trying to set up a DB Connection with SQL server db. Earlier we had mysql which was working fine, I'm having trouble connecting to sql server DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'AAAAA', 'USER': 'AAAAA', 'PASSWORD': 'AAAAA', 'HOST': 'AAAAA', 'PORT': '1433', } } Error: django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Tried https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/install-microsoft-odbc-driver-sql-server-macos?view=sql-server-ver16 doesn't work. Also, I have 2 question Is it a good idea to use third party library/drivers for SQL server? will it affect the performance compared to Mysql? -
UnboundLocalError: cannot access local variable 'form' where it is not associated with a value
I can't pass the form value into my template file, my views.py file: def Home(request): chat_group = get_object_or_404(GroupChat,group_name='TalkAboutPython') chat_message = chat_group.chat_message.all()[:30] if request.method == "POST": form = ChatMessageCreateForm(request.POST) if form.is_valid(): chat =form.save(commit=False) chat.auther = request.user chat.group = chat_group chat.save() return redirect('home') context = {"chat_message":chat_message,"form":form} return render(request, 'a_realchat/chat.html',context) form.py: class ChatMessageCreateForm(ModelForm): class Meta: model = GroupMessage fields = ['body'] I am passing the form to my .html file <form id="chat_message_form" method='POST' class="w-full"> {% csrf_token %} {{ form }} </form> when I try to send a message in the form Iam getting this error "cannot access local variable 'form' where it is not associated with a value" error showing here context = {"chat_message":chat_message,"form":form} -
How can I update data in vue.js?
I am new to vue.js and I try to update data. I write this code for pencil icon <i class="mdi mdi-pencil" v-b-modal.updateHolidayType ></i> I write this for modal <b-modal id="updateHolidayType" title="Update holiday" centered hide-footer> <ModalForm cardTitle="Update holiday" description="Update holiday" :holiday="holiday" @holidayUpdated="holidayUpdated"/> </b-modal> and this for form EditForm() { const holidayTypesId = this.holidayTypes .filter((e) => e.title === this.holidayTypeValue) .map((item) => item.id); session .put(`api/person/holiday/${this.holidayId}/update/`, { holidays_start_date: this.startDate, holidays_end_date: this.endDate, comments: this.comments, person: this.$route.params.id, holiday_type: holidayTypesId, }) .then(() => { this.alertShow = !this.alertShow; this.alertVariant = 'success'; this.alertMsg = 'Updated'; setTimeout(() => { this.$emit('holidayUpdated'); }, 1500); }) .catch((e) => { this.alertShow = !this.alertShow; this.alertVariant = 'danger'; this.alertMsg = e.response.data; }); } But when I click on pencil I go in empty page. When I click on pencil I want the page to show a modal which have the data and I can edit them. How can I do this? -
what is the meaning of this query in django
I am working on a django project, and taking over the project from other developers as they have left the project. I came across a query which I am not able to understand how it works, This is the query in question. provider_evaluations = ProviderEvaluation.objects.filter( customer_provider_relation_id__projectproviders__project_id=project_id, customer_provider_relation_id__provider_id=provider_id, and these are the models included in the query. class ProviderEvaluation(models.Model): provider_evaluation_criterias_id = models.ForeignKey(ProviderEvaluationCriterias, on_delete=models.CASCADE, null=True) evaluation = models.CharField(max_length=255, null=True) comment = models.TextField(null=True, blank=True) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True) workflow_step = models.ForeignKey(WorkflowStep, on_delete=models.CASCADE, default=None, null=True) customer_provider_relation_id = models.ForeignKey(CustomerProviderRelation, on_delete=models.CASCADE, null=True, default=None) def __str__(self): return f"{self.provider_evaluation_criterias_id} - {self.evaluation}" class CustomerProviderRelation(models.Model): customer_tenant_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, related_name='customer_tenant', limit_choices_to={'model__in': ['customer']}, ) provider_tenant_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, related_name='provider_tenant', limit_choices_to={'model__in': ['provider']}, ) customer_tenant_id = models.PositiveIntegerField() provider_tenant_id = models.PositiveIntegerField() customer_tenant = GenericForeignKey('customer_tenant_type', 'customer_tenant_id') provider_tenant = GenericForeignKey('provider_tenant_type', 'provider_tenant_id') customer_id = models.ForeignKey(Customer, on_delete=models.CASCADE) provider_id = models.ForeignKey(Provider, on_delete=models.CASCADE) def save(self, *args, **kwargs): # Assign values to content type and object ID fields based on the instance being saved if isinstance(self.customer_tenant, Customer): self.customer_tenant_type = ContentType.objects.get_for_model(Customer) self.customer_tenant_id = self.customer_tenant.id if isinstance(self.provider_tenant, Provider): self.provider_tenant_type = ContentType.objects.get_for_model(Provider) self.provider_tenant_id = self.provider_tenant.id super().save(*args, **kwargs) def __str__(self): return f"CustomerProviderRelation ID: {self.id}" class ProjectProviders(models.Model): STATE_CHOICES = [ ('searched', 'Searched'), ('initiated', 'Initiated'), ('completed', 'Completed'), ('closed', 'Closed'), ('rejected', 'Rejected'), ] project_id = … -
django with order by receiving duplicate data
I don't know what is happening here already. I can't figured this out. I am using a pagination and fetching a lot of data in my Person model. I have sort from descending order and ascending order but when the data is returned and i go to other pages of my pagination, i keep receiving multiple duplicates of data from the other pages. Why? Can anyone explain or solution for this? Here is my code: def get_queryset(self, *args, **kwargs): if self.request.user.team: queryset = self.request.user.team.leads.all() else: queryset = super().get_queryset(*args, **kwargs) ordering = self.request.query_params.get("ordering", "") if ordering == "total_email_sent": queryset = ( queryset.annotate( total_email_sent=Count( "prospectsequenceevent__scheduledEmail", filter=Q( prospectsequenceevent__status="scheduled", prospectsequenceevent__scheduledEmail__status=0, ), ) ) .distinct() .order_by("total_email_sent") ) elif ordering == "-total_email_sent": queryset = ( queryset.annotate( total_email_sent=Count( "prospectsequenceevent__scheduledEmail", filter=Q( prospectsequenceevent__status="scheduled", prospectsequenceevent__scheduledEmail__status=0, ), ) ) .distinct() .order_by("total_email_sent") ) elif ordering == "total_opened": queryset = ( queryset.annotate( total_opened=Count( "emails", filter=models.Q( emails__trackings__opened=True, emails__created_by=self.request.user, ), ) ) .distinct() .order_by("total_opened") ) elif ordering == "-total_opened": queryset = ( queryset.annotate( total_opened=Count( "emails", filter=models.Q( emails__trackings__opened=True, emails__created_by=self.request.user, ), ) ) .distinct() .order_by("-total_opened") ) elif ordering in ["total_click_count", "-total_click_count"]: # Use conditional aggregation to calculate total click count queryset = queryset.annotate( total_click_count=Coalesce( Sum( Case( When( emails__created_by=self.request.user, then=F("emails__click_tracking__click_count"), ), default=Value(0), output_field=IntegerField(), ) ), Value(0), ) ).distinct() … -
Heroku: H18 right before my app should download .mp4
I'm having trouble with my app that generates 5-8sec videos. The entire request takes about 15 seconds, the app does all the steps required, but when it's time to download the video file it fails. I'm deploying the same python version as I run locally python-3.11.5. I'm running the app right now as we speak locally with no issue. Web console returns this error: generate-reel/:1 Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH (index):562 Error in generating reel: TypeError: Failed to fetch Headers have both Content-Length and Content-Type correctly, but when I go to "Response" theres nothing... I copied header: Request: POST /generate-reel/ HTTP/1.1 Accept: */* Accept-Encoding: gzip, deflate, br, zstd Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Connection: keep-alive Content-Length: 14 Content-Type: application/json Cookie: sessionid=lcjfb0cgcd0fzth59hd95wg7g4jcl9m5; csrftoken=DcqP62fbGQkoyKTdR1tWnUrF2degrOLD; lastReset=Thu Apr 25 2024; usageCount=3 Host: vast-everglades-19722-937b6a99a857.herokuapp.com Origin: https://vast-everglades-19722-937b6a99a857.herokuapp.com Referer: https://vast-everglades-19722-937b6a99a857.herokuapp.com/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 X-CSRFToken: DcqP62fbGQkoyKTdR1tWnUrF2degrOLD sec-ch-ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99" sec-ch-ua-mobile: ?0 sec-ch-ua-platform: "macOS" Response: HTTP/1.1 200 OK Report-To: {"group":"heroku-nel","max_age":3600,"endpoints":[{"url":"https://nel.heroku.com/reports?ts=1714013226&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=yq0l506BqIrW%2F3MHhVj%2Bj2D7GdjU4YvL1xFQNDkYycQ%3D"}]} Reporting-Endpoints: heroku-nel=https://nel.heroku.com/reports?ts=1714013226&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=yq0l506BqIrW%2F3MHhVj%2Bj2D7GdjU4YvL1xFQNDkYycQ%3D Nel: {"report_to":"heroku-nel","max_age":3600,"success_fraction":0.005,"failure_fraction":0.05,"response_headers":["Via"]} Connection: keep-alive Server: gunicorn Date: Thu, 25 Apr 2024 02:47:23 GMT Content-Type: video/mp4 X-Frame-Options: DENY Content-Length: 8478634 Vary: Cookie X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Set-Cookie: sessionid=lcjfb0cgcd0fzth59hd95wg7g4jcl9m5; expires=Thu, 09 … -
When i press edit profile i get value error
trying to make an edit page where you can upload a profile picture and add various things to your profile, but when i click on edit profile i get "ValueError at /profile/ The 'profile_image' attribute has no file associated with it." models.py from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=50, null= True) designation = models.CharField(max_length=100, null= True) profile_image = models.ImageField(null=True, blank = True, upload_to="static/images/") profile_summary = models.TextField(max_length=300, null= True) city = models.CharField(max_length=100, null= True) state = models.CharField(max_length=100, null= True) county = models.CharField(max_length=100, null= True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() urls.py from .views import HomeView, UserProfile, register, user_login, user_logout from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("", HomeView.as_view(),name="home-page"), path("profile/", UserProfile.as_view(), name="user-profile"), path("register/", register, name="register"), path("login/", user_login, name="login"), path("logout/", user_logout, name="logout"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from .forms import RegisterForm from django.contrib.auth.forms import AuthenticationForm from django.contrib import messages from .models import Profile from django.core.files.base import ContentFile class HomeView(View): def get(self, request): return render(request, "home.html") def register(request): … -
ModuleNotFoundError: No module named 'project_name'
I tried to make 'load_data.py' file, but error confound me. Traceback (most recent call last): File "/Users/name/Downloads/Dev/culture/culture/api/load_data.py", line 4, in <module> from models import Theatre File "/Users/name/Downloads/Dev/culture/culture/api/models.py", line 4, in <module> class Theatre(models.Model): ... ModuleNotFoundError: No module named 'culture' The project has only one app 'api' and 'load_date.py' in it. Project name is 'culture'. settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', ] i tried export DJANGO_SETTINGS_MODULE=culture.settings but it didnt help. -
Single dropdown with values from two tables
I may be going about this entirely wrong. I'm new to Django, so sometimes the way I think of things doesn't seem to be the easy Django way to do it. I've got two tables: class LocationGroup(models.Model): #Fields ##Location Group ID - auto generated ID field id = models.AutoField('Location Group ID', primary_key = True) ##Location Group Name name = models.CharField('Location Group Name', max_length=200, help_text='Location Group name') def __str__(self): """String for representing the Model object.""" return self.name class Meta: verbose_name = "Location Group" verbose_name_plural = "Location Groups" and class Location(models.Model): #Fields ##Location ID - auto generated ID field id = models.AutoField('Location ID', primary_key = True) ##Location name name = models.CharField('Location Name', max_length=200, help_text='Location name') ##Location Group - link location to a Location Group group = models.ManyToManyField('LocationGroup', verbose_name='Location Group', blank=True, help_text='...') ...etc Then I have my forms.py calling as follows: class MyForm(forms.ModelForm): class Meta: model = Call fields = ['location', ...etc] This all works well and I can pick a location and add it to the database with the other values that are on that form/model. But what I'd like to do, is include the values from the locations plus the location groups. And to go further, if a value is picked … -
Django: how to store email credentials when sending email from a Django application
What is a standard or safe way to store my Google Workspace email credentials in my first Django project? I've tried to store the password in an .env file, but I get all kinds of error messages (e.g., "decouple module not recognized"--despite my alternately using pip install decouple and pip install python-decouple). But more importantly, I suspect it's not the best approach anyway. My research seems to whittle the options down to eliminating my password altogether and to somehow API into Google from within my app (to send out emails to my customers from my Google Workspace email). Is that would you recommend? Is there an simpler/better way?