Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i couldnt redirecting my django app from int to string in the url
I'm having trouble with my Django URL patterns. The URL exercise4/1/ is not matching any of my defined patterns, even though I have a pattern defined for exercise4/int:month/. Can you help me figure out why it's not matching?" from django.shortcuts import render from django.http import HttpResponseNotFound,HttpResponse,HttpResponseRedirect month_chalenge = { 'JAN': 'IT IS NEW YEAR CONGRATS', 'FEB' : 'WELCOME TO NEW MONTH OF FEBURARY', 'APRIL': 'FASTING MONTH', 'MAY': 'EDEPENDENCE DAY' } def month_chalenge_bynumber (request,month): months = list( month_chalenge.keys()) redirect_month = months[month-1] return HttpResponseRedirect("/exercise4/"+ redirect_month) def monthchalenge(request,month): try: chalenge_list = month_chalenge[month] return HttpResponse(chalenge_list) except: return HttpResponseNotFound('sorry ! we dont have data for this data') -
djangos cmd like how do i make my C:\Users\user\Desktop\djangodemo> go into C:\Users\user\Desktop\DjangoCourse\djangodemo>
enter image description here enter image description here its little different since i had to start another one but i encounter '[Errno 2] No such file or directory' and it has become quite the problem for me so do y'all have any suggestions? well i have asked couple of people but they couldn't explain it well since they aren't sure themselves what causes the error to happen and i do not have solution for it so i would appreciate some suggestions or help from this community :) -
Filter a query set depending on state at a given date
Given the following model (using django-simple-history): class MyModel (models.Model): status = models.IntegerField() history = HistoricalRecords() I would like to get all instances that didn't have a certain status on a given date (i.e. all instances that had a different status on the limit date, plus all instances that didn't exist at that time). The following query will return all instances that never had status = 4 at any point before the limit date: MyModel.filter (~Exists ( MyModel.history.filter ( id = OuterRef ("id"), history_date__lte = limit_date, status = 4)) But unfortunately it also removes instances that had status = 4 at some past date, then changed to a different status by the limit date, and I want to keep those. The following should give the correct result: MyModel.filter (~Exists ( MyModel.history.filter ( id = OuterRef ("id"), history_date__lte = limit_date) .order_by ("-history_date") [:1] .filter (status = 4))) Unfortunately it doesn't work: Cannot filter a query once a slice has been taken. This question links to this documentation page which explains that filtering is not allowed after the queryset has been sliced. Note that the error comes from an assert in Django. If I comment out the assert in django/db/models/query.py:953, then the code … -
I want to link my subcategory to relevant category in forms.py? How to do that?
enter image description here dasdasdadadsadsadasdadadasdaadsdasdadasarasdfadkdvskfds and dasfkasfkfas mdasjkdkad;ksla;kdk;l sfkdlfkslkdflkslkdfs, kfslkdfsdfsdfsfsdfs and asffasfaskmfakmsfmkakmfsfas asfdsfds ewsf asd asdada dasdas dasdasd -
Setting page layout to landscape at specific page or after appendPageBreak() in google doc file using google app script
I have a google doc template file named 'TemplateDOC' which will append a paragraph heading at last "11. Annex of Google Sheet Records." at page 11 after appendPageBreak(). I need to set the page layout landscape so I can insert data range from a googlesheet named 'logDATA'. The code goes like this but the result is null, please help to reach out the solution. body.appendPageBreak(); body.appendParagraph("\n11. Annex of Google Sheet Records."); var paragraphs = body.getParagraphs(); var pageCounter = 1; var switchToLandscape = false; for (var pLen = 0; pLen < paragraphs.length; pLen++){ var paragraph = paragraphs[pLen]; if(paragraph.getText() == "11. Annex of Google Sheet Records." ){ switchToLandscape = true; break; } } if(switchToLandscape && paragraph.getType() == DocumentApp.ElementType.BODY_SECTION){ pageCounter++; } if(pageCounter==11){ var element = paragraph; var parent = element.getParent(); if(parent.getType()==DocumentApp.ElementType.BODY_SECTION){ var attribute = {}; attribute[DocumentApp.Attribute.PAGE_WIDTH]=792; attribute[DocumentApp.Attribute.PAGE_HEIGHT]=612; parent.setAttributes(attribute); } -
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() …