Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I've been trying to build a simple Django website but have been running into an error
I've been stuck with this DoesNotExist at /match/create Match matching query does not exist. error, and can not figure out what the problem is. Any help would be appreciated. This is my urls.py from django.conf.urls import url from django.urls import path, include from . import views app_name = 'match' urlpatterns = [ path('', views.match, name="list"), url('create/', views.profile_create, name="create"), path('<slug:slug>', views.match_detail, name="detail"), ] This is my views.py from django.shortcuts import render from .models import Match from django.http import HttpResponse def match(request): matches = Match.objects.all().order_by('date') return render(request, 'match/match.html', { 'matches': matches }) def match_detail(request, slug): #return HttpResponse(slug) match = Match.objects.get(slug=slug) return render(request, 'match/match_detail.html', { 'match': match }) def profile_create(request): return render(request, 'match/profile_create.html') This is my profile_create.html {% extends 'base_layout.html' %} {% block content %} <div class="create-match"> <h2>Create a Profile</h2> </div> {% endblock %} -
Best way to upload CSV and insert its info into database table using Django and PostgreSQL
What is the best way to upload a CSV file information and then saving it into a PostgreSQL table? If the upload is successful I will check on the database, I don't want to show the table anywhere in the templates. Please inform if you need more info. template where the upload will happen: {% extends "product_register/base.html" %} {% block content %} <form action="" method="post" autocomplete="off"> {% csrf_token %} <label for="file1">Upload a file: </label> <input type="file" id="file1" name="file"> <div class="row"> <div class="col-md-8"> <button type="submit" class="btn btn-success btn-block btn-lg"><i class="far fa-save"></i> Submit</button> </div> <div class="col-md-4"> <a href="{% url 'product_list' %}" class="btn btn-secondary btn-block btn-lg"> <i class="fas fa-stream"></i> Lista de Produtos </a> </div> </div> </form> {% endblock content %} views.py def category_form(request): """Cadastro de Categorias""" if request.method == "GET": return render(request, "product_register/category_form.html") else: #CSV UPLOAD HERE return render(request, "/product") models.py class Category(models.Model): """Classe Categoria""" name = models.CharField(max_length=20) def __str__(self): return self.name forms.py class CategoryUpload(forms.ModelForm): """Upload de Categorias""" class Meta: model = Category fields = "__all__" -
After upgrade, raw sql queries return json fields as strings on postgres
I am upgrading a Django app from 2.2.7 to 3.1.3. The app uses Postgres 12 & psycopg2 2.8.6. I followed the instructions and changed all my django.contrib.postgres.fields.JSONField references to django.db.models.JSONField, and made and ran the migrations. This produced no changes to my schema (which is good.) However, when I execute a raw query the data for those jsonb columns is returned as text, or converted to text, at some point. I don't see this issue when querying the models directly using Model.objects.get(...). import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "big_old_project.settings") django.setup() with connection.cursor() as c: c.execute("select name, data from tbl where name=%s", ("rex",)) print(c.description) for row in c.fetchall(): for col in row: print(f"{type(col)} => {col!r}") (Column(name='name', type_code=1043), Column(name='data', type_code=3802)) <class 'str'> => 'rex' <class 'str'> => '{"toy": "bone"}' Trying the old trick of "registering" the adapter doesn't work, and shouldn't be needed anyway. import psycopg2.extras psycopg2.extras.register_json(oid=3802, array_oid=3807, globally=True) This app has a lot of history, so maybe something is stepping on psycopg2's toes? I can't find anything so far, and have commented out everything that seems tangentially related. Going through the release notes didn't help. I do use other postgres fields so I can't delete all references to contrib.postgres.fields from my models. Any … -
Can you use a Jinja variable within a python Tag?
I'm new to the Django Framework and I'm trying to create a link to a site in which I pass a variable that exists in the current loaded/rendered site as follows: {% extends "layout.html" %} {% block title %} {{ title }}{{ content_title }} {% endblock %} {% block body %} <h1>{{ title }}</h1> {{ content|safe }} {% if matches %} {% for item in matches %} <li><a href="{% url 'contentlist' item %}">{{ item }}</a></li> {% endfor %} {% endif %} {% if edit_button %} <form action="{% url 'edit' title %}" method="post"> <input type="Submit" value="Edit Entry"> </form> {% endif %} {% endblock %} Specifically this line keeps giving me an error: <form action="{% url 'edit' title %}" method="post"> I have also tried <form action="{% url 'edit' {{ title }} %}" method="post"> No matter what I try, I keep getting a NoReverseMatch exception with the following exception value Reverse for 'edit' with arguments '('',)' not found. 1 pattern(s) tried: ['edit/(?P[^/]+)$'] -
Endpoint with very slow response with DRF when receiving a parameter
I am using Django REST framework for my API and I start using filters, depending on the value, it make various count, but it take at least 3 minutes everytime I make a response. The serealizer use the context['request'] to get the url parameter and filter for the result class CheetosSerializer(serializers.ModelSerializer): total_cheetos = serializers.SerializerMethodField() cheetos_on_sale = serializers.SerializerMethodField() cheetos_on_stock = serializers.SerializerMethodField() class Meta: model = Cheetos fields = ( 'total_cheetos' ,'cheetos_on_sale' ,'cheetos_on_stock' ) read_only_fields = fields def get_total_cheetos(self,obj): request_object = self.context['request'] customer_id = request_object.query_params.get('Shop__id_Cat_Customer') if customer_id is None: return Cheetos.objects.filter(Estatus=3).count() else: return Cheetos.objects.filter(Estatus=3,Shop__id_Cat_Customer = customer_id).count() def get_cheetos_on_sale(self,obj): request_object = self.context['request'] customer_id = request_object.query_params.get('Shop__id_Cat_Customer') if customer_id is None: return Cheetos.objects.filter(Estatus=3, id_Cat = 1).count() else: return Cheetos.objects.filter(Estatus=3, id_Cat = 1,Shop__id_Cat_Customer = customer_id).count() def get_cheetos_on_stock(self,obj): request_object = self.context['request'] customer_id = request_object.query_params.get('Shop__id_Cat_Customer') if customer_id is None: return Cheetos.objects.filter(Estatus=3, id_Cat = 2).count() else: return Cheetos.objects.filter(Estatus=3, id_Cat = 2,Shop__id_Cat_Customer = customer_id).count() On the view is where I set the filterset parameter class CheetosView(DefaultViewSetMixin): filterset_fields = ['Shop__id_Cat_Customer'] queryset = Cheetos.objects.all() serializer_class = CheetosSerializer And I use postman to validate the data, and here it says the time it takes with the correct values I´m looking for: Postman Result Is there a way to make this much better? -
django: chart.js graph not rendering anything
I have been using chart.js for quite some time and I am coming across a bug that makes me bang my head off the wall for hours. I don't get any error outputed (neither in log, neither in server, neither in js from google dev tool) but nothing shows up on the graph. What's interesting is that although nothing at all gets rendered when there is a mistake in the chart.js code of one graph, in this case, everything else is rendered just fine. In addition, the data for this graph makes it from the view to the template just fine too. I can even print it on screen with no problem. I am out of things to try so here is my code: chart.js code: $(document).ready(function() { var endpoint = 'Supplier2.html' var default_items = [] var labels = [] var default_item1s = [] var label1s = [] ; $.ajax({ method: "GET", url: endpoint, success: function (data) { labels = data.labels default_items = data.default_items label1s = data.label1s default_item1s = data.default_item1s setChart() }, error: function (error_data) { console.log(error_data) } } ) function setChart(){ var ctx3 = document.getElementById('myChart3').getContext('2d'); var myChart3 = new Chart(ctx3, { type: 'bar', data: { labels: labels, datasets: [{ … -
Order objects that contain a many-to-many field that need to be ordered beforehand in Django
I've these two models: class Message(models.Model): content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) class Chat(models.Model): title = models.CharField(max_length=255) messages = models.ManyToManyField('Message') How do I order the chats by the last send message in each chat? -
No changes are detected when I try to make migrations while models.py was modified
I modified the model.py but when I tried to do the migrations the compliator answered me that there are none: >>>python manage.py makemigrations No changes detected My attempts to solve the problem: As you can see on the image I have a 'migrations' folder: python manage.py makemigrations -v 3 doesn't give me more informations In my main project folder, in settings.py there is the app: ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo' ] -
Django select_related doesn't show all fields, but raw SQL does
I have a table of hosts, and a table of parameters, with a foreign key linking the parameters back to hosts. I want to select all the hosts, and the parameter "kernelversion". >>> q = Parameter.objects.filter(name__exact='kernelrelease').select_related('host')[:1] This is the SQL query it shows will use, notice it's selecting all the fields from inventory_host, however only inventory_parameter columns are shown in the final QuerySet >>> print(q.query) SELECT `inventory_parameter`.`id`, `inventory_parameter`.`name`, `inventory_parameter`.`value`, `inventory_parameter`.`host_id`, `inventory_host`.`id`, `inventory_host`.`certname`, `inventory_host`.`report_timestamp`, `inventory_host`.`role`, `inventory_host`.`ipaddress`, `inventory_host`.`operatingsystemrelease`, `inventory_host`.`manufacturer`, `inventory_host`.`productname`, `inventory_host`.`alive`, `inventory_host`.`datacenter_id` FROM `inventory_parameter` INNER JOIN `inventory_host` ON (`inventory_parameter`.`host_id` = `inventory_host`.`id`) WHERE `inventory_parameter`.`name` = kernelrelease ORDER BY `inventory_parameter`.`name` ASC LIMIT 1 >>> q.values() <QuerySet [{'id': 133376, 'name': 'kernelrelease', 'value': '2.6.32-754.3.5.el6.x86_64', 'host_id': 4061}]> I tried to run the SQL query above manually, and it provides all the results it should. Why is django removing all the inventory_host columns from the output? MariaDB [opstools]> SELECT `inventory_parameter`.`id`, `inventory_parameter`.`name`, `inventory_parameter`.`value`, `inventory_parameter`.`host_id`, `inventory_host`.`id`, `inventory_host`.`certname`, `inventory_host`.`report_timestamp`, `inventory_host`.`role`, `inventory_host`.`ipaddress`, `inventory_host`.`operatingsystemrelease`, `inventory_host`.`manufacturer`, `inventory_host`.`productname`, `inventory_host`.`alive`, `inventory_host`.`datacenter_id` FROM `inventory_parameter` INNER JOIN `inventory_host` ON (`inventory_parameter`.`host_id` = `inventory_host`.`id`) WHERE `inventory_parameter`.`name` = 'kernelrelease' AND host_id = 4061 ORDER BY `inventory_parameter`.`name` ASC LIMIT 1\G *************************** 1. row *************************** id: 133376 name: kernelrelease value: 2.6.32-754.3.5.el6.x86_64 host_id: 4061 id: 4061 certname: myhost001.sub.domain.com report_timestamp: 2020-10-09 11:12:33.765000 role: qwerty ipaddress: … -
"Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received" Django Channels
I get this error only in chrome (not in safari and not in firefox) when trying to connect to the server via a websocket: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received. The server accepts the connection but chrome unexpectedly closes it immediately. This is how I create a websocket connection on the frontend: const websocket = new WebSocket('ws://127.0.0.1:8000/ws/', ['Token', 'user_secret_token']) This is how my consumers.py looks: class MyConsumer(JsonWebsocketConsumer): def connect(self): self.room_group_name = 'example_room' # Join room group async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name) self.accept() -
How do you list all warning filters in Python?
I just spent the day trying to remove this warning from my output: sys:1: ResourceWarning: unclosed file <_io.TextIOWrapper name='/dev/null' mode='w' encoding='UTF-8'> I just finished a binary search of about 100k lines of code to try to figure this out. I still haven't found what's leaving /dev/null open, but I did find that some of our code says: warnings.simplefilter("always") Removing that removes the warning. Hooray! I plan to remove that bit of code, but I'm curious of two things: Could I have avoided doing a binary search for this somehow? Enabling TRACEMALLOC=1 was entirely ineffective (maybe because this is in third-party code we import?) Once I remove this, is there a way to list all of the warning filters that are applied at a particular point in the code? Seems like an important thing to be able to analyze, but I can't figure out how. -
Recover deleted files while creating a branch in Git
I have a branch in a Git and in that branch I have made my local changes. But to push to master I have created a new branch all the files in my previous branch which is in my local got deleted. Is there a way to recover those? Have spend lot of time installing recovery softwares and going through all the posts but don't find anything useful. So thought to ask the community for help.It will be very helpful to get some suggestions. Thanks in advance -
How to get data at once from sql for some n entities
The following are my models: class Symbol(models.Model): symbol = models.CharField(max_length = 50, unique=True) # The following three are collected every hour Class Type1data(models.Model): symbol = models.ForeignKey(Symbol,on_delete=models.CASCADE) quantity = models.IntegerField() date = models.DateTimeField() Class Type2data(models.Model): symbol = models.ForeignKey(Symbol,on_delete=models.CASCADE) quantity = models.IntegerField() date = models.DateTimeField() Class Type3data(models.Model): symbol = models.ForeignKey(Symbol,on_delete=models.CASCADE) quantity = models.IntegerField() date = models.DateTimeField() Class Average(models.Model): symbol = models.ForeignKey(Symbol,on_delete=models.CASCADE) value = models.FloatField() Now i have to loop over each symbol and get 100 data of each Type1data & Type2data & Type3data and store some value in Average table symbolObjects = Symbol.objects.all() for symbol in symbolObjects: # get the latest 100 data of each type1Objects = Type1data.objects.filter(symbol=symbol).sort_by('-date')[0:100] type2Objects = Type2data.objects.filter(symbol=symbol).sort_by('-date')[0:100] type3Objects = Type3data.objects.filter(symbol=symbol).sort_by('-date')[0:100] # I have to calculate some value and then save the results in Average( symbol = symbol, value = value calculated from 100 samples of Type1data, Type2data, Type2data ).save() The number of symbols is 20000+ So I am thinking to run 1000 symbols loop data at once for symbol in symbolObjects[0:1000]: # get the latest 100 data of each type1Objects = Type1data.objects.filter(symbol=symbol).sort_by('-date')[0:100] type2Objects = Type2data.objects.filter(symbol=symbol).sort_by('-date')[0:100] type3Objects = Type3data.objects.filter(symbol=symbol).sort_by('-date')[0:100] # I have to calculate some value and then save the results in Average( symbol = symbol, value = value … -
How to list distinct sqlite queryset in django
I'm trying to get all unique values of a certain field of a Django model. Unfortunately sqlite doesn't support DISTINCT on fields so the following didn't work dates = Invoices.objects.distinct('invoice_date') so I've tried this dates = Invoices.objects.values_list('invoice_date').distinct() what looked good on first sight because dates.count() returns the amount of unique values. However len(dates) still returns the total number of dates and when I transform it into a list (to be able to build a JSON response) via list(dates) I end up with all dates :/ How can get that list of uniques values? Or is it impossible with sqlite? -
RSS to html bootstrap
good night, i have a link with direct access to an rss that gets me weather information for a certain city. How is it possible from rss to make a web page with these rss? I was looking but I didn't find information to help me i create a class name weather class WeatherFeed(Feed): title = "meteorology" link = "https://weather-broker-cdn.api.bbci.co.uk/en/forecast/rss/3day/2742611" description = "meteorology" def items(self): return Post.objects.filter(status=1) def item_title(self, item): return item.title def item_description(self, item): return truncatewords(item.content, 30) I don't know what I have to do anymore -
How to use DRF serializer with djongo in Django?
I'm using djongo with Django in order to be able to use MongoDB. But there seems to be a small problem that I cannot fix. I have such model: class Company(models.Model): _id = models.ObjectIdField(primary_key=True) STATUS_CHOICES = [ (0, "active"), (1, "inactive"), ] status = models.IntegerField(choices=STATUS_CHOICES, null=False, blank=False) name = models.TextField(unique=True, null=False, blank=False) short_name = models.CharField(max_length=40, default=None) description = models.TextField(null=False, blank=False) profile_image = models.ImageField(default=None, upload_to=company_directory_path) owners = models.ArrayField(model_container=Person, default=[]) staff = models.ArrayField(model_container=Employee, default=[]) roles = models.ArrayField(model_container=Role, default=[]) address = models.EmbeddedField(model_container=Address, null=False, blank=False) localizations = models.ArrayField(model_container=Address, default=[]) LEGAL_FORM_CHOICES = [ (0, "jednoosobowa działalność gospodarcza"), (1, "spółka cywilna"), (2, "spółka jawna"), (3, "spółka partnerska"), (4, "spółka komandytowa"), (5, "spółka komandytowo-akcyjna"), (6, "spółka z ograniczoną odpowiedzialnością"), (7, "spółka akcyjna"), (8, "fundacja"), (9, "szkoła/uczelnia wyższa"), (10, "inne"), ] legal_form = models.IntegerField( choices=LEGAL_FORM_CHOICES, null=False, blank=False ) nip = models.CharField(max_length=10, null=False, blank=False) pkd = models.CharField(max_length=11, choices=PKD_OPTIONS, null=False, blank=False) created_at = models.DateField(blank=False, null=False, auto_now_add=True) objects = models.DjongoManager() def __str__(self): return self.name (Person, Employee and Role models are abstract) I have this view set: class CompanyViewSet(CustomViewSet): """The viewset for the User model.""" queryset = Company.objects.all() # mapping serializer into the action serializer_classes = { "list": CompanyListSerializer, "retrieve": CompanyDetailSerializer, "update": CompanyUpdateSerializer, "create": CompanyDetailSerializer, } default_serializer_class = CompanyListSerializer def get_serializer_class(self): return … -
Problems adding multiple data in one field
I am developing an application where a task is assigned to a developer and each task has different activities, the scare is that I am trying to add several activities per task but I can only add one, I have tried ajax but it did not work This is my model class Task(models.Model): developer = models.ManyToManyField(Developer) type_task = models.ForeignKey(TypeTask, on_delete=models.CASCADE) task = models.CharField(max_length=50) description = models.TextField() state = models.BooleanField(default=True) slug = models.SlugField(max_length=60, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Activities(models.Model): name = models.CharField(max_length=50, unique=True) task = models.ManyToManyField(Task) this is my view class TaskCreateView(PermissionRequiredMixin, LoginRequiredMixin, CreateView): login_url = 'users:login' permission_required = 'tasks.can_add_user' template_name = 'tasks/add_task.html' form_class = TaskForm model = Task success_url = reverse_lazy('tasks:task') -
Django/wsgi not serving media files properly
I'm developing a small web GIS app with Django just for demo purposes. Everything works fine with static and media files when Debug=True, but when I set Debug to False in production and want to serve static and media files through the web server (apache), using wsgi, I get 404 when sending a request to fetch the .tiff files from media folder (but files are there, I've checked the paths a million times). I know it's not a good idea to serve .tiff files from media folder and from the same server Django uses, I know I should dedicate a different server for media and static files or use AWS S3 buckets (which is a plan for the future), but this is only a demo/presentation/PoC kind of an app and I want to know what am I doing wrong. A working scheme is pretty straightforward, I process some images (geotiffs), store them locally in data folder (which is defined as a media folder in my project), save the path in PostgreSQL database and render it in frontend. Like I said, everything works fine in production when Debug=True, but when I change it to False for security reasons, only media files … -
Random default value for a related model Django
I got a model Car and model Bumper related to Car . How can I set the default value of a Bumper's car to a random Car object in Django ? -
alpine.js $dispatch modal -> submit Form
I am using django and i have a base template where i defined a modal using alpine.js with $dispatch sender. base.html: <div x-data="modal()" class="mt-6" x-cloak> <template x-on:show-modal.window="isOpenModal = $event.detail.show; modalHeader = $event.detail.modalHeader; modalData = showData($event.detail.modalData); "></template> <div class="absolute z-50 top-0 left-0 w-full h-full flex items-center justify-center bg-black bg-opacity-50" x-show="isOpenModal"> <div class="z-50 text-left bg-gray-200 px-4 shadow-xl rounded-lg mx-2 md:max-w-lg md:p-6 lg:p-8 md:mx-0 h-auto " > <div class="flex justify-between"> <h2 id="modalHeader" class="text-2xl" x-text="modalHeader"> </h2> </div> <div class="w-full border border-gray-600 mt-4" ></div> <div id="modalContent" class="text-lg w-auto" > </div> </div> </div> </div> in script tags .... function modal(){ return{ isOpenModal: false, modalHeader:'', modalData: '', showData(data){ document.getElementById('modalContent').innerHTML = data let fp = flatpickr(".pickerDate", {locale: "at", dateFormat: "d.m.Y"}); }, } } then in the other html which is extendet from the base.html i want to use the modal where i want to get with axios form data from the server and put it into the modal. This is working perfect. But i don't know how to realize the submit button ? new.html <div x-data="test()" @click="getCreateForm($dispatch)"> test click </div> this is the point where i go to function getCreateForm .... function test(){ return{ getPatientCreateForm($dispatch){ axios.get("{% url 'user:createForm'%}") .then(response => { var modalHeader = response.data.header var modalData = … -
Return an image as a GET response django
I would like to return a .png image with Django. I know I can serve a basic HTML file in which I would have an <img src"">. I would like to be able to serve just the image just like in here: https://static.toiimg.com/photo/msid-67586673/67586673.jpg?3918697 I have an /images/ folder with this image and a Django Model class CatImage(django.db.models.Model): image = models.ImageField(upload_to="images/") Preferably, I would like to serve it with a GET response. -
Django - HTML input value not printing in Views
I want to pass an input value to views, assign variable, and print out the result. HTML: <div class="collapse navbar-collapse" id="navbarColor02"> <form class="col-sm-12" method="POST">{% csrf_token%} <div class="form-group row"> <input type="text" class="col-sm-10 form-control" name='stockList'> <div class="col-sm-2"> <button type="submit" class="btn btn-primary mb-2">Append</button> </div> </div> {% block label %}{% endblock %} </form> views: def home(request): print(request.POST) if request.method == 'POST' and request.POST: stockPost = request.POST.get('stockList','') print(stockPost) expected Result: when clicking submit, the terminal will display the values in 'stockList' Actual result: the terminal does not print the values in 'stockList' I saw some explanations regarding the queryDict but had a hard time following them. Any help would be greatly appreciated! -
Unrecognised error when deploying django app to heroku with git push
I have a django app with the following file structure - project_name (settings, __init__, urls, asgi, wsgi ... *.py) - manage.py - app_name - templates (template files) - static (just some static files) (urls, views, apps, models __init__ and the other usual files within django app *.py) - requirements.txt I think that I have run all the necessary commands inside top-level directory (containing project_name and app_name sub-directories) git init heroku git:remote -a (heroku_app_name) git add . git commit -am "this is a commit message" and then the error comes in git push heroku master with the following log: remote: -----> Python app detected remote: -----> Installing python-3.6.12 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting django remote: Downloading Django-3.1.3-py3-none-any.whl (7.8 MB) remote: Collecting django-heroku remote: Downloading django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB) remote: Collecting sqlparse>=0.2.2 remote: Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) remote: Collecting asgiref<4,>=3.2.10 remote: Downloading asgiref-3.3.1-py3-none-any.whl (19 kB) remote: Collecting pytz remote: Downloading pytz-2020.4-py2.py3-none-any.whl (509 kB) remote: Collecting whitenoise remote: Downloading whitenoise-5.2.0-py2.py3-none-any.whl (19 kB) remote: Collecting psycopg2 remote: Downloading psycopg2-2.8.6.tar.gz (383 kB) remote: Collecting dj-database-url>=0.5.0 remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) remote: Building wheels for collected packages: psycopg2 remote: Building … -
How to Sum time values from a specific month in Django?
I have the following view in my views.py: timesheet = Timesheet.objects.annotate( total_time=ExpressionWrapper( ExpressionWrapper(F('out') - F('entry'), output_field=IntegerField()) - Coalesce(ExpressionWrapper(F('lunch_end') - F('lunch'), output_field=IntegerField()), Value(0)), output_field=DurationField() ) ) This allows me to calculate the total worked hours in a single day, which is then looped on a table. But, I need to be able to Sum all the total worked hours from each specific month. Is this achievable? -
How to select a DateTime on a Django website using a selector filled with local JavaScript logic?
I am building a website using Django on the backend. On the website, there should be a form which allows a user to select a date and time. The exact date and time which users should be able to select depends on their current timezone. Therefore, I implement the logic showing users possible times with JavaScript on the users side. Currently, I was using a forms.DateTimeField but this gives me a textbox UI when using the {{ form.as_table }} in the template. I want to show the users a selector UI, so I manually implemented it in HTML and filled it with JavaScript. Now I ran into problem that the time format depends on local language of the user - for example, it is different in the German and the English language. So my question is, what should I do instead? I feel like my above solution has too much technical debt to pursue it further. Should I create a custom form field, and then just transmit the UNIX timestamp which I can easily convert back and forth using JavaScript on the users side? Or is there some other architecture / solution or even a already available code online? I …