Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model with multi foreign key takes too long to load with forms.ModelChoiceField
My first question after years of searching in stackoverflow ! I have a django project for student marks. Models: class Registration(CMTracking): student = models.ForeignKey(Student, on_delete=models.CASCADE) academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE) school = models.ForeignKey(School, on_delete=models.CASCADE) grade = models.CharField(max_length=5, choices=Grade.choices) school_class = models.ForeignKey(SchoolGradeClass, on_delete=models.CASCADE, blank=True, null=True) last_year_result = models.PositiveSmallIntegerField(choices=RESULT.choices, blank=True, null=True) last_grade = models.CharField(max_length=5, choices=Grade.choices, null=True) date_of_join = models.DateField(null=True, blank=True) type_of_registration = models.PositiveSmallIntegerField(choices=TypeOfRegistration.choices, default=0, null=True) type_of_attendance = models.PositiveSmallIntegerField(choices=TypeOfAttendance.choices, null=True) transfer_from = models.PositiveSmallIntegerField(choices=TransferFrom.choices, blank=True, default=1) status = models.PositiveSmallIntegerField(choices=RequestStatus.choices, default=0) class Exam(CMTracking): fa_name = models.CharField(max_length=70, null=False) en_name = models.CharField(max_length=70, null=False) ar_name = models.CharField(max_length=70, null=False) total_mark = models.DecimalField(max_digits=5, decimal_places=2, default=0) exam_type = models.PositiveSmallIntegerField(choices=ExamType.choices) academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE) class ExamSubject(CMTracking): exam = models.ForeignKey(to=Exam, on_delete=models.CASCADE) subject = models.ForeignKey(to=SubjectMaster, on_delete=models.CASCADE) teacher = models.ForeignKey(Staff, related_name='ExamSubjectList', on_delete=models.CASCADE) # Namavar school_class = models.ForeignKey(SchoolGradeClass, on_delete=models.CASCADE, blank=True, null=True) min = models.PositiveSmallIntegerField(null=True) max = models.PositiveSmallIntegerField(null=True) class MarkDescriptive(CMTracking): subject = models.ForeignKey(ExamSubject, on_delete=models.CASCADE) student = models.ForeignKey(Registration, related_name='mark_list_descriptive', on_delete=models.CASCADE) goal = models.ForeignKey(to=SubjectGoalsMaster, on_delete=models.CASCADE) point = models.FloatField(null=True, blank=True) t2point = models.FloatField(null=True, blank=True) form: class MarkDescriptiveModelForm2(forms.ModelForm): student = forms.ModelChoiceField(queryset=Registration.objects.all().select_related('student__person').filter(school_id=106), required=False) # student = forms.IntegerField() # only shows the id goal = forms.ModelChoiceField(queryset=SubjectGoalsMaster.objects.all(), required=False) point = forms.ChoiceField(choices=DescriptivePoint5.choices) t2point = forms.ChoiceField(choices=DescriptivePoint5.choices) class Meta: model = MarkDescriptive fields = ['id', 'student', 'point', 't2point'] View : @login_required() @require_http_methods(['POST', 'GET', 'PUT']) def mark_descriptive_update(request, exam_subject_id=None, goal_id=None): … -
redirect on the same post_id after edit post
I have created a forum website in Django where users can post Questions/Answers and edit them. After editing the reply I want to redirect the user to the currently edited post page. like if user edit reply which has been posted on the question with id 4 (which url is (http://127.0.0.1:8000/discussion/4)) then after edited it should redirect to the same url Post view.py def forum(request): user = request.user profile = Profile.objects.all() if request.method=="POST": form=PostContent(request.POST) if form.is_valid(): user = request.user image = request.user.profile.image content = request.POST.get('post_content','') post = Post(user1=user, post_content=content, image=image) post.save() messages.success(request, f'Your Question has been posted successfully!!') return redirect('/forum') else: form=PostContent() posts = Post.objects.filter().order_by('-timestamp') form= PostContent() context={ 'posts':posts, 'form':form } return render(request, "forum.html",context) reply view.py def discussion(request, myid): post = Post.objects.filter(id=myid).first() replies = Replie.objects.filter(post=post) if request.method=="POST": form=ReplyContent(request.POST) if form.is_valid(): user = request.user image = request.user.profile.image desc = request.POST.get('reply_content','') post_id =request.POST.get('post_id','') reply = Replie(user = user, reply_content = desc, post=post, image=image) reply.save() messages.success(request, f'Your Reply has been posted successfully!!') return redirect(f'/discussion/{post_id}') else: form=ReplyContent() form= ReplyContent() return render(request, "discussion.html", {'post':post, 'replies':replies,'form':form}) Edit reply view def edit_reply(request, pk): reply = Replie.objects.get(id=pk) if request.method == 'POST': form = UpdateReplyForm(request.POST, instance=reply) if form.is_valid(): form.save() messages.success(request,"Reply updated successfully!") return redirect('/forum') else: form = UpdateReplyForm(instance=reply) context … -
An error while changing text with javascript
I'm using google recaptcha with my django project. But it is not English. So I want to change its writing with javascript. html {% extends 'base.html' %} {% block content %} <div class="form-body"> <div class="row"> <div class="form-holder"> <div class="form-content"> <div class="form-items"> <h1>Registration</h1> <br><br> <form class="requires-validation" method="POST" novalidate> {% csrf_token %} {{form.as_p}} <div class="form-button"> <button id="submit" type="submit" class="btn btn-primary">Register</button> </div> </form> </div> </div> </div> </div> </div> <script type="text/javascript"> document.querySelector('recaptcha-anchor-label').innerHTML = "I'm not a robot"; </script> {% endblock %} After I did that it won't apply the html in browser. Below the error message: Cannot set properties of null (setting 'innerHTML') -
I have to create a website to decode Invoice QR codes
I have to create a website to decode Invoice QR codes. Is there any module using Python, Java, and JavaScript? I searched more for Python and I also have created a website using the python module which is pyzbar to decode QR codes and then I used jwt module which has a decode function to decode the QR code into a readable format such as '{'data': '{"SellerGstin": "27AAACB5724H1ZU", "BuyerGstin": "27AAHCS2420A1ZX", "DocNo": "MK20040946"}'. -
Is it possible to store images as BLOB in MySQL database using Django models?
I want to store images in MySQL Database (not the path, the actual image) using Django as the backend and React js as the frontend. Is it possible to do that? Please help me in resolving this issue. Thanks in advance. -
How does django-simple-captcha really work?
I have been trying to implement django-simple-captcha to my Django project for a while and I just can't get it in. Many of the questions related to it are many years old, so I wonder if it is still functional. I tried following the docs but that was no better than some of the questions here. A lot of people remark on how easy it is to install but I've tried so many times and ways that I am confused. This question here is just one of many like I described earlier. Using django-simple-captcha with django-lazysignup? Can someone please tell me what I am doing wrong? I suspect that I am not validating the captcha properly in my views.py. I have added 'captcha' to my installed apps in my settings.py. settings.py INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'taggit', 'crispy_forms_gds', 'captcha', 'django.forms', ] In my forms.py I added it just like I've seen in the docs and other questions. forms.py from captcha.fields import CaptchaField, CaptchaTextInput class PostForm(forms.ModelForm): captcha = CaptchaField() class Meta: model = Post fields = [ 'title', 'content', 'image', 'video', 'url', 'tags', ] views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = … -
I'm trying to build a Django query that will sum multiple categories in to one distinct category
I have a model called Actuals with a field called category which is unique, and another model called Budget which is a many to many field in the Actuals Model. A user can select a unique category in budget and select it in actuals so there can be many actuals to a budget. I am trying to create a query that will group and Sum 'transaction_amount' by category in Actuals model. class Actuals(models.Model): category = models.ForeignKey(Category,on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=False) transactions_amount = models.IntegerField() vendor = models.CharField(max_length = 255,default="") details = models.CharField(max_length = 255) budget = models.ManyToManyField('budget') def __str__(self): return self.category.category_feild This is the query that I currently have. However it still gives me multiple categories lub = Actuals.objects.filter(category__income_or_expense = 'Expense', date__year = "2022" ,date__month = "01").values('category__category_feild','date').order_by('category__category_feild').annotate(total_actuals = Sum('transactions_amount')).annotate(total_budget = Sum('budget__budget_amt')) This is the output. There should only be one line for "Fun" and one line for "Paycheck". <QuerySet [<Actuals: Fun>, <Actuals: Fun>, <Actuals: Paycheck>, <Actuals: Paycheck>]> -
Employee model details not showing in navbar in django template
I have an issue showing my Employee name and picture in navbar.html I have a CustomUser model from accounts app structure as below core |_accounts |_models.py (CustomUser is in here) | |_employees |_models.py (Employee model in here) My CustomUser is as below class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email and my employee model is class Employee(models.Model): # PERSONAL DATA user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="employees") title = models.CharField(_('Title'), max_length=10, default='Mr', choices=TITLE, blank=False, null=True) image = models.ImageField(_('Profile Image'), upload_to='avatars/', blank=True, null=True, help_text='upload image < 2.0MB')#work on path username-date/image firstname = models.CharField(_('Firstname'), max_length=125, null=False, blank=False) lastname = models.CharField(_('Lastname'), max_length=125, null=False, blank=False) In my navbar template I have <img alt="image" src="{{ request.user.employees.image.url }}" class="user-img-radious-style"> and <div class="dropdown-title">Hello {{ request.user.firstname }}</div> My template is not showing the desired results -
503 error while uploading django project in server
I've program written in django and tried to upload in server i've uploaded the project in cpanel and tried to setup in python app in first image there is command to run in terminal i've also tried doing that now i'm getting 503 service unavailable This is my first time hosting so i dont know that is going wrong!! https://prnt.sc/Dy4PiphauS1c https://prnt.sc/aRVB9NDgdWzx https://prnt.sc/osZW-oDow123 -
Gunicorn does not display updated logs. But once I restart gunicorn service it shows all the logs
I went through multiple stack overflow questions and blogs for this issue and tried the answers available but no success. Below is my gunicorn service socket and ngnix config settings. Please help me out have been stuck on this for almost 1 week. gunicorn.socket [Unit] Description=IPU socket [Socket] ListenStream=/run/IPU.sock [Install] WantedBy=sockets.target gunicorn.service [Unit] Description=IPU daemon Requires=IPU.socket After=network.target [Service] User=ubuntu Group=ubuntu WorkingDirectory=/project/path ExecStart=/../../venv/bin/gunicorn \ --bind unix:/run/IPU.sock \ --capture-output \ --workers 4 \ --worker-class gevent \ --worker-connections 1000 \ --timeout 300 \ --access-logfile /path/to/log/access.log \ --error-logfile /path/to/log/error.log \ IPU.wsgi:application [Install] WantedBy=multi-user.target nginx.conf server { listen 9000 default_server; listen [::]:9000 default_server; server_name ip_address; rewrite_log on; location = /favicon.ico { access_log off; log_not_found off; } location /IPU/ { include proxy_params; proxy_pass http://unix:/run/IPU.sock:/; } } -
Filter on single element transformed value of ArrayField
Assuming I have the following Models defined: from django.db import models from django.contrib.postgres.fields import ArrayField from django.db.models import Func, F class SingleDayEvent(models.Model): title = models.TextField() day = models.DateField() class MultiDayEvent(models.Model): title = models.TextField() days = ArrayField(models.DateField(), default=list) If I want a queryset with all SingleDayEvent in a given calendar week, I would do: SingleDayEvent.objects.filter(day__week = week) How can I achieve the same for the MultiDayEvent defined above? -
How can I use two Django authentication backends and give different access depending on which is used?
I have two different classes of user for a Django-based event registration system. Let's call them "Registrant" and "Staffer". These two are not mutually exclusive, and I see no reason not to use the same User model for both classes (with a flag to distinguish them). A Registrant can sign in by verifying their identity with a third-party API, and can then register for an event. A Staffer has access to Django Admin, and can manage events. I do not trust the third-party API to sufficiently authenticate somebody who has Staffer access as, while it does request personal information to identify someone, it doesn't ask for anything as secure as a password. I therefore want Staffers to enter in a password instead of authenticate via the third-party API. I see that I can write a custom auth backend in Django, and I can customise the default User model to suit my needs regarding aforementioned flags (though I suspect the default is_staff) flag might be sufficient). Unfortunately, while I know that I can use multiple authentication backends, I am quite stuck working out how to: a) determine which authentication backend to use (e.g. use the Registrant auth backend in the frontend, … -
Django-Graphql mutation works in Playground but Returns null in ReactJS-Apollo
I making a simple update mutation from Graphql Playground, and I believe that if the mutation is working from playground, Hence there is no issue in backend. mutation{ emwCustomMessageToCustomerUpdate( id:"RU1XQ3VzdG9tSW5mb3JtYXRpb25Gb3JDdXN0b21lcjoxNQ==", input:{ isActive:false, allowClose:false, message:"asdfssdf", displayLocation:"S1", messageHeader:"Dsfsdf" }){ eMWInformationForCheckout{ message } errors{ message } } } Which returns this response indicating call is success, I could verify that. { "data": { "emwCustomMessageToCustomerUpdate": { "eMWInformationForCheckout": { "message": "asdfssdf" }, "errors": [] } } } But when I call this mutation from reactjs-apollo, It is not mutating the data, I am mutating a single key, But it makes other keys to null. The mutation i am using from react is : export const UpdateMessageForCustomer = gql` mutation UpdateMessageForCustomer( $id: ID! $message: String $startDate: DateTime $endDate: DateTime $allowClose: Boolean $displayLocation : String $buttonText : String $screenPlacement : String $messageHeader : String $isActive : Boolean ){ emwCustomMessageToCustomerUpdate(id: $id, input:{ message: $message startDate: $startDate, endDate: $endDate, allowClose: $allowClose, displayLocation : $displayLocation buttonText : $buttonText screenPlacement : $screenPlacement messageHeader : $messageHeader isActive : $isActive }){ eMWInformationForCheckout{ message } errors{ message } } } ` function used to mutate in react component const [UpdateMessageForCustomerMutation] = useMutation(UpdateMessageForCustomer, { onCompleted({ emwCustomMessageToCustomerUpdate }) { if (emwCustomMessageToCustomerUpdate.errors.length) { notify({ text: intl.formatMessage({ defaultMessage: … -
How to fetch webcam data from client side and send to django server for storage and face recognition?
I want to create an app where I can store images and then detect faces. I am using Django. Now I don't know how to send this webcam data to the Django server for further processing with OpenCV. It would be appreciated if someone can write tell how to proceed when the attain img button is clicked. <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible"> {% load static %} <link rel="stylesheet" href={% static 'camera.css' %}> <title>Capture</title> </head> <body> <div class="cameraElement"> <video id="webcam" width="1200" height="600" autoplay></video> </div> <div class="buttonElement-train"> <button type="submit" class="btn-hover color-1" id="train">Train Images &#x2192</button> </div> <div class="buttonElement-back"> <button type="submit" class="btn-hover color-2" id ="back" onclick="window.location.href = '{% url 'reg' %}' ">&#x2190 Back</button> </div> Script part:- <script> let video=document.querySelector("#webcam"); if (navigator.mediaDevices.getDisplayMedia) { navigator.mediaDevices.getUserMedia({ video:true}) .then(function (stream) { video.srcObject = stream; }) .catch(function (error) { console.log("ERROR") }) } </script> views part:- def train_img(request): return render(request, "camera.html") -
Querying a relational table in Django database
I have an database with a relational table created by my Models. This table has all the information I'm trying to query, but I'm having a difficult time getting the values from it that aren't objects of the Model. Models.py class Ingredient(models.Model): '''All ingredients for any recipe or individual selection''' ingredient = models.CharField(max_length=50) department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL) def __str__(self): return self.ingredient class IngredientDetail(models.Model): '''A class to identify variable quantities of ingredients''' recipe = models.ForeignKey('Recipe', null=True, on_delete=models.SET_NULL) ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL) quantity = models.CharField(max_length=1) class Meta: verbose_name_plural = 'Ingredient Details' def __str__(self): return self.quantity class Recipe(models.Model): '''A Recipe class to input new recipes''' recipe = models.CharField(max_length=50) ingredients = models.ManyToManyField(Ingredient, through=IngredientDetail) instructions = models.TextField(null=True) cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL) picture = models.ImageField(upload_to= 'media/', null=True, blank=True) def __str__(self): return self.recipe It creates the following table, which has the info I need: ID quantity ingredient_id recipe_id 1 1 5 5 2 1 6 5 3 2 7 5 When I try to query Ingredient details with IngredientDetails.objects.filter(recipe_id='5'), it only gives me the values for quantity, and I also need the ingredient_id. Did I structure my models incorrectly, or have I overlooked an obvious solution to this? Ideally, I'd like to be able … -
azure app service treating websocket request as http and hence not found
So when a 'ws' request hits my django server on azure app service in logs it shows 2022-05-27T03:40:41.606708018Z Not Found: /tm/123 2022-05-27T03:40:41.608467127Z 169.254.130.1 - - [27/May/2022:03:40:41 +0000] "GET /tm/123 HTTP/1.1" 404 4190 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36" So this may be due to daphne service is not on in my server environment when I put a startup command for daphne it gives error -
verbose_name vs verbose_name_plural (Django)
I created "Category" model with "verbose_name" and "verbose_name_plural" following some tutorial as shown below: # "store/models.py" from django.db import models class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name = "category" verbose_name_plural = "categories" Then, the plural model name "Categories" is displayed in Django Admin as shown below: Then, to display the singular model name "Category", I removed "verbose_name_plural" as shown below: # "store/models.py" from django.db import models class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name = "category" # verbose_name_plural = "categories" But, the model name is "Categorys" instead of "Category" in Django Admin as shown below: Now, my questions are: What is the difference between "verbose_name" and "verbose_name_plural"? How to use "verbose_name" and "verbose_name_plural" properly? How to display the singular model name "Category" in Django Admin? -
How can I add data to my django db. Using excel as an input, I extracted the data but i don’t know to go store it in the database
#help me with this ,I have two models patient and doctor . Have extracted the data using xlrd, and got a dictionary with d ={“name”:list of names,”number”: list of numbers , so on } #Have used a forms.form model -
How to download .two txt file as zip?
I want to download the test.txt and text1.txt as dynamically created zip file. test.txt and test1.txt file load from the base dir of my project.when i called function, no error occurs and status will 200. can anybody correct me for extract zip file of test.txt and test1.txt. # # FIXME: Change this (get paths from DB etc) filenames = [] #load the test.txt file from base directory filename1 = os.path.join(settings.BASE_DIR, 'test.txt') filename2 = os.path.join(settings.BASE_DIR, 'test1.txt') filenames.append(filename1) filenames.append(filename2) # # Folder name in ZIP archive which contains the above files # # E.g [thearchive.zip]/somefiles/file2.txt # # FIXME: Set this to something better zip_subdir = "somefiles" zip_filename = "%s.zip" % zip_subdir # # Open StringIO to grab in-memory ZIP contents # s = StringIO() s = BytesIO() # # The zip compressor zf = zipfile.ZipFile(s, "w") for fpath in filenames: # # Calculate path for file in zip fdir, fname = os.path.split(fpath) zip_path = os.path.join(zip_subdir, fname) # Add file, at correct path zf.write(fpath, zip_path) print(zf) # # Must close zip for all contents to be written zf.close() # # Grab ZIP file from in-memory, make response with correct MIME-type resp = HttpResponse(s.getvalue(), content_type = "application/zip") # # ..and correct content-disposition resp['Content-Disposition'] = … -
SQL query in django
I need to do the following sql query in django specifically in the views window, I need to filter the "Nota" according to which "Profesor" it belongs to SQL QUERY select * from nota n join profesor on (profesor.id_asignatura = n.id_asignatura) models.py class Nota(models.Model): id_nota = models.IntegerField(primary_key=True) nota = models.IntegerField() tipo_evaluacion = models.CharField(max_length=15) fecha_evaluacion = models.DateField() id_libro = models.ForeignKey(LibroClases, models.DO_NOTHING, db_column='id_libro') id_asignatura = models.ForeignKey(Asignatura, models.DO_NOTHING, db_column='id_asignatura') rut_alumno = models.ForeignKey(Alumno, models.DO_NOTHING, db_column='rut_alumno') class Meta: managed = True db_table = 'nota' class Profesor(models.Model): rut_profesor = models.IntegerField(primary_key=True) dv_profesor = models.CharField(max_length=1) p_nombre = models.CharField(max_length=15) s_nombre = models.CharField(max_length=15, blank=True, null=True) ap_paterno = models.CharField(max_length=15) ap_materno = models.CharField(max_length=15, blank=True, null=True) especialidad = models.CharField(max_length=35) fecha_contrato = models.DateField() direccion = models.CharField(max_length=25) id_colegio = models.ForeignKey(Colegio, models.DO_NOTHING, db_column='id_colegio', blank=True, null=True) id_asignatura = models.ForeignKey(Asignatura, models.DO_NOTHING, db_column='id_asignatura') id_comuna = models.ForeignKey(Comuna, models.DO_NOTHING, db_column='id_comuna') class Meta: managed = True db_table = 'profesor' Views.py def vistaProfesor(request): rut= request.user.rut_user notas = Nota.objects.select_related?????????? -
Input data django to microsoft sql
I not migrate Django to DB. But, I already connect to microsoft sql server. I have create my table. How to make crud app? -
How to paginate two models after being combined
class Book(models.Model): title = models.CharField(max_length=32, blank=True) class Read(models.Model): user = models.ManyToManyField(UserModel) book = models.ManyToManyField(Book) I want to paginate it the way first list the books user has read and then show other books without duplicates my solution is to first fetch Read based on user__id and then exclude Book where title is in Read but i have problem with pagination. -
How to get the selected text by dragging my mouse in Python?
I am trying to build a web service that enables users to copy text easily. I want to copy a selected text automatically to the clipboard when I drag the mouse. I thought I can make it easily at first with pyautogui. So I make the script in Python3 below, but it doesn't work. import pyautogui as pya import pyperclip def copy_text(): if pya.drag(): pya.hotkey('ctrl', 'c') time.sleep(.01) sentence= pyperclip.paste() return sentence var = copy_text print (var) Please help me to make it work. I know that pyautogui has mouse functions, however, it is to move the mouse automatically. I want to automate copying by dragging the mouse manually. Thank you for your help. -
Django: Adding user to a permission group more than once
I have an application containing users who can belong to multiple organizations and via a job with a certain role for each. Each role has specific permissions to control what the job can do. I plan on using Django's built-in permissions to create a permission group for each role and assign them to a user. However, it does not feel correct from a design perspective to assign a permission group to a user because the permission belongs to the job specific role which can be held across multiple organizations. This creates messy logic when a job is removed since I must also check if the user also has another job with the same role before adding or removing permissions for the user. Is there a way to add a user to a permission group multiple times. E.g once for each role they hold across different jobs to simplify this logic? The Django documentation is unclear on how to do this. e.g of what I want to do from django.contrib.auth.models import Group sales_group = Group.objects.get_or_create(name='sales') sales_job = request.user.job.filter(role='sales', organization__name="Google") sales_job_two = request.user.job.filter(role='sales', organization__name='Microsoft') #is it possible to do this ??? sales_group.add(user, job=sales_job_one) sales_group.add(user, job=sales_job_two) models.py class Users: first_name = models.CharField(max_length=255) last_name … -
Django order_by is not ordering results of query
Django not ordering results by date. Am using Django-Rest-Framework to create API for app initially had a filter by on the query and after reading similar issues where people faced same problem when combining order_by and filter I removed the filter and manually filtered using a for loop but still keep getting the same results. Initially query was: progresslogs = ProgressLog.objects.filter(user__userprofile__coach=request.user).order_by('-date') But reading similar issues I changed the query and filtered manually think there is an issue with using filter and order by together but am still getting the results out of order: class ProgressLogAPI(APIView): def get(self, request: Request, format=None): if request.user.is_authenticated: if request.user.is_staff: logger.info('API: Staff {} fetched progress logs'.format(request.user.id)) progresslogs = ProgressLog.objects.order_by('-date') # Below loop added to manually filter results filteredlogs = [] for progress in progresslogs: if progress.user.userprofile.coach == request.user: filteredlogs.append(progress) serializer = ProgressLogSerializer(filteredlogs, many=True) return Response(data=serializer.data) But in each case the results are coming out of order, wondering is this some bug in Django, I suppose could probably sort the results manually but am thinking this would drastically increase the time for the API call to get the results so don't really want to do this. For reference the first 3 result from the API call are …