Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
auto-save the selected answers and cheaking the answear for the quiz beacuse of it is out of the time
in my quiz app i have the following models : from django.db import models class Quizzes(models.Model): title = models.CharField(max_length=200) description = models.TextField() question_number = models.PositiveIntegerField() total_marks = models.PositiveIntegerField() date = models.DateTimeField(auto_now_add=True) time_limit_mins = models.PositiveIntegerField() def __str__(self): return self.title class Question(models.Model): quiz = models.ForeignKey(Quizzes,on_delete=models.CASCADE) question=models.CharField(max_length=600) marks=models.PositiveIntegerField() option1=models.CharField(max_length=200) option2=models.CharField(max_length=200) option3=models.CharField(max_length=200) option4=models.CharField(max_length=200) cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4')) answer=models.CharField(max_length=200,choices=cat) class Attempter(models.Model): quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE) score = models.PositiveIntegerField() completed = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username class Result(models.Model): exam = models.ForeignKey(Quizzes,on_delete=models.CASCADE) marks = models.PositiveIntegerField() date = models.DateTimeField(auto_now=True) and i have the following js code for keeping track of the time that is allowed to the exam and if the time is out the quiz page redarect to the result page : <script> function saveAns(){ var ele = document.getElementsByTagName('input'); for(i = 0; i < ele.length; i++) { if(ele[i].type="radio") { if(ele[i].checked){ setCookie(ele[i].name,ele[i].value,3) } } } } function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } window.onload = function begin(){ document.getElementById('timer').innerHTML = {{quiz.time_limit_mins}} + ":" + 00; startTimer(); } function startTimer() { var presentTime = document.getElementById('timer').innerHTML; var timeArray = presentTime.split(/[:]+/); var m = timeArray[0]; var s = checkSecond((timeArray[1] - … -
to each formset to match an automatically different value taken from a field of the model
I have a formset set to have an extra = 6. pasto it is the variable that allows me to choose which one pasto but I would like those six to be automatically set with the 6 values present in the formset. so when I save the formset it saves in the field pasto the value 1 if it is the first of the formset, 2 if it is the second etc ... my model class PianoDay(models.Model): scelta_pasto = [ ("1","Colazione"), ("2","Spuntino mattina"), ("3","Pranzo"), ("4","Merenda"), ("5","Cena"), ("6","Spuntino sera") ] pasto = models.CharField( choices = scelta_pasto, max_length = 300, default = '-' ) kcal = models.IntegerField(default = 0) grassi = models.IntegerField(default = 0) carboidrati = models.IntegerField(default = 0) proteine = models.IntegerField(default = 0) piano_day = models.ForeignKey( PianoSingleDay, on_delete = models.CASCADE, related_name = 'piano_day' ) form class PianoDayForm(forms.ModelForm): class Meta: model = models.PianoDay exclude = ['piano_day', 'pasto'] view @login_required def PianoSingleView(request, id): piano = get_object_or_404(models.Piano, id = id, utente_piano = request.user) datiFormSet = formset_factory(PianoDayForm, extra = 6) if request.method == 'POST': giorno_form = PianoSingleDayForm(request.POST, piano = piano, prefix = 'giorno') dati_formset = datiFormSet(request.POST, prefix = 'dati') if giorno_form.is_valid(): day_instance = giorno_form.save(commit= False) day_instance.single_piano = piano day_instance.save() if dati_formset.is_valid(): for dato in dati_formset: … -
Django how to transfer data from SQLite database after migrating to PostgrSQL
I migrated my Django app from SQLite to PostgreSQL in the process of preparing it for deployment using Heroku, but I forgot to transfer the data in the original SQLite database before migrating (I should have done something like this (https://www.shubhamdipt.com/blog/django-transfer-data-from-sqlite-to-another-database/). I still have the SQLite database and so I'm trying to figure out how to transfer the data over. My first thought was to try and migrate back to the SQLite database to then transfer the data, but I have not been able to do this. I tried changing the settings.py files back to how it was: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } and then I ran python manage.py migrate but when I locally host the app, the data is not accessed. Does someone know if I'm missing anything to revert back to my original SQLite database or maybe another way to transfer the data without migrating back? -
Getting net::ERR_CONNECTION_REFUSED when trying to make a request to Django REST Server
I am trying to test a Django app by using other devices in my local network. I am using Angular as my client. So far, I am able to run my Angular app on other devices. However, whenever I try to make any sort of request, I get back a response specifying: net::ERR_CONNECTION_REFUSED I am able to properly run both the client app and Django REST server in my local machine but it's not the case when it comes to other devices. Based on some of the already posted solutions, I have done : Binding Django server to IP : 0.0.0.0:8000 by running python .\manage.py runsslserver --certificate .\ssl\server.crt --key .\ssl\server.key 0.0.0.0:8000 (I am using SSL for both client and server). Setting ALLOWED_HOSTS to ['*'] in settings.py. But the error is still persistent. All the devices (including my local machine) which I am using is Windows if that's important. Can someone help me in fixing this issue? Or are there any other way to run the API server? -
Django populating dropdown with values
Hello guys i want to populate a dropdown with the ids from the database, but when iterating over the list i get back also the brackets and the commas and some spaces. In views.py, i have the following: id = list(Device.objects.values_list('patientId', flat=True).distinct()) print(id) for item in id: print(item) context = {"filename": filename, "collapse": "", "patientId": json.dumps(id), "labels": json.dumps(labels, default=str), "data": json.dumps(data), } The print is returning exactly what i want the ids(1,2,3), but when going in the frontend(index.html), with the following code: {{patientId}} <div class="row"> <label for="patientId">Choose a patient:</label> <select name="patient" id="patient"> {% for item in patientId%} <option value="{{item}}"> {{item}} </option> {%endfor%} </select> What i get How can i get in the frontend the dropdown with the correct values? -
capture input text from url in django rest framework
I am using django rest framework to take two string from URL and output as a json response. below is the code I have tried and the response I got. Input URL: http://127.0.0.1:8000/predict/?solute=CC(C)(C)Br&solvent=CC(C)(C)O. here inputs are CC(C)(C)Br and CC(C)(C)O and I was expecting the json response contains both the inputs but I got null as output This is my urls.py file @api_view(['GET']) def result(request): response = {} solute = request.POST.get('solute') solvent = request.POST.get('solvent') results = [solute,solvent] return Response({'result':results}, status=200) I got null as output json response -
Css not working in django after deployment
I was working on Django==3.1.7 in dev, but I had to move to Django==3.0.14 during production. I don't know if that is why, but my css is not working for all of my webpages. Here is my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] STATIC_ROOT = "static_root" Thank you, and please leave a comment if you have any questions. -
How to iterate json list with dict in python
I am calling data via an API and want to write that data to my Django model. The API provides me with a JSON with the following structure: "results": [ { "key1": "value", "key2": "value" }, { "key1": "value", "key2": "value", }, { "key1": "value", "key2": "value", }, .... My code looks like this: for data in response['results']: print(data) mydata = MyModel.add(**data) return results I get this error: list indices must be integers or slices, not str What I am doing wrong? A screenshot of the variables in PyCharm -
Django can't serialize Object because of _id prefix
I'm making a program which allows my frontend to send a Question Number and Category name to receive a question from the database. However, When i go to serialize the question object to send it back, the serializer errors. Model.py from django.db import models from django.db import models from django.contrib.auth.models import User class Category(models.Model): #Might Change later CategoryTitle = models.TextField() class Question(models.Model): questionText = models.TextField() QuestionType = models.TextField() questionScore = models.IntegerField() QuestionNist = models.TextField() Category = models.ForeignKey(Category, on_delete=models.CASCADE) Serializer.py from rest_framework import serializers from .models import(Question) class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('id','questionText','QuestionType','questionScore','Category') View.py from django.http import JsonResponse from django.core import serializers from rest_framework.views import APIView from django.http import HttpResponse from .models import (Category, Question) from django.contrib.auth.models import User from .serializers import (QuestionSerializer, QuestionSender) from rest_framework.response import Response as Rs class questionRecive(APIView): QuestionSerializer = QuestionSerializer QuestionSender = QuestionSender def get(self, request): user = self.authcall(request) QuestionSenderInstance = self.QuestionSender(data=request.data) print(request.data) if QuestionSenderInstance.is_valid(): print(QuestionSenderInstance.validated_data.get('Category')) CategoryRequested=QuestionSenderInstance.validated_data.get('Category') try: CategoryID = Category.objects.get(CategoryTitle=CategoryRequested) except: Response = HttpResponse("Invalid Category", content_type="text/plain") return Response try: QuestionObject = Question.objects.filter(Category=CategoryID).values() print(QuestionObject) except: Response = HttpResponse("No QUestions Within Category", content_type="text/plain") return Response questionnumber = QuestionSenderInstance.validated_data.get('QuestionNumber') print(questionnumber) SelectedQuestion = QuestionObject[questionnumber] print(f'{SelectedQuestion} HERE') SerializedQuestion = self.QuestionSerializer(data=SelectedQuestion) if not SerializedQuestion.is_valid(): print(SerializedQuestion.errors) return Rs(SerializedQuestion.data) … -
how to do you use django-tailwind pip with django on python 3.6
I am trying to download django-tailwind, but it downloads django-tailwind==0.9.0(which I think is an older version) and installs my Django as Django==3.0.14. I think this is because I have python 3.6. However, I cannot change my python version as it is already set by the host provider. I would like to use Django==3.1.17, but then I get an error when installing django-tailwind. Is there a way I can use Django==3.1.17 and django-tailwind together on python 3.6? -
How serve media files using dreamhost with django
I would like to say that i researched a lot before ask this, there are similar questions on Dreamhost, but it's not a repeated question because there's not a answer yet for this question. For django static files are part of your application code, while media files is for generated content by your application or users of your application. My application have a database of images that will be created for users, but i have no idea about how to serve this image files. All tutorials that i saw don't explain how serve media files, only static files. Dreamhost deploy django apps using this file passenger_wsgi.py on folder /home/username/domain import sys, os INTERP = "/home/username/example.com/venv/bin/python3" #INTERP is present twice so that the new python interpreter #knows the actual executable path if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) cwd = os.getcwd() sys.path.append(cwd) sys.path.append(cwd + '/djangoprojectname') #You must add your project here sys.path.insert(0,cwd+'/venv/bin') sys.path.insert(0,cwd+'/venv/lib/python3.8/site-packages') os.environ['DJANGO_SETTINGS_MODULE'] = "djangoprojectname.settings" from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Can i solve this creating a .htaccess file? If yes, how it is and which directory save it? How can i solve this problem? Is it possible solve this and don't pay for another hosting service? -
Git push django project error - No such file or directory
I typed git push heroku master in the command(Terminal) then this error occurs remote: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/home/ktietz/src/ci/alabaster_1611921544520/work' I can ensure that my prework before these steps is all correct because I had followed the tutorial video. Does any brother know this error before, and do you know how to fix it, please help my school project🙏 -
Flutter persistent login using django rest framework - jwt token authentication
I have some doubts related to how exactly should I have a persistent login system for my flutter app, using django backend. So, I am using jwt token authentication, but suppose the user goes offline then how am I supposed to keep them logged in, I mean the token would expire, so I will not be able to use it then how am I supposed to get the new token, I obviously cannot ask the user to login every time so I was thinking how I should be doing this. I am still learning django and so, I do not know exactly how I should be doing this. Sorry if this question is not very good. -
How to cache 404 responses in django?
I use django FileBasedCache backend. By default it caches only 200 responses and documentation doesn't mention any settings parameter that help specify which status code to cache. How to customize it to cache 404 responses? -
getting wrong format of date in Django
I am trying to create a form to receive date input from the user and then pass that input to my another python script my Django form code is as below from Django import forms class NameForm(forms.Form): lev=forms.IntegerField(label='lev') status = forms.CharField(label='status', max_length=100) start_date = forms.DateField(widget=forms.DateInput(format = '%Y/%m/%d',attrs={'type': 'date'})) i am receiving the date and all other values in my views.py file and then passing them to my python script my views.py code is def generate(request): form=NameForm(request.POST) if form.is_valid(): a=str(form.cleaned_data.get('lev')) b= form.cleaned_data.get('status') c=str(form.cleaned_data.get('start_date')) output=run([sys.executable,'C:\\Users\\siddhant\\Desktop\\internship\\indicator\\work\\water.py',a,b,c],stdout=PIPE,text=True) events_list=level.objects.all() return render(request,'result.html',{'res':events_list}) and I am doing a strptime conversion of passed date in my work.py code as follow current_level=int(sys.argv[1]) x=sys.argv[2] start_date=sys.argv[3] print(start_date) start=datetime.strptime(start_date, "%y/%d/%m") but i am getting error that ValueError: time data '2022-01-01' does not match format '%y/%d/%m' please can someone suggest how to do tackle with this problem -
All-auth does not work properly with djongo, shows DatabaseError at /accounts/google/login/callback/
I am implemeting all-auth for google oauth authentication with django. Earlier when I was using default sqlite database configurations, it was working fine (i have configured api in developer console and added it to socialapplications with proper site configuration). But When I migrated the database to mongodb using djongo with the following database configuration replacing the default one # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', # } # } DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'teqsrch' } } it is giving the following error on trying to authenticate with google oauth Request Method: GET Request URL: http://127.0.0.1:8000/accounts/google/login/callback/?state=FhTF1EeKyY0T&code=4%2F0AX4XfWi8PEE5Z6eCdaOWJrB8tIPHYE10OcnT7z25MPELbvJfDQlXn5PUHFT2ipb0OnanBQ&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid&authuser=1&prompt=consent The above exception ( Keyword: None Sub SQL: None FAILED SQL: ('SELECT (1) AS "a" FROM "account_emailaddress" WHERE ("account_emailaddress"."user_id" = %(0)s AND "account_emailaddress"."verified") LIMIT 1',) Params: ((2,),) Version: 1.3.6) was the direct cause of the following exception: File "/home/abhi/Projects/smartbull-backend/backend.env/lib/python3.10/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/abhi/Projects/smartbull-backend/backend.env/lib/python3.10/site-packages/djongo/cursor.py", line 59, in execute raise db_exe from e The above exception () was the direct cause of the following exception: File "/home/abhi/Projects/smartbull-backend/backend.env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/abhi/Projects/smartbull-backend/backend.env/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File … -
Turn off or edit autocomplete for Django allauth signup fields
I have an issue using allauth for Django on the signup fields, right now if I select the autocomplete option for the email field of my signup form then it fills the selected email into email and username. I am not quite sure how to fix this. allauth settings for my app: #django-allauth registraion settings ACCOUNT_EMAIL_SUBJECT_PREFIX ='VYGR ' ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = False ACCOUNT_CONFIRM_EMAIL_ON_GET= True ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION= True ACCOUNT_AUTHENTICATION_METHOD = 'email' LOGIN_REDIRECT_URL = '/' ACCOUNT_LOGOUT_ON_GET=True ACCOUNT_LOGOUT_REDIRECT_URL='/' The specific template: <div class="registration-form"> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> <div class="login-page-title page-title" href="#">VYGR</div> {% csrf_token %} {% for field in form %} {{ field }} {{ field.errors }} {% endfor %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %}</button> <p class="signup registration">{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">Sign In</a>.{% endblocktrans %}</p> </form> </div> What I see in Chrome developer tools: <div class="registration-form"> <form class="signup" id="signup_form" method="post" action="/accounts/signup/"> <div class="login-page-title page-title" href="#">VYGR</div> <input type="hidden" name="csrfmiddlewaretoken" value="xxx"> <input type="email" name="email" placeholder="E-mail address" autocomplete="email" required="" id="id_email"> <input type="text" name="username" placeholder="Username" autocomplete="username" minlength="1" maxlength="150" required="" id="id_username"> … -
How do you solve django.db.migrations.exceptions.NodeNotFoundError in Django?
I get the following error when I do python manage.py makemigrations: django.db.migrations.exceptions.NodeNotFoundError: Migration leads.0001_initial dependencies reference nonexistent parent node ('auth', '0012_alter_user_first_name_max_length') This is a part of my 0001_initial.py: class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='User', ... How am I supposed to solve this error? Currently, I am in production. Thank you, and please leave a comment if you have any questions. -
No matching version found for @vue/cli-plugin-router@3.12.1 after npm audit fix --force
I have just run this: after npm audit fix --force But after that I got this issue: djackets_vue@0.1.0 serve vue-cli-service serve node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module '@vue/cli-plugin-router' Require stack: - C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\lib\Service.js - C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\bin\vue-cli-service.js at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15) at Function.Module._load (node:internal/modules/cjs/loader:778:27) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at idToPlugin (C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\lib\Service.js:150:14) at C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\lib\Service.js:190:20 at Array.map (<anonymous>) at Service.resolvePlugins (C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\lib\Service.js:176:10) at new Service (C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\lib\Service.js:34:25) at Object.<anonymous> (C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\bin\vue-cli-service.js:16:17) { code: 'MODULE_NOT_FOUND', requireStack: [ 'C:\\DjangoWeb\\venv\\Scripts\\djackets_django - Copy\\djackets_vue\\node_modules\\@vue\\cli-service\\lib\\Service.js', 'C:\\DjangoWeb\\venv\\Scripts\\djackets_django - Copy\\djackets_vue\\node_modules\\@vue\\cli-service\\bin\\vue-cli-service.js' ] } Here is my package.json: { "name": "djackets_vue", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build" }, "dependencies": { "axios": "^0.24.0", "bulma": "^0.9.3", "bulma-toast": "^2.4.1", "core-js": "^3.6.5", "vue": "^3.0.0", "vue-router": "^4.0.0-0", "vuex": "^4.0.0-0" }, "devDependencies": { "@vue/cli-plugin-babel": "^3.3.0", "@vue/cli-plugin-router": "3.12.1", "@vue/cli-plugin-vuex": "~4.5.0", "@vue/cli-service": "^3.12.1", "@vue/compiler-sfc": "^3.0.0", "sass": "^1.26.5", "sass-loader": "^8.0.2" } } I have just tried to unistall node_modules and npm then reinstall all of this, but still nothing Any idea? Thank you in advance -
Django Favorite system
I am trying to build a "add to favorite" system in django for my app. So far, I have a detail page called ad_detail, where I have a button that if the user clicks on, wether he already clicked on it or not, adds or remove the ad to his "watch list". This works fine. Now I am trying to do the same thing but in home.html, where I have couple ads that I render to the template. For each ad, I want to add the "add to watch list" button. If the user has aleady added the ad in his favorites, then show the icon-fill. If not show simply the icon-not-fill. When the user clicks on one of the displayed "add to favorite" button, then I want in views.py to be able to get the exact button that has been clicked, to then add it to user's favorites. Code below: models.py class VlandAd(models.Model): metaverse_name = models.CharField(max_length=100) title = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price = models.CharField(max_length=50) currency = models.CharField(max_length=8) ad_link = models.CharField(max_length=200) sold = models.BooleanField(default=False) bought_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="has_bought") created = models.DateTimeField(auto_now_add=True) published = models.CharField(max_length = 30, choices=STATUS_CHOICES, default="Published" ) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) … -
Hello everyone , i built web site with django framework for online services like freelancer,
and i want when the normal user requests a specific project from a particular freelancer ,I want to send him an email with project details what can i do? -
how to compare two objects fields in django
I have two objects and I want to compare them in order to find which fields are field in one and miss in the other... what should I do? how can I do it in a query(if it is possible) or how can I do it in python? assume two objects school1 and school2( from model School). the fields are students_number, classes, name, address) example: school1( 10,4,"","") school2(12,5,"alexi", "USA,alex street") -
Not Able to import 'RetrieveUpdateDestoryAPIView' from 'rest_framework.generics'
I am able to import other APIViews but not RetrieveUpdateDestoryAPIView using rest_framework.generics. from .models import Employee from .serializers import EmployeSerializer from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestoryAPIView # Create your views here. class emp_get(ListCreateAPIView): queryset = Employee.objects.all() serializer_class = EmployeSerializer class emp_api(RetrieveUpdateDestoryAPIView): queryset = Employee.objects.all() serializer_class = EmployeSerializer **File "../genericsAPIViewAndMixin/concreteApi/views.py", line 3, in from rest_framework.generics import ListCreateAPIView, DestroyAPIView, RetrieveUpdateDestoryAPIView ImportError: cannot import name 'RetrieveUpdateDestoryAPIView' from 'rest_framework.generics** -
Search part in navbar doesn't work properly (django)
I wanted to create a search box in my navbar and show the food which I search, but it seems it doesn't work properly. I can't find out where's the problem; I mean if I search a food which exists it shows me nothing. my views.py file: class SearchResultsView(ListView): model = Food template_name = "restaurant/food_search_results.html" context_object_name = "data" def get_queryset(self): query = self.request.POST.get("search") if query is not None: return Food.objects.filter(name__icontains=query) else: return my urls.py file: path("search", SearchResultsView.as_view(), name='search_results'), my base.html file: <form class="form-inline my-2 my-lg-0" action="/search" method="get"> {% csrf_token %} <div class="input-group"> <label> <input name="search" type="text" class="form-control" placeholder="Search Foods ..."> </label> <div class="input-group-append"> <a class="btn btn-outline-warning" href="{% url 'search_results' %}" type="submit" >Search</a> </div> </div> </form> -
Get Average of every n records in django in a efficient way
Imagine that you have 6 records like [1,2,3,4,5,6] how it is possible to calculate result bellow with least query to db in django? { 1 : (1+2)/2, 2 : (3+4)/2, 3 : (5+6)/2, }