Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I solve this DJANGO_SETTINGS_MODULE or call settings.configure() problem?
I'm currently learning to use Django with a Udemy course that is pretty outdated but since it was the best rated I thought I'd give it a try. After covered how to set the models.py file they showed how to use Faker to populate the admin section with fake data. The problem arises when trying to run this populate file, this is what shows up: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This is my populate file from faker import Faker from first_app.models import AccessRecord, Webpage, Topic import random import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') django.setup() # FAKE POP SCRIPT fakegen = Faker() topics = ['Search', 'Social', 'Market', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # get the topic for the entry top = add_topic() # create the fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # create the new webpage entry webpg = Webpage.objects.get_or_create( topic=top, url=fake_url, name=fake_name)[0] # create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create( name=webpg, date=fake_date)[0] if __name__ == '__main__': print('populating script..') populate(20) … -
pg_config executable not found. WINDOWS
I'm trying to pip install my requirements with this command": pip install -r ..\requirements\local.txt looks like everything is going good but then I run into this error -
MultiValueDictKeyError at /sendEmail/ 'file'
I'm trying to send an attachment via e-mail in my project with Django. But I am getting such an error. I know this question asked before but they're almost 10 years old and some of them didn't even answered. So I need help 😅. Thanks in Advance.. My codes are as follows: Django=3.2.7 django-crispy-forms==1.12.0 views.py # send email def sendMail(request): message = request.POST.get("message", "") subject = request.POST.get("subject", "") receivers = request.POST.get("email", "") email = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [receivers]) email.content_subtype = "html" file = request.FILES["file"] #file = request.POST.get("file") email.attach(file.name, file.read(), file.content_type) email.send() return HttpResponse(f"Sent to {receivers}") forms.py class EmailForm(forms.Form): # receivers email email = forms.EmailField() subject = forms.CharField(max_length=100) file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) message = forms.CharField(widget = forms.Textarea) models.py # for sending email class EmailReportModel(models.Model): """ this model created just for email foreignKey """ #receiver_emails = models.ForeignKey(BolgeMailListeleri, on_delete=models.CASCADE, related_name = "receiver_emails") receiver_emails = models.ManyToManyField(BolgeMailListeleri) subject = models.CharField(max_length=255, default="") message = models.TextField() upload = models.FileField(upload_to='uploads', null=True, blank=True) #upload = models.Field() #image1 = forms.Field(label='sample photo', widget = forms.FileInput, required = True ) SendEmail.html {% load crispy_forms_tags %} <div class="main"> <!-- Create a Form --> <form method="post" enctype="multipart/form-data"> <!-- Security token by Django --> {% csrf_token %} {{ form|crispy }} <button type="submit">Gönder</button> </form> <button onclick="goBack()" … -
Make a http call in python
I am trying to call the google fit API with python but the example for sessions is not working for me. The example by google GET https://fitness.googleapis.com/fitness/v1/users/me/sessions?activityType=97 HTTP/1.1 Authorization: Bearer [YOUR_ACCESS_TOKEN] Accept: application/json My code @api_view(['GET']) def googleFitView(request): social_token = SocialToken.objects.get(account__user=2) token=social_token.token url_session= "https://fitness.googleapis.com/fitness/v1/users/me/sessions" headers = { "Authorization": "Bearer {}".format(token), "Accept": "application/json" } session_call = requests.post(url_session, headers=headers) return Response(session_call) If I a call to another API of google fit it is working so the authentication is not a problem. I also followed the documentation and the session call does not require a body @api_view(['GET']) def googleFitView(request): social_token = SocialToken.objects.get(account__user=2) token=social_token.token url = "https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate" headers = { "Authorization": "Bearer {}".format(token), "Content-Type": "application/json;encoding=utf-8", } body = { "aggregateBy": [{ "dataTypeName": "com.google.activity.segment", }], "startTimeMillis": 1634767200000, "endTimeMillis": 1634853600000 } respo = requests.post(url, data=json.dumps(body), headers=headers) return Response(respo) -
Getting this error '' No Python at 'c:\program files (x86)\python38-32\python.exe' ''
I have an existing django project . I wanted to open that project . But , after activating the virtual environment ,whenever i am trying to run 'python manage.py runserver' I am getting this "No Python at 'c:\program files (x86)\python38-32\python.exe" error in command prompt. I am not getting any solution of this problem . -
django- how to override the django field
I have Django model date field I just want to override the date field with the JavaScript date range picker. JavaScript date range picker is working fine but unable to override the field in the template. html: <div>Netdue Date</div> <div class="row" id='id_row'> <input type="text" name="daterange" value="01/01/2018 - 01/15/2018" /> <!-- {{ form.Netdue_Date}} --> </div> <script> $(function() { $('input[name="daterange"]').daterangepicker({ opens: 'left' }, function(start, end, label) { console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); }); }); </script> forms.py class DateInput(forms.DateInput): input_type = "date" def __init__(self, **kwargs): kwargs["format"] = "%Y-%m-%d" super().__init__(**kwargs) class Userform(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['Netdue_Date'].widget.attrs.update( { 'placeholder': 'Netdue_Date', 'name': 'email', 'id': 'Netdue_Date'}) class Meta: model =Userbase fields = '__all__' widgets={ 'Netdue_Date':DateInput(), } -
Django code to read from a file and update to website without refresh
I would like to implement the solution provided at the link below to list a number on my website and have that number change automatically as it reads from the file. The file will be updated with a new number as part of a separate process. Django: Display contents of txt file on the website I would like to ensure that the number in the website changes dynamically without needing a refresh of the browser Thanks in advance community! -
Django rest frameowrk : Prevent one user from deleting/Editing/Viewing other users in ModelViewSet
I was using Django users model for my Django rest framework. For this I used Django's ModelViewSet for my User class. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer Serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = { 'password' : { 'write_only':True, 'required': True } } def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) # create token for the user return user But currently from postman when I make the request using the token of one user to view, delete, edit other users http://127.0.0.1:8000/api/users/4/ Its able to edit/delete/view other users. I don't want that to happen and one user can make request on itself only is all I want. This is my apps urls.py urls.py from django.urls import path, include from .views import ArticleViewSet, UserViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('articles', ArticleViewSet, basename='articles') router.register('users', UserViewSet, basename = 'users') urlpatterns = [ path('api/', include(router.urls)), ] How can I prevent one user from accessing other users when they make GET/POST/PUT/DELETE request. -
How much HTML and CSS knowledge should I have before learning Django? [closed]
I've completed learning python basic concepts and now I want to learn Django. But I want to know how much HTML and CSS knowledge should I have before approaching in Django. -
Relating data in a Django Model to another model
I have this model. class AuctionListings(models.Model): """ Model for all the listings listed on the site. """ title = models.CharField(max_length=40) description = models.TextField() image_url = models.URLField() current_bid = models.PositiveSmallIntegerField() category = models.CharField(choices=CATEGORIES, max_length=5) date = models.DateField(default=date.today) datetime = models.DateTimeField(default=timezone.now) date_last_updated = models.DateField(auto_now=True) date_added = models.DateField(auto_now_add=True) timestamp_last_updated = models.DateTimeField(auto_now=True) timestamp_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Title:{self.title}, Date Added:{self.date_added}, Category:{self.category}" class Meta: """ Specifies the plural name of the model for the Django Admin Panel. """ verbose_name_plural = "Auction Listings" I want to be able to set the starting bid in Auction Listings when someone creates a new listing. Just like how eBay would do it. I want the bid to also be able to be updated in the bid model. And that if the listing is deleted, the bid on the listing would also be deleted. Because there is no listing. I've tried using a foreign key but then I get this You are trying to add a non-nullable field 'current_bid' to auctionlistings without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) … -
Primary key error logging in Django Admin using MongoDB
first of all, I'm new in MongoDB and this is my first application using it so I know I have lack of documentation reading, but I am trying to find solution to this problem due that the documentation read says that everything might work well with no changes. I have correctly configured the settings file with the MongoDB database and have created my models. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'my database', } } I have created a superuser using the django-admin createsuperuser but when I try to login into the admin panel I get this error. ValueError: Cannot force an update in save() with no primary key. I know that MongoDB doesn't have a Primary Key and Foreign Key system and it's based on JSON-like type objects, but the documentation say that it works well with it so I thought that it was previously ready to run this. Any clue of what is happening? Thank you. -
How to post a Json with a base64 file using python request?
Right now I am programming an API with python, and I have the following problem: I have to POST the following JSON to an url: prescription = { "Name": “file_name", # This is a string "Body" : "xxx",# (File in base64 format) "ParentId" : "xxxxxxxxxxxxxxxxxx", # This is a string "ContentType" : "xxxxx/xxx" # This is a string } But when I try to do the following request: requests.post(url, prescription) I am getting the following error: TypeError: Object of type bytes is not JSON serializable How can I make a request for posting that JSON? Is it even possible? Thanks for your help. -
Django rest framework: how can I serialize multiple table to get combine JSON output
I am very new to django, any help highly appreciated. thanks in advance! Here is my code 'model.py' class Stocks(models.Model): ticker = models.CharField(max_length=30, primary_key=True, unique=True) company_name = models.CharField(max_length=100, blank=True, null=True) sector = models.CharField(max_length=50, blank=True, null=True) class Meta: db_table = 'stocks' def __str__(self): return "%s %s %s" % (self.ticker, self.company_name, self.sector) class QuarterlyFinance(models.Model): ticker = models.ForeignKey(Stocks, db_column='ticker',on_delete=models.CASCADE, related_name='quarter_result', blank=True, null=True) quarter_end = models.DateTimeField(blank=True, null=True) total_revenue = models.FloatField(blank=True, null=True) net_income = models.FloatField(blank=True, null=True) class Meta: db_table = 'quarterly_finance' unique_together = (('ticker', 'quarter_end'),) def __str__(self): return "%s %s %s %s" % (self.ticker, self.quarter_end, self.total_revenue, self.net_income) serialize.py class StocksSerialize(serializers.ModelSerializer): class Meta: model=Stocks fields="__all__" depth=1 class QuarterlyFinanceSerialize(serializers.ModelSerializer): class Meta: model=QuarterlyFinance fields=['quarter_end', 'total_revenue','net_income'] depth=1 view.py class DataClassView(APIView): def get(self, request, format=None): max_day = Advice.objects.latest('advice_date').advice_date max_day=max_day.strftime("%Y-%m-%d") qfinance = QuarterlyFinance.objects.filter(ticker='TCS') stk = Stocks.objects.filter(ticker='TCS') qfin_ser_obj = QuarterlyFinanceSerialize(qfinance, many=True) stock_ser_obj = StocksSerialize(stk, many=True) result = stock_ser_obj.data +qfin_ser_obj.data return Response(result) I want to return JSON output like this: { "ticker": "TCS", "company_name": "Tata Consultancy Services Ltd", "sector": "IT", "qtr_result": [ { "quarter_end": "2021-06-30T04:00:00", "total_revenue": 454110000000, "net_income": 90080000000 }, { "quarter_end": "2021-03-31T04:00:00", "total_revenue": 437050000000, "net_income": 92460000000 }, { "quarter_end": "2020-12-31T05:00:00", "total_revenue": 420150000000, "net_income": 87010000000 }, { "quarter_end": "2020-09-30T04:00:00", "total_revenue": 401350000000, "net_income": 74750000000 } ] } my code is working but I am … -
#static files is not working with #django
in my 000-default.conf help me please ServerAdmin webmaster@localhost ServerName targetmed.uz ServerAlias www.targetmed.uz DocumentRoot /var/www/targetmed.uz/tmed ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias static/ /var/www/targetmed.uz/tmed/static <Directory /var/targetmed.uz/tmed/static> Require all granted </Directory> <Directory /var/www/targetmed.uz/tmed/tmed> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess tmed python-home=/var/www/targetmed.uz/tmed/venv python-path=/var/www/targetmed.uz/tmed WSGIProcessGroup tmed WSGIScriptAlias / /var/www/targetmed.uz/tmed/tmed/wsgi.py </VirtualHost> and in settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-p8&sn%iv@2fzv_h_j8jb*t=p#q-tch9n*sc+l66^@5v8pf$p18' DEBUG = False ALLOWED_HOSTS = [ '*' ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tmed.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'tmed.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Tashkent' USE_I18N = True USE_L10N = True USE_TZ = False PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIR = '/var/www/targetmed.uz/tmed/static' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' but id doesn't work it takes server error(500) how can i solve it ??? please help … -
TypeError: User() got an unexpected keyword argument 'is_staff'
I'm newbie with django. I want to create an login, signup API so I find a solution on Internet. But it's not user my own User model, it use django.contrib.auth.models import AbstractUser. I don't need some field of AbtractUser so I give it =none. Here is my models code: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.postgres.fields import JSONField from django.contrib.auth.models import AbstractUser # Create your models here. # class User(models.Model): # name = models.CharField(null=False,blank=False, max_length=512) # username = models.CharField(null=False,blank=False, max_length=512, unique=True) # email = models.EmailField(null=False,blank=False, max_length=512, unique=True) # password = models.CharField(null=False,blank=False, max_length=512) # status = models.CharField(null=True,blank=True, max_length=512) # role = models.IntegerField(null=False, blank=False, default=1) # USERNAME_FIELD = 'username' # REQUIRED_FIELDS = [] # def __str__(self): # return self.username class User(AbstractUser): last_login = None is_staff = None is_superuser = None first_name = None last_name = None name = models.CharField(null=False,blank=False, max_length=512) username = models.CharField(null=False,blank=False, max_length=512, unique=True) email = models.EmailField(null=False,blank=False, max_length=512, unique=True) status = models.CharField(null=True,blank=True, max_length=512) role = models.IntegerField(null=False, blank=False, default=1) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] def __str__(self): return self.username class Category(models.Model): title = models.TextField(null=False, blank=False) description = models.TextField(null=False, blank=False) class Question(models.Model): title = models.TextField(null=False, blank=False) description = models.TextField(null=False, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) choices = models.JSONField(null=False, blank=False) answer = … -
Javascript - Uncaught ReferenceError: $ is not defined
I trying to use date range picker in JavaScript in Django where I have a date field from the django model. i want to override using the daterange picker but I'm getting a error.Though i have added the jquery cdn as well. error jquery-3.6.0.min.js:2 jQuery.Deferred exception: $(...).daterangepicker is not a function TypeError: $(...).daterangepicker is not a function at HTMLDocument.<anonymous> (http://localhost:1700/:646:34) at e (https://code.jquery.com/jquery-3.6.0.min.js:2:30038) at t (https://code.jquery.com/jquery-3.6.0.min.js:2:30340) undefined S.Deferred.exceptionHook @ jquery-3.6.0.min.js:2 t @ jquery-3.6.0.min.js:2 setTimeout (async) (anonymous) @ jquery-3.6.0.min.js:2 c @ jquery-3.6.0.min.js:2 fireWith @ jquery-3.6.0.min.js:2 fire @ jquery-3.6.0.min.js:2 c @ jquery-3.6.0.min.js:2 fireWith @ jquery-3.6.0.min.js:2 ready @ jquery-3.6.0.min.js:2 B @ jquery-3.6.0.min.js:2 jquery-3.6.0.min.js:2 Uncaught TypeError: $(...).daterangepicker is not a function at HTMLDocument.<anonymous> ((index):646) at e (jquery-3.6.0.min.js:2) at t (jquery-3.6.0.min.js:2) html <div> Due Date</div> <div class="row" id='id_row' name="daterange"> <!-- From: <input type="date" name='fromdate'> To: <input type="date" name='todate'> --> {{ form.due_Date}} </div> <p></p> <script> $(function() { $('input[name="daterange"]').daterangepicker({ opens: 'left' }, function(start, end, label) { console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); }); }); </script> -
How to authenticate user by the Microsoft Active Directory (AD) in Django app
according to this article: django-auth-ldap installation not working I want to ask you, how to transform this code for Microsoft Active Directory auth. It's for OpenLDAP. I want to only authenticate user by username and password from AD with django-python3-ldap modul without anymore mapping. Thanks!!! -
"Invalid Date format. It must be YYYY-MM-DD" -- Django Rest Framework
I am trying to redefine Django's Restframework default Date input type from YYYY-MM-DD to DD-MM-YYYY, while any post request is sent from frontend. I tried with postman to test the scenarios but Django is only accepting it without YYYY-MM-DD format I followed the doc tried to set settings.py with with configs like 1. REST_FRAMEWORK = { "DATE_INPUT_FORMATS": ["%d-%m-%Y"], } REST_FRAMEWORK = { "DATE_INPUT_FORMATS": [("%d-%m-%Y")], } But nothing seems to work. Please someone help, its like Iam stuck here. -
Django queryset with left join?
Suppose I have from django.db import models class Obj(models.Model): obj_text = models.CharField(max_length=100) class ObjAnnot(models.Model): obj = models.ForeignKey(Obj, on_delete=models.CASCADE) annot_text = models.CharField(max_length=100) I want to efficiently get all Obj objects with zero associated ObjAnnot instances. I could iterate over all Obj instances and query how many associated ObjAnnot instances there are, but that seems quite inefficient. In SQL, I would do a left outer join, and pick the rows with objannot.id null. How can I do that with the Django ORM? EDIT: Possible duplicate question. -
REST Django - filter with multiple variables
I know you can do something like : if Test.objects.filter(id = 2).exists(): #do something But with my attempt of using two variables, it does not work properly. I have a table with two Foreign keys to a User and a Project. I want to see if a specific combination exists. This attempt is what I tried but does not work. if Test.objects.filter(user = User, project = Project).exists(): #do something Maybe I just implemented it wrong ? my whole line is this. I get username and projectid by POST in the request.data if Userproject.objects.filter(user= User.objects.get(username = request.data.get('username',0), project = Project.objects.get(id = request.data.get('projectid',0)).exists(): -
Why is unmanaged model not calculating id in Django?
I have an unmanaged model in Django: class Person(models.Person): name = models.CharField(max_length=200) class Meta: managed = False db_table = '"public"."person"' Somewhere in my tests, I try to create a Person entry in the DB: person = Person(name="Ariel") person.save() But then I get an error: django.db.utils.IntegrityError: null value in column "id" of relation "person" violates not-null constraint DETAIL: Failing row contains (null, Ariel). Outside tests, everything works fine. In the tests, I initialize the DB with the tables referenced by the unmanaged by loading a schema dump. The Django docs states that "no database table creation, modification, or deletion operations will be performed for this model", and that "all other aspects of model handling are exactly the same as normal", including "adding an automatic primary key field to the model if you don’t declare it". But doesn't that mean this code should work? How come Django and Postgres are not taking care of the id? Am I doing something wrong? How can I fix it? -
Prefetching model with GenericForeignKey
I have a data structure in which a Document has many Blocks which have exactly one Paragraph or Header. A simplified implementation: class Document(models.Model): title = models.CharField() class Block(models.Model): document = models.ForeignKey(to=Document) content_block_type = models.ForeignKey(to=ContentType) content_block_id = models.CharField() content_block = GenericForeignKey( ct_field="content_block_type", fk_field="content_block_id", ) class Paragraph(models.Model): text = models.TextField() class Header(models.Model): text = models.TextField() level = models.SmallPositiveIntegerField() (Note that there is an actual need for having Paragraph and Header in separate models unlike in the implementation above.) I use jinja2 to template a Latex file for the document. Templating is slow though as jinja performs a new database query for every Block and Paragraph or Header. template = get_template(template_name="latex_templates/document.tex", using="tex") return template.render(context={'script': self.script}) Hence I would like to prefetch script.blocks and blocks.content_block. I understand that there are two methods for prefetching in Django: select_related() performs a JOIN query but only works on ForeignKeys. It would work for script.blocks but not for blocks.content_block. prefetch_related() works with GenericForeignKeys as well, but if I understand the docs correctly, it can only fetch one ContentType at a time while I have two. Is there any way to perform the necessary prefetching here? Thank you for your help. -
Django Table forward fill missing values
I have a table like this: A B a row row row row b row row row c row ... .... How can I fill in missing values like forward fill in Pandas data frame using Django ORM query? -
How to add the previous/next value of a filter_gt or filter_lt?
I have an array with several values including a date_time. With the django-url-filters module, I filter by this date_time. I can for example put in the url: https://URL/myws/?date_time__lte=2021-10-21T16:00:00&date_time__gte=2021-10-20T16:00:00 My problem is that I need a minimum and maximum value. For example, if in my database, I have 5 objects: [ { date_time: 2021-10-01T00:00:00, id: 1 ... }, { date_time: 2021-10-02T00:00:00, id: 2 ... }, { date_time: 2021-10-06T00:00:00, id: 3 ... }, { date_time: 2021-10-10T00:00:00, id: 4 ... }, { date_time: 2021-10-20T00:00:00, id: 5 ... } ] If I pass in my request the following parameters: date_time__lte=2021-10-08T00:00:00&date_time__gte=2021-10-03T00:00:00 The result is : [ { date_time: 2021-10-06T00:00:00, id: 3 ... } ] But I would like to have the previous value at date_time__gte and the next value at date_time__lte. The goal is to be sure to have a value for the whole period chosen in parameter. So I have to get: [ { date_time: 2021-10-02T00:00:00, id: 2 ... }, { date_time: 2021-10-06T00:00:00, id: 3 ... }, { date_time: 2021-10-10T00:00:00, id: 4 ... } ] Of course, I can't change the date of my previous value by the day - 1 because I don't know in advance the period between 2 values. My function: … -
Weird errors installing django-heroku for python
Although I'm not sure it is important, I will prefix by saying that I started working on a Heroku app on my old computer and am continuing on my new one. After a lot of struggling I finally managed to get the app to build on Heroku, although it didn't run. Perhaps the reason was because Heroku doesn't host static files so I set up an Azure account to do that and made some changes to settings.py and created a custom_azure.py file. After running "git push heroku main" it failed to build because it said that django-heroku was not found. Running "pip install django-heroku" resulted in a many errors. Then "pip freeze" shows that "django-heroku 0.0.0" is installed. Running "pip install --upgrade django-heroku" resulted in the same errors. It is so long I can't post it here so here's a link to a google doc: https://docs.google.com/document/d/17eQUC3Zd4YKq1vt4jObSV9s7MzoHjBy7jbfCerMlzT0/edit?usp=sharing I can't make sense of it.