Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django inline formset same value is repeated
I want to set employee target for every product, its showing all product but only one product saving everytime i want all product with different target In my Views.py class targetcreate(CreateView): model = target form_class = targetform1 success_url = '/' def get_context_data(self,** kwargs): context = super(targetcreate, self).get_context_data(**kwargs) context['formset'] = targetFormset(queryset=target.objects.none(), instance=product.objects.get(id=1),initial=[{'name': name} for name in self.get_initial()['name']]) return context def get_initial(self): initial = super(targetcreate , self).get_initial() initial['name'] = product.objects.all() # initial['name'] = add_users.objects.all() return initial def post(self, request, *args, **kwargs): formset = targetFormset(request.POST,queryset=target.objects.none(), instance=product.objects.get(id=1), initial=[{'name': name} for name in self.get_initial()['name']]) if formset.is_valid(): return self.form_valid(formset,request) else: messages.warning(request,'error') return render(request,'add_target_emp1.html',{'formset':formset}) def form_valid(self,formset,request): instances = formset.save(commit=False) for instance in instances: instance.date = request.POST.get('date') instance.name = emp.objects.get(id=3).user.username instance.save() return redirect('../../accounts/add_target_emp1') in my models.py this is my employee model i have product in another app class emp(models.Model): user=models.OneToOneField(User,null=True,on_delete=models.CASCADE) firstname=models.CharField(default='',max_length=100,null=False) lastname=models.CharField(default='',max_length=100,null=False) gender=( ('M','Male'), ('F','Female'), ('O','Others'), ) gender=models.CharField(choices=gender, default='',max_length=10) dob=models.DateField(default=datetime.now) created_by=models.CharField(default='',max_length=100) phonenumber=models.TextField(default='',null=False,unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(default=timezone.now) branch=models.CharField(default='',max_length=100) position=models.CharField(default='',max_length=100) class target(models.Model): conversion_target=models.BigIntegerField(null=True) total_target=models.BigIntegerField(null=True) name=models.CharField(default='',max_length=100) branch=models.CharField(default='',max_length=100) created_at = models.DateTimeField(auto_now_add=True) created_by=models.CharField(default='',max_length=100) month=models.CharField(default='',max_length=100) vehicle=models.ForeignKey(product,on_delete=models.CASCADE,null=True) class product(models.Model): product_category=models.CharField(null=True,max_length=5000) product_category_id=models.CharField(null=True,max_length=5000) Value=models.DecimalField(default=0.00,max_digits=10,decimal_places=2) products=models.CharField(null=True,max_length=5000) forms.py class targetform1(ModelForm): class Meta: model = target fields ='__all__' widgets = {'name' : HiddenInput} exclude=['created_at','created_by','completed_total_target','completed_conversion_target','completed_total_percentage','completed_conversion_percentage','branch'] def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for field in self.fields: new_data={ 'class':'form-control', 'rows':1, 'required':'True', } self.fields[str(field)].widget.attrs.update( new_data … -
Represent number as currenct from paragraph
On my web page I have an paragraph which looks like this: <p class="article-content mb-1" id="cost"><strong>Cost [Euro]: </strong>1000000</p> Number is always something else (which I read from db and represent using Django forms) and I would like to represent it as currency (in this case 1.000.000). I tried to get the value with: <script type="text/javascript"> function on_load(){ var a = document.getElementById('cost').value; console.log(a) } on_load(); </script> but Console output is: 'undefined'. When I get value, I'll use something like (12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); // 12,345.67 To convert to currency. -
Chart.js Django Everthing is Working fine but in index of graph there is 0.028 instead of date from the list
<canvas id="myChart" width="400" height="400"></canvas> <script> var final={{final|safe}}; var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for i in final %}{{i.Date}},{% endfor %}], datasets: [{ label: 'Actual Price', data: [{% for i in final %}{{i.Open}},{% endfor %}] }, { label: 'Prediction Price', data:[{% for i in final %}{{i.prediction}},{% endfor %}] }] }, options: { scales: { xAxes: [{ display: true }], yAxes:[{ ticks:{ beginAtZero: true } }] } } }); </script> </div> Graph Console Chart.js Django Everthing is Working fine but in index of graph there is 0.028 instead of date from the list.Chart.I uses a For loop to for getting Value from list name final then i run the for loop on labels to get the value of date but in graph there is no any date -
fail compiling GDAL 3.0.4 on AMI 2
I have the following output after trying to do a make install echo 'CONFIG_VERSION='`cat ./VERSION`'' >> gdal.pc echo 'CONFIG_INST_PREFIX=/usr/local' >> gdal.pc echo 'CONFIG_INST_LIBS=-L/usr/local/lib -lgdal' >> gdal.pc echo 'CONFIG_INST_CFLAGS=-I/usr/local/include' >> gdal.pc echo 'CONFIG_INST_DATA=/usr/local/share/gdal' >> gdal.pc cat gdal.pc.in >> gdal.pc /usr/local/gdal/gdal-3.0.4/install-sh -d /usr/local/lib for f in libgdal.la ; do /bin/sh /usr/local/gdal/gdal-3.0.4/libtool --mode=install - silent /usr/local/gdal/gdal-3.0.4/install-sh -c $f /usr/local/lib ; done install: .libs/libgdal.lai does not exist make: *** [install-lib] Error 1 -
Django server not initializing with Docker?
I'm new to Docker, and I'm not being able to make it work. I'm on Windows. I cloned the repository https://github.com/18F/docker-compose-django-react, went to VSCode and built the containers with the "Remote - Containers" extension. When I try to access http://localhost:8000/, I get the message "localhost didn’t send any data.", although the React http://localhost:3000/ loads correctly. If I open the terminal from inside the Container, go to the correct folder and run python manage.py runserver, I can access it normally. So it seems that the server isn't being initialized on the Dockerfile/docker-compose. I'm also having this trouble on a setup I'm trying to make from some blog posts. How can I fix/debug this? -
Django implementation of if-else statement
I want to implement a django payment system using a payment platform named mpesa. I also want to print "hello world" on the console every time the page loads or when the request.POST.get('action') == 'post' is not triggered when the function is accessed. I have my code below. def pay_online(request): response_data = {} current_user = request.user queryset = Individual.objects.filter(user = request.user.id) if queryset.exists(): queryset = Individual.objects.get(user = request.user.id) else: queryset = Business.objects.get(user = request.user.id) if request.POST.get('action') == 'post': print("hello world 1") MpesaNo = request.POST.get('mpesaNumber') response_data['message'] = "Check your phone for ussd prompt to complete the payment." access_token = MpesaAccessToken.validated_mpesa_access_token api_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest" headers = {"Authorization": "Bearer %s" % access_token} request = { "BusinessShortCode": LipanaPpassword.Business_short_code, "Password": LipanaPpassword.decode_password, "Timestamp": LipanaPpassword.lipa_time, "TransactionType": "CustomerBuyGoodsOnline", "Amount": queryset.ccTotal, "PartyA": Number, "PartyB": LipanaPpassword.Business_short_code, "PhoneNumber": Number, "CallBackURL": "https://sandbox.com", "AccountReference": "Trial", "TransactionDesc": "Trial payments" } response = requests.post(api_url, json=request, headers=headers) return JsonResponse(response_data) else: print("hello world") context = {'queryset':queryset} template = 'payments_page.html' return render(request, template, context) My main question is why this is not displaying "hello world" on the console when request.POST.get('action') == 'post' is not triggered. -
How to save default JavaScript datetime object in django
I want to save default JavaScript datetime format in django database. How can I change the datetime field format in django default to JavaScript format? For example: This JavaScript format: Mon Feb 06 2017 11:39:05 GMT+0000 (GMT) while django's models.DateTimeField expects: 2017-02-06 11:39 ? -
i use this code to edit and delete in django python but this message shows DoesNotExist at /Edit/1 or DoesNotExist at /Delete/1
i use this code to edit and delete in django python but this message shows DoesNotExist at /Edit/1 or DoesNotExist at /Delete/1 def stedit(request, id): getsudentdetails= acc.objects.get(studnumber=id) return render(request, 'edit.html',{"acc":getsudentdetails}) def stupdate(request,id): if request.method=='POST': stupdate= acc.objects.get(studnumber=id) form=stform(request.POST,instance=stupdate) if form.is_valid(): form.save() messages.success(request, "The Student Record Is Updated Successfully..!") return render(request, "edit.html",{"acc":stupdate}) def stdel(request, id): delstudent= acc.objects.get(studnumber=id) delstudent.delete() results=acc.objects.all() return render (request, "Login.html",{"acc":results}) -
Not using decimals but got Object of type Decimal is not JSON serializable
my view is working perfectly, but when i try to store a ModelForm result on session it's stored but got Object of type Decimal is not JSON serializable it doesn't make sens beceause i'm not storing Decimals on session PS: i'm storing the ModelForm result on session because i have to redirect the user to an external url after he come back i need that data stored on session here is the view def cart_detail(request): cart = Cart(request) order_form = OrderCreateForm() for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'override': True}) if cart.__len__() : if request.method == 'POST': order_form = OrderCreateForm(request.POST) if order_form.is_valid(): order = order_form.save(commit=False) for item in order_form.cleaned_data.items(): request.session[str(item[0])] = str(item[1]) print(request.session[str(item[0])]) #also tried this way and same result # request.session['order_data'] = order_form.cleaned_data #also tried this way and same result # request.session['first_name'] = order_form.cleaned_data['first_name'] # request.session['order_phone'] = str(order_form.cleaned_data['phone']) # print('type => ', request.session['order_phone']) if request.user.is_authenticated: order.user = request.user order.save() for item in cart: OrderItem.objects.create(order=order,product=item['product'],price=item['price'],quantity=item['quantity'],attribute_1 = ['attrbute_1'], attribute_2 = ['attrbute_2'], attribute_3 = ['attrbute_3']) context = { 'order': order, 'total_price': total_price, 'delivery': order.delivery_cost, 'total_price_with_delivery': total_price_with_delivery, } print('here i am') return render(request, 'created.html', context) else: print('errorforms', order_form.errors) messages.error(request, order_form.errors) return render(request, 'cart.html', {'cart':cart, 'form' : order_form, 'wilayas': wilayas, 'communes': communes}) else: … -
How to make this item and group list shown in table on django?
I wanna make something like this image. On the left i wanna add lots of things. But this example only 8 items. And right section shows main groups of items and under the names it shows how many items in total. How can i make this. Has someone can give me an idea? -
aldjemy query with ManyToManyField in django model
I need some help for the following problem. I have the following django model, it is a simple example with the use of ManyToManyField: from django.db import models # Create your models here. class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ['title'] def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) class Meta: ordering = ['headline'] def __str__(self): return self.headline Then, I have the following test.py file. The first test is ok, but the second fails: from django.test import TestCase # Create your tests here. from magazine.models import Publication, Article import sqlalchemy as sa import sqlalchemy.orm as orm class MagazineTestCase(TestCase): def setUp(self): p1 = Publication.objects.create(title='The Python Journal') p2 = Publication.objects.create(title='Science News') p3 = Publication.objects.create(title='Science Weekly') a1 = Article.objects.create(headline='Django lets you build web apps easily') a1.publications.add(p1) a2 = Article.objects.create(headline='NASA uses Python') a2.publications.add(p1,p2) def test_publications(self): article = Article.objects.get(headline='NASA uses Python') print(article) def Session(): from aldjemy.core import get_engine engine = get_engine() _Session = orm.sessionmaker(bind=engine) return _Session() session = Session() class AldjemyTestCase(TestCase): def setUp(self): p1 = Publication.objects.create(title='The Python Journal') p2 = Publication.objects.create(title='Science News') p3 = Publication.objects.create(title='Science Weekly') a1 = Article.objects.create(headline='Django lets you build web apps easily') a1.publications.add(p1) a2 = Article.objects.create(headline='NASA uses Python') a2.publications.add(p1,p2) def test_publications_with_aldjemy(self): article = Article.sa.query().join(Article.publications).all() print(article) with … -
Django - Variable cached with "with" template tag isn't evaluated
I'm following along this article, and I have a form like this: <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} </fieldset> <input type="submit" value="Vote"> </form> I figured, since there are multiple instances of "choice{{ forloop.counter }}", I can cache it with with template tag and use it as a variable. But as you can see, the variable forloop.counter inside the with template tag isn't evaluated. The expected result was this: How can I fix this? -
Seed Django + Postgres with .sql file
I have a .sql file which I'd like to seed my django + postgres app with on build. That way I'll have some data in my app during development. Here's my docker stuff: Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip3 install -r requirements.txt COPY . /code/ docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db -
Django channels sending 10 items from server to client
I need help sending 10 event objects to the client as one json object but so far I can only send one, please help me with the logic. def event_message(self, event): event = Event.objects.all().order_by("-facebook_reactions")[0:10] facebook_reactions = str(event[0].facebook_reactions) tweet_text = str(event[0].tweet_text) url = str(event[0].url) self.send( text_data=json.dumps( { "facebook_reactions": facebook_reactions, "tweet_text": tweet_text, "url": url, } ) ) -
Curling dj-rest-auth login with custom serializer returns HTTP 500 error
Ran: python manage.py testserver myFixtures.json and I tried to test the login endpoint via: curl -X POST -F "email=test@test.com" -F "password=password" http://127.0.0.1:8000/dj-rest-auth/login/ > result; Note: myFixtures.json have such a endUser with these fields. Returns result: 2 <!doctype html> 3 <html lang="en"> 4 <head> 5 <title>Server Error (500)</title> 6 </head> 7 <body> 8 <h1>Server Error (500)</h1><p></p> 9 </body> 10 </html> I think it is something to do with my custom_dj_rest_auth_serializers.py. It is based on the standard serializers: https://github.com/iMerica/dj-rest-auth/blob/master/dj_rest_auth/serializers.py Using the default serializers doesn't not have the same problem. But my system's EndUser entity does not have username. I think I do not know how to customise the serializer which may have led to this problem. BackendApp.custom_dj_rest_auth_serializers.py: from django.conf import settings from django.contrib.auth import authenticate, get_user_model from django.contrib.auth.forms import SetPasswordForm, PasswordResetForm from django.urls import exceptions as url_exceptions from django.utils.encoding import force_str from django.utils.module_loading import import_string from django.utils.translation import gettext_lazy as _ from rest_framework import exceptions, serializers from rest_framework.exceptions import ValidationError from django.core.exceptions import ValidationError as DjangoValidationError from django.http import HttpRequest from django.urls.exceptions import NoReverseMatch from requests.exceptions import HTTPError from rest_framework import serializers from rest_framework.reverse import reverse from BackendApp.models import EndUser, Admin try: from allauth.account import app_settings as allauth_settings from allauth.account.adapter import get_adapter … -
Elastic search with django
Am working with elastic search with Django where I find difficult to map parent child relationship.here is my code.Here category is a child of division and they have many to one relationship. @registry.register_document class DivisionDoc(Document): id = fields.IntegerField(attr="id") code = fields.TextField( fields={ "raw":{ "type":"keyword" } } ) name = fields.TextField() is_active = fields.BooleanField() is_delete = fields.BooleanField() status = fields.TextField() division_meta = fields.NestedField() class Index: name = 'division' settings = { 'number_of_shards':1, 'number_of_replicas':1 } class Django: model = Division @registry.register_document class CatgeoryDoc(Document): id = fields.IntegerField() parent = fields.NestedField() division_id = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'code': fields.TextField(), 'name': fields.TextField(), 'is_active': fields.BooleanField(), 'is_delete': fields.BooleanField(), 'status' :fields.TextField(), 'division_meta' : fields.NestedField() }) code = fields.TextField( fields = { "raw":{ "type":"keyword" } } ) name = fields.TextField() image = fields.FileField() is_active = fields.BooleanField() is_delete = fields.BooleanField() status = fields.TextField() category_meta = fields.NestedField() class Index: name = 'category' settings = { 'number_of_shards':1, 'number_of_replicas':1 } class Django: model = Category class DivisionDocuments(DocumentViewSet): permission_classes = [AllowAny] document = DivisionDoc def get_serializer_class(self): if self.action == 'list': return DivisionSerializer filter_backends = [ FilteringFilterBackend, CompoundSearchFilterBackend ] search_fields = ('code','name') multi_match_search_fields = ('code','name') filter_fields = { 'code':'code', 'name':'name' } class CategoryDocuments(BaseDocumentViewSet): permission_classes = [AllowAny] document = CatgeoryDoc lookup_field = 'id' # serializer_class = CategorySerializer … -
should I run daphne + gunicorn or just dapne? why?
I have created a real-time RESTful application that uses Django channels and was referring to this link to host my application. It works. But I was wondering do we need daphne+gunicorn when the app runs with daphne alone. Is there any benefit/drawback of just running daphne apart from the easier configuration? -
React/Django - ImageField (when no uploding any file) - The submitted data was not a file. Check the encoding type on the form
I want not to upload any image when submitting but it is giving me an error The submitted data was not a file. Check the encoding type on the form. When I select a file it works fine. How can fix this, I also try some methods. I try removing image when it get null and set default in models views.py class ProductViewset(ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def create(self, request, *args, **kwargs): data = format_product_data(request.data.copy()) serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) pprint(serializer.validated_data) headers = self.get_success_headers(serializer.data) return Response(format_product_response_data(serializer.data), status=201, headers=headers) serializer.py class ProductSerializer(ModelSerializer): image = serializers.ImageField(max_length=None, use_url=True, allow_empty_file=True) attrs = ProductAttrSerializer(many=True, required=False, read_only=False) type = serializers.PrimaryKeyRelatedField(read_only=False, required=True, allow_null=False, allow_empty=False, queryset=ProductType.objects.all()) class Meta: fields = "__all__" model = Product def create(self, validated_data): attr_list: List[dict] = [] if 'attrs' in validated_data: attrs = validated_data['attrs'] del validated_data['attrs'] for attr in attrs: attr_serializer = ProductAttrSerializer(data=attr) attr_serializer.is_valid(raise_exception=True) attr_list.append(attr_serializer.save()) instance = Product.objects.create(**validated_data) instance.attrs.set(attr_list) instance.save() return instance models.py class Product(models.Model): number = models.CharField(max_length=20, null=True, unique=True, blank=True, db_column='NO.') name = models.CharField(max_length=30, null=True, unique=False, db_column='Name') image = models.ImageField(upload_to="product_images", blank=True, null=True, db_column='Image') entry_date = models.DateTimeField(auto_now_add=True, db_column='Date', null=True, blank=True) last_updated = models.DateTimeField(auto_now=True, db_column='Update_date') source_type = models.CharField(max_length=10, blank=False, choices=PRODUCT_TYPES, default="spd") type = models.ForeignKey(to=ProductType, on_delete=models.CASCADE, related_name="products", related_query_name="product") status = models.CharField(max_length=8, null=False, blank=False, choices=PRODUCT_STATUS_CHOICES, … -
What changes I should make change the get to filter?
I am doing a project for my college work. In that, I need to change a function. That function is giving error saying multiple objects returned. The function works well if there is only one object to return. But I need to change it to return it to return all the objects. So what changes do I need to do. I am attaching the function code. Pls provide the code to modify also. I am just beginner in coding. Thanks I am using Pycharm, Django and. MySQL to do my project The problem is obj=booking.objects.get is returning multiple objects and it can't displayed by the function . So I need to get the code to display all objects. I understood that using filter() will solve the problem. But I don't know what are the changes to make and where should I make it. So pls help. I am just a beginner. def vpay(request) : b=request.session['uid'] ob=TurfManager.objects.get(t_id=b) bb=ob.tf_id obj=Booking.objects.get(tf_id=bb) nn=obj.b_id o = Payment.objects.filter(book_id=nn) context = { 'obval': o, } -
How to instantiate Annotorious.js API with Django
I am trying to include Annotorious.js in a Django Web app. Using the steps from annotorious documentation, I am able to annotate an image at the front end. But, I could not save the coordinates of the drawn annotation. Is there a way to instantiate the annotorious APIs with Django, such that any changes to the bounding boxes drawn at the front end be saved automatically? -
How to effectively query DB when need to build paginated view for big table and join extra details from small one?
I'm trying to understand typical approaches for the below common situation faced when developing on Rails or Django. Example user story I want to filter and sort purchases and then expand details about some purchased products by clicking on their lines and to see details right there. Go to the next pages if needed. Data model details Big table with purchases (millions). Small table with products details (thousands). Only one product per purchase. Main question How to organize the processing of such request to gain the best performance? Does framework ORM have any effect on it? There are likely many 'it depends'. I will appreciate it if you point them out. Smaller questions Even when we provide all data in one HTTP request: is there a case to split queries into two? First WHERE's, ORDER, OFFSET and LIMIT for big table. Then go with the result to a small table to join. If done in one query: is it a common approach to subset with WITH first and only then do join? Is it correct understanding that generally ORM query builder will do one big query, so if one wants to optimize SQL requests, then one needs to bypass ORM? … -
How to display parsed JSON data into different tables based on matching list criteria
Have a feeling there is an easy solution for this, but I am spinning my wheels here. I am building a simple Django website that will have 10 different tables, each table will have unique sports teams listed with associated stats like scores, wins, losses, etc. I am parsing JSON data from an API that has all this information. The issue I am running into is how to specifically designate say Team1, Team2, Team3, Team4 goes to first table, and Team5, Team6, Team7, Team8 to the second table, etc. I have tried multiple different ways with no good results. For simplicity lets just say we are working with just two tables, here is snippet from my views.py file def bball(request): url = "https://api-URL" querystring = {"criteria":"criteria","criteria":"criteria"} headers = { 'x-rapidapi-host': "api-host", 'x-rapidapi-key': "APIKEY" } jsonList = [] response = requests.request("GET", url, headers=headers, params=querystring) data = json.loads(response.content) main = data["get"] league = data["parameters"]["league"] season = data["parameters"]["season"] temp_main = data["response"] final = list() table_1 = ["TEAM1","TEAM2","TEAM3","TEAM4"] table_2 = ["TEAM5","TEAM6","TEAM7","TEAM8"] for temp in temp_main: for record in temp: position = record['position'] stage = record['stage'] group_name = record["group"]["name"] group_points = record["group"]["points"] team_id = record["team"]["id"] team_name = record["team"]["name"] games_played = record["games"]["played"] games_won_total = record["games"]["win"]["total"] games_won_perct … -
What's the recommended way for me to decouple csv parsing and data saving in Django?
Novice here. I'm using Django Rest Framework to create an API that a user can post a csv file to. My program then parses the csv and creates model instances to save data in my database. I've heard that it's best practice to decouple processes like csv parsing and saving data to the database. I haven't found any helpful examples of what this might look like on google, though. In my view I'm currently using csv.DictReader(csv_contents.splitlines()) to begin deserializing the contents of the csv, and then I'm calling a method from my services.py file to go through the csv contents and create my model instances. Can anyone recommend a better way for me to design this process? Thank you so much for your time. -
Django group nearby rows based on datetime
In a Django model that stores an event datetime, I would like to group rows nearby in datetime. To clarify, each object has a date_time field and I can find the gap between objects in date time rather easily with: # We want a minimum date_time as the default for prev_date_time # but because Session.date_time is a DateFimeField and TZ aware # Django requires teh default to be TZ aware. And datetime.min # cannot be made TZ awre (it crashes), adding one day prevents # that crash and works and serves our purposes. min_date_time = make_aware(datetime.min + timedelta(days=1), "UTC") sessions = Session.objects.all().annotate( prev_date_time=Window( expression=Lead('date_time', default=min_date_time), order_by=F('date_time').desc() ), dt_difference=F('date_time') - F('prev_date_time') ) This works brilliantly. Now, I would like to group these sessions such that any session with a dt_difference of over 1 day marks a group boundary. I imagine two new annotations could do the trick, but I am struggling to write them and would ideally like to do so without resorting to raw SQL. A new annotation that is equal to the date_time of the session when dt_difference is greater than one day, null otherwise. A new annotation that fills all these nulls with the first non-null value (in … -
Ordering not rendering the way I prefer when compared to sqlite and postgres
I am using django templatetag regroup to nest grouping in template, my problem is that regroup is not working the way I want for some reason it works well in sqlite but not in postgres #My Model class Question(models.Model): TEXT = "textarea" TEXT_MULTIPLE = "textmultiple" SHORT_TEXT = "text" RADIO = "radio" CHECKBOX = "checkbox" DATE = "date" NUMBER = "number" SELECT = "select" FIELD_TYPE = ( (TEXT, "Long text"), (SHORT_TEXT, "Short text"), (TEXT_MULTIPLE, "Text multiple"), (RADIO, "Radio"), (CHECKBOX, "Checkbox"), (DATE, "Date"), (NUMBER, "Number"), (SELECT, "Select"), ) field_type = models.CharField(choices=FIELD_TYPE, default=SHORT_TEXT, max_length=13) category = models.ForeignKey( Category, on_delete=models.CASCADE ) section = models.ForeignKey( Section, on_delete=models.CASCADE, blank=True, null=True, help_text="Sub category", ) prompt = models.TextField(help_text="Question name") required = models.BooleanField(default=True, help_text="Required") help_text = models.TextField(blank=True, help_text="Description for question") disabled = models.BooleanField(default=False, help_text="Disable field") enable_status = models.BooleanField( default=True, help_text="Enable status for questionaire" ) enable_date = models.BooleanField(default=True, help_text="Enable date") enable_field = models.BooleanField(default=True, help_text="Enable Input field") question_number = models.CharField( blank=True, max_length=255, help_text="Question number" ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) created_by = models.ForeignKey( User, blank=True, null=True, on_delete=models.CASCADE, help_text="Created by" ) def __str__(self): return self.prompt #My view def question_list(request, company_id=None): categories = Category.objects.all() company_id = request.session.get("company_id") category = Category.objects.first() questions = "" if category is not None: try: questions = category.question_set.all().order_by("category") …