Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to force server time on DateTimeField?
I have a datetime field on a model date_time = models.DateTimeField(auto_now_add=True, blank=True, null=True) I need it to be as server time, the problem is when i change local time on pc the field created with the modified time and date. Is it because my server is local (for dev) or is it how datetimefield field works? Thanks! -
Django dumpdata generating
I have a question how to generate dumpdata without this txt on start: [1mLoading .env environment variables...[0m Here is an example: [1mLoading .env environment variables...[0m [ { "model": "auth.permission", "pk": 1, "fields": { "name": "Can add permission", "content_type": 1, "codename": "add_permission" } }, .... I can't find solution, it is annoying, because i want to do a sh script docker-compose exec django pipenv run python manage.py dumpdata --indent 2 > fixtures/test_dumpdata.json Thanks for all help. -
Scheduled tasks in Django to update data in the models (database)
I need to schedule tasks via Pythonanywhere, to update some records in my database. As an example, I do have Events as models: models.py class Events(models.Model): event_title = models.CharField(max_length=300) event_info = models.TextField(max_length=2000) event_date = models.DateField(default=now) event_time = models.TimeField(default='00:00') event_location = models.CharField(max_length=150) event_status = models.CharField(max_length=30, choices=EVENT_STATUS_CHOICES, default='New Event') Also within that Events class in models.py I have the following: def save(self, *args, **kwargs): if date.today() > self.event_date: self.event_status = 'Completed Event' super(Events, self).save(*args, **kwargs) Thanks to that, all events in the past, change their status to Completed. Problem is, you need to refresh the page to have the save function run on the production website. It also drives some other functions, e.g. showing the user the count of active events - this one as well, in order to show the right active number of events, has to be refreshed manually. By scheduling tasks in PA to run overnight, iterating through all Events, and if in the past, changing their status. I created the below file and uploaded it to PA Tasks. tasks.py from .models import Events from datetime import date def verify_events(): all_events = Events.objects.all() for event in all_events: if event.event_date < date.today(): event.event_status = 'Completed Event' event.save() I got an … -
Can i use both django autofield and foreignkey on one field?
so i have specific use case currently the database has a table with one field that acts as both primary key and foreign key (and i have no access to change this as it would break other processes) so what i tried with the models is something like this: class Foos(models.Model): foo_id = models.AutoField(primary_key=True) foo_name = models.CharField(max_length=15) foo_dt = models.DateTimeField() class Bars(models.Model): bar_id = models.AutoField(primary_key=True) bar_id = models.ForeignKey(Foos, db_column='bar_id', on_delete=models.CASCADE, blank=True, null=True, related_name='bars') bar_qty = models.IntegerField() bar_image = models.ImageField() That didn't work as django will keep the last bar_id (the foreignField) and ignore the AutoField, the thing is i need the foreign key to do some reverse lookup like Foos.object.values(bars__bar_qty) so i can get the left outer join query. But someone else need the AutoField. I know django is really strict on it but is there a possible solution? i just need to keep the reverse lookup i am fine with autofield if it is possible but the thing is django return an error not permitted. -
My if statement doesn't work with two str
i'm trying to use Django to build a wikipedia like. When I want to search an article, i type the research in the search input. I collect my research in my views.py in a function. I have a list of different entries stores in the wiki. But when i try to compare with an if statement if the content of the request is in my list, automatically, the case is false. below my silly function just for testing what's happened def search(request): request_dict = json.dumps(request.GET) print(request_dict, type(request_dict)) request_dict = json.loads(request_dict) print(request_dict, type(request_dict)) title = request_dict["q"] print(title, type(title)) for item in util.list_entries(): print(item, type(item)) title = title.casefold() print(item.casefold().encode("utf-8"), title.encode("utf-8")) if item.casefold().encode("utf-8") == title.encode("utf-8"): entry(request, item) else: print("ko") pass and this is the print in my terminal {"q": "html"} <class 'str'> {'q': 'html'} <class 'dict'> html <class 'str'> CSS <class 'str'> b'css' b'html' Django <class 'str'> b'django' b'html' Git <class 'str'> b'git' b'html' HTML <class 'str'> b'html' b'html' Python <class 'str'> b'python' b'html' ko how can i fix that? I know that here json.loads and dumps here doesn't do anything more than request.GET["q"]. I'm so disappointed and try everything that i could to fix this bug -
Django get users who have updated their age field in the last 1 day
How can I get users who do not update their age information in last 1 day? I need to use Django ORM. not For loop. I tried something in the second code block but without success. You can tell by looking at what I've done from simple_history.models import HistoricalRecords class User(AbstractUser): age = models.IntegerField() history = HistoricalRecords() ################################################################################ date_start = timezone.now() - timezone.timedelta(days=1) queryset = User.history.filter(history_user_id__in=users,history_date__lte=timezone.now(),history_date__gte=date_start).annotate( lag=Window( partition_by=[F("id")], expression=Lag("age"), order_by=[F("history_date")], ) ) here what i have to do is compare lag with age and see if it is updated -
How to run multiple manage.py using docker file
I have Django application which has docker file and using below command to bring up the application CMD ["gunicorn", "--bind", ":8000", "--workers", "3", "--worker-class", "uvicorn.workers.UvicornWorker", "myapplication.asgi:application"] Would like to run one more process "task_process" which is present in the below directory structure taskApp/ __init__.py models.py management/ __init__.py commands/ __init__.py task_process.py How to execute task_process after loading an application ? I tried the below shell script command to execute same.. But task_process is not running using below commands in startup.sh #!/bin/sh exec gunicorn --bind :8000 --workers 3 --worker-class uvicorn.workers.UvicornWorker myapplication.asgi:application & exec python manage.py task_process Updated existing Docker file as below RUN chmod +x startup.sh CMD ["./startup.sh"] -
When I add settings folder with settings for different environments, I get CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
I want to make two files with different settings for dev and prod. I created a python package in the app folder where my settings are, and even if I run the app with old settings, I receive an error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. Here is my project structure: -
Collection uploaded to Ansible Automation Hub displays all files under Documentation and Plugins
I wrote a collection containing one lookup plugin named res_query. This plugin imports two local libraries (credentials.py, resources.py) from the module_utils directory. Further it uses the common.py document fragment from the directory doc_fragments. After uploading this collection to our Ansible Automation Hub, ALL files (common.py, credentials.py, resources.py, res_query.py, README.md) are displayed under Documentation and Plugins. I expected, that only the README.md and res_query.py should be displayed. What I'am doing wrong? namespace.collname ├── CHANGELOG.md ├── galaxy.yml ├── LICENSE.md ├── meta │ └── runtime.yml ├── plugins │ ├── doc_fragments │ │ └── common.py │ ├── lookup │ │ └── res_query.py │ ├── modules │ └── module_utils │ ├── credentials.py │ └── resources.py └── README.md -
"That username is already taken." but there is no entry in DB
In my environment I'm trying to create a new superuser via python .\manage.py createsuperuser. However, when I enter the name I get the following error: Error: That username is already taken.. So I check the auth_user table in PgAdmin and I can see there are no entries. Moreover, the QuerySet is empty when I do the following: from django.contrib.auth.models import User superusers = User.objects.filter(is_superuser=True) superusers >>> <QuerySet []> I'm using a managed cloud-hosted PostgreSQL server with the postgresql_psycopg2 client, and have checked that all credentials are correct. What am I doing incorrectly? I'm using Django 4.1.2. -
Python Datetime Comparison
I'd like to check if the current date is bigger than a date put in by the user. All dates are converted using strftime('%d/%m/%Y'). But if I compare both dates, I get a wrong result: absenzen.view def absenzen(request): if request.user.is_authenticated: # if user is logged in object_list = Subject.objects.order_by('name') subject_list = [] for subject in object_list: subject_list.append(subject.name) absenzen_local = Absenzen.get_absenzen(student=request.user.id, subjects=subject_list) current_date = datetime.date.today().strftime('%d/%m/%Y') return render(request, 'absenzen.html', {'absenzen': absenzen_local, 'current_date': current_date}) else: # else redirect to login page return redirect('loginForm:login') get_absenzen method def get_absenzen(student, subjects): absenzen_dict = {} for subject in subjects: absenzen_list_complete = [] absenzen_object_list = Absenzen.objects.filter(student=student, subject__name=subject).order_by('-date') for absenz in absenzen_object_list: absenzen_list = [] expire_date = absenz.date + datetime.timedelta(days=10) if absenz.excused: absenzen_list.append('Ja') elif not absenz.excused: absenzen_list.append('Nein') absenzen_list.append(expire_date.strftime('%d/%m/%Y')) absenzen_list_complete.append(absenzen_list) print(absenzen_list_complete) absenzen_dict[subject] = absenzen_list_complete print(absenzen_dict) return absenzen_dict html {% if absenzen %} {% for subject, absenzen in absenzen.items %} <button class="collapsible" type="button">{{ subject }}</button> <div class="content"> {% if absenzen %} <ul> {% for absenzen_list in absenzen %} <div class="content-text"> <li>Entschuldigt: {{ absenzen_list.0 }}</li> {% if absenzen_list.0 == 'Nein' %} {{ absenzen_list.1 }} {{ current_date }} {% if absenzen_list.1 < current_date %} <p><strong>Abgabedatum schon abgelaufen</strong></p> {% else %} <p>--> Abgabadatum: {{ absenzen_list.1 }}</p> {% endif %} {% else %} <p>Abgegeben</p> {% … -
Hiding Django form fields using Jquery but it is not hiding form labels (using crispy forms)
I am trying to hide certain fields in a form based on select field choices. For example for Select field "system_description_1" If option "Direct" is selected following fields should be hidden (also hidden by default on page load), but when "Indirect" is selected the fields should become visible. This function is absolutely working fine using Jquery, but it is still showing the form label, It is hiding the field but not the label of the field how do I hide them ? I want to hide the field label when I hide the field, but show the field label when I unhide or show them. Fields: secondary_circulation_pump_model secondary_circulation_pump_capacity models.py: class Systemprofile(models.Model): SYSTEMDESC1 = ( ('direct', 'Direct'), ('indirect', 'Indirect') ) SECONDARYPUMPMODEL = ( ('grundfos', 'Grundfos'), ('cnp', 'CNP'), ('others', 'Others') ) SECONDARYPUMPCAPACITY = ( ('ltr-hr', 'Ltr/hr'), ('others', 'Others') ) name = models.CharField(max_length=255, null=True) system_description_1 = models.CharField(blank=True, max_length=255, null=True, choices=SYSTEMDESC1) secondary_circulation_pump_model = models.CharField(blank=True, max_length=255, null=True, choices=SECONDARYPUMPMODEL) secondary_circulation_pump_capacity = models.CharField(blank=True, max_length=255, null=True, choices=SECONDARYPUMPCAPACITY) forms.py class CreateSystemprofile(ModelForm): class Meta: model = Systemprofile fields = '__all__' system_profile.html {% extends 'base.html' %} {% load static %} {% block content %} {% load crispy_forms_tags %} <script> function Hide() { if(document.getElementById('id_system_description_1').options[document.getElementById('id_system_description_1').selectedIndex].value == "Direct") { document.getElementById('id_secondary_circulation_pump_model').style.display = 'none'; document.getElementById('id_secondary_circulation_pump_capacity').style.display = … -
how to create unicode slug in bangla language in django from title field
I am getting this error in Django: when i click slingle view page in djanog my slug is insert properly but when i try to view single page this error is shown what to do now: Not Found: /ফবরযর-থক-বস-ভড-দয-হব [25/Oct/2022 10:40:42] "GET /%E0%A6%AB%E0%A6%AC%E0%A6%B0%E0%A6%AF%E0%A6%B0-%E0%A6%A5%E0%A6%95-%E0%A6%AC%E0%A6%B8-%E0%A6%AD%E0%A6%A1-%E0%A6%A6%E0%A6%AF-%E0%A6%B9%E0 %A6%AC HTTP/1.1" 404 5408 Module.py user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) type = models.ForeignKey(Type, on_delete=models.CASCADE, null=True) division = models.ForeignKey(Division, on_delete=models.CASCADE, null=True) district = models.ForeignKey(District, on_delete=models.CASCADE, null=True) upazila = models.CharField(max_length=50, blank=True, null=True) postcode = models.ForeignKey(Postcode, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=50, blank=True, null=True) mobile = models.CharField(max_length=50, blank=True, null=True) postoffice = models.CharField(max_length=50, blank=True, null=True) detail = QuillField(null=True, blank=False) bedroom = models.IntegerField(blank=True, null=True) bathroom = models.IntegerField(blank=True, null=True) veranda = models.IntegerField(blank=True, null=True) drawing = models.BooleanField(blank=True, null=True, default=False) dining = models.BooleanField(blank=True, null=True, default=False) status = models.BooleanField(blank=True, null=True, default=True) rent = models.IntegerField(blank=True, null=True) address = models.CharField(max_length=200, blank=True, null=True) google_location = models.CharField(max_length=500, blank=True, null=True) date = models.DateField(auto_now=False, blank=False, null=False) image = models.FileField(blank=True, default="feature_image.jpg") slug = models.SlugField(null=True, blank=True, allow_unicode=True, unique=True) create_date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.title def save(self, *args, **kwargs): if self.slug is None: slug = slugify(self.title, allow_unicode=True) has_slug = AddPost.objects.filter(slug=slug).exists() count = 1 while has_slug: count += 1 slug = slugify(self.title, allow_unicode=True) + '-' + str(count) has_slug = AddPost.objects.filter(slug=slug).exists() … -
How to get the Django model from its name
I have the name of the model table, for example, main_masterinventory, as a string. How do I get the model table given this name? I'm not really understanding the logic of this task, so I've got nothing to show for my work, but if you have any questions about my query, feel free to ask in the comments. -
Django filter where every item in an object's many to many list is included in provided queryset
I'm having a bit of trouble phrasing my question title, which might be why I can't find an answer. It doesn't need to be query set, it could just be a list of pks or some other method. I'll explain with an example and say what I want and what I don't. I have the following models. class Document(models.Model): allowed_groups = models.ManyToManyField(Group, related_name='allowed_documents') class Person(models.Model): permission_groups = models.ManyToManyField(Group, related_name='people') class Group(models.Model): id = models.BigIntegerField() I want to find all the documents that Person can access with the condition that they have to be a member of all of the allowed groups. I want this: Case Document(allowed_groups=1,2,7) with Person(permission_groups=1,2,6,7,11,15) -> MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=1,7) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=1,2) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=2) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=8) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=1,2,7) -> MATCH If I do this: person = Person.objects.get(pk=1) Document.objects.filter(allowed_groups__in=person.permission_groups.all()) I would match on all of the above cases except 8 (not what I want) There are many questions on stack overflow that are asking about exact matching i.e. match only on case 6 but not case 1. (also not what I want) So my question is how can I use django to do this? I've considered … -
How to properly serialize a PrimaryKeyRelatedField in Django Rest Framework
I have two Django models: Book -- which has some Wagtail StreamFields: class Book(models.Model): title = models.CharField(max_length=255) cover_image = StreamField(...) ... Publisher -- which is pure Django: class Publisher(models.Model): name = models.CharField(max_length=255) ... I wanted to have a PublisherChooser in my Wagtail admin. So I [created all that was required and then] added a field to my Book model: class Book(models.Model): title = models.CharField(max_length=255) cover_image = StreamField(...) ... publisher = models.CharField(max_length=10) panels = [ FieldPanel("title"), FieldPanel("cover_image"), FieldPanel("publisher", widget=PublisherChooser), ] Now I have a proper PublisherChooser whenever I want to create a Book in Wagtail Admin. Problem Now I want to serialize my Book model. So I have tried: class PublisherSerializer(serializers.ModelSerializer): class Meta: model = Publisher fields = [ "name", ... ] name = serializers.CharField() ... and class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = [ "title", "cover_image", ..., "publisher", publisher = serializer.PrimaryKeyRelatedField(queryset=Publisher.objects.all()) def update(self, instance, validated_data): publisher = validated_data.pop("publisher") instance.publisher_id = publisher.id return instance def to_representation(self, instance): data = super().to_representation(instance) publisher_serializer = PublisherSerializer( Publisher, context={"pk": instance.publisher} ) data["publisher"] = publisher_serializer.data return data I get publisher in the response but the publisher data doesn't seem to look right: "publisher": { "name": "<django.db.models.query_utils.DeferredAttribute object at 0x7f9ffa146310>", } -
Different format of currency using DecimalField based on choices from other models
What I am trying to do I would want Django to save different format of currency based on which preferred language that user wants to use without using localization. But I am totally lost from where to start. I have two types of currencies: US Dollar($) and Thai Baht. US Dollar can have upto maximum 2 decimal places whereas Thai Baht does not have any 2 decimal places. Here, when user chose their preferred language as USD, I would like Django save price per night of hotel room (this is defined in other models) upto 2 decimal places although its value does not have any decimal numbers. On the other hand, Thai Baht should always have 0 decimal places. Example Preferred currency is USD and price per night is $600 -> Want to save as $600.00 Preferred currency is USD and price per night is $600.12 -> Want to save as $600.12 Preferred currency is THB and price per night is ฿600 -> Want to save as ฿600 (without any decimal points) Preferred currency is THB and price per night is ฿600.12 -> This will throw validation error as there is no such 2 decimal places in THB. Below is … -
Django ORM - Annotate
G'day All, I'm trying to create a running balance of all negative transactions with a date less than or equal to the current transaction object's transaction date however if I use __lte=transaction_date I get multiple rows, while this is correct I want to sum those multiple rows, how would I do that and annotate to my queryset? Current Attempt: #getting transaction sum and negative balances to take away from running balance totals = queryset.values('transaction_date','award_id','transaction').annotate(transaction_amount_sum=Sum("transaction_amount"))\ .annotate(negative_balance=Coalesce(Sum("transaction_amount",filter=Q(transaction__in=[6,11,7,8,9,10,12,13])),0))\ #adding it all to the queryset queryset = queryset\ .annotate(transaction_amount_sum=SubquerySum(totals.filter(award_id=OuterRef('award_id'),transaction_date=OuterRef('transaction_date'),transaction=OuterRef('transaction'))\ .values('transaction_amount_sum')))\ .annotate(negative_balance=SubquerySum( totals.filter(award_id=OuterRef('award_id'),transaction_date=OuterRef('transaction_date'),transaction=OuterRef('transaction'))\ .values('negative_balance') ))\ .annotate(total_awarded=SubquerySum("award__total_awarded"))\ .annotate(running_balance=F('total_awarded')-F('negative_balance')) #This doesnt work correct, we need transaction date to be less than or eqaul not just the transaction date. #filtering on distinct, we only want one of each record, doesnt matter which one. :) distinct_pk = queryset.distinct('transaction_date','award_id','transaction').values_list('pk',flat=True) queryset = queryset.filter(pk__in=distinct_pk) What needs to be fixed: .annotate(negative_balance=SubquerySum( totals.filter(award_id=OuterRef('award_id'),transaction_date=OuterRef('transaction_date'),transaction=OuterRef('transaction'))\ .values('negative_balance') The above should really be: .annotate(negative_balance=SubquerySum( totals.filter(award_id=OuterRef('award_id'),transaction_date__lte=OuterRef('transaction_date'))\ .values('negative_balance') It will return multiple rows if I do this, what I want to do is sum those multiple rows on negative_balance. Hope the above makes sense. Any help will be greatly appreciated. Thanks, Thomas Lewin -
django rest: AssertionError at /api/v1/users/1/ 'UserDetail' should either include a `queryset` attribute, or override the `get_queryset()` method
I'm trying to follow a tutorial from the book 'Django for APIs', this tutorial consists on doing a blog project API with django rest framework. I cant get to work the UserDetail view at url: 'http://127.0.0.1:8000/api/v1/users/int:pk/' it raises the following error ,although queryset is defined in the UserDetail class in views.py: AssertionError at /api/v1/users/1/ 'UserDetail' should either include a queryset attribute, or override the get_queryset() method. here is the code: urls.py views.py serializers.py models.py urls.py: from django.urls import path from .views import UserList, UserDetail, PostList, PostDetail urlpatterns = [ path('users/',UserList.as_view()), path('users/<int:pk>/', UserDetail.as_view()), path('',PostList.as_view()), path('<int:pk>/', PostDetail.as_view()), ] views.py: from django.contrib.auth import get_user_model from rest_framework import generics from .models import Post from .permissions import IsAuthorOrReadOnly from .serializers import PostSerializer, UserSerializer # Create your views here. class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (IsAuthorOrReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer class UserList(generics.ListCreateAPIView): queryset = get_user_model().objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveUpdateDestroyAPIView): queryset_= get_user_model().objects.all() serializer_class = UserSerializer serializers.py: from django.contrib.auth import get_user_model from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: fields = ('id','author','title','body','created_at',) model = Post class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ('id','username',) models.py: from django.db import models from django.contrib.auth.models import User # … -
How to improve myself to become a full-stack freelancing developer in the aspect of technicalities and career?
I started learning coding from 5 months. My goal is to work as a full-stack web freelancing developer. I have learned programming basics (cs50) and then learned python through Youtube courses. Then I learned HTML and CSS also on youtube. Finally, I learned Django, Javascript needed for interactive client-side interface (like DOM, event listeners, fetch, API) by CS50 web programming with python and Javascript. I have applied what I learned on 5 projects (mail, auctions(e-commerce), Twitter like web site, bookstore, and google like interface). Know I'm confused about two points. The first point is what is the most compatible front-end framework that I can use with Django which will help me make better projects. The second thing is how can I work as a freelancer and any suggestions for courses or anything that will help me start my career as a freelancer. And finally, if there are any suggestions for libraries, frameworks or programming languages that will help me improve my projects and myself in web development? to summarize my questions in points: What is the best front-end framework that works and is compatible with Django? What should I do to become a full-stack freelancer (I have good experience with … -
Comparing sensor data and sending warning to Django website when below threshold
I'm able to read data from a flow sensor into python terminal and now I need to compare it to a threshold value and if it's below I need to send warning to a Django website I have created. Can anyone help with this? Thank you -
How to Ban Webmail Registration in a Django Application
How can I effectively ban: 1) Webmail (GMail, Outlook, Yahoo! and so on); and 2) Free, temporary e-mail addresses (like EmailOnDeck, 10minutemail, Mailnator) registrations in my Django Application? Is it possible to solve this problem only using built-in, Django validations? Do some Mail Sender Tool offer this feature out of the box? Thanks. -
Accordion element makes whole page move
When opening a long text accordion, the whole page (or the whole div) moves slightly. I attach a little video to show the problem visually here. I have the accordions displaying information from a django template engine loop, here's the template code: <div class="accordion accordion-borderless" id="accordion_{{ forloop.counter }}"> <div class="accordion-item"> <h2 class="accordion-header" id="heading_{{ forloop.counter }}"> <button class="accordion-button collapsed" type="button" data-mdb-toggle="collapse" data-mdb-target="#collapse_{{ forloop.counter }}" aria-expanded="false" aria-controls="collapse_{{ forloop.counter }}" > {{event.title}} </button> <div id="collapse_{{ forloop.counter }}" class="accordion-collapse collapse" aria-labelledby="heading_{{ forloop.counter }}" data-mdb-parent="#accordion_{{ forloop.counter }}"> <div class="accordion-body"> {{event.description|safe}} </div> </div> </div> </div> What is causing that movement and how can it be solved? -
Time before full counter with percent python
how to calculate based on timestamp and get the progress before the max full value? def full_energy(): time_now = 1666650096 #changes every update time_end = 1666679529 max_energy = 50 diff = datetime.utcfromtimestamp(time_now) - datetime.utcfromtimestamp(time_end) secs = diff.total_seconds() ??? # expected output # x/y (z) # 25/50 (50%) how to get the value of x and z based on this sample? -
Return Redis cached Django views with rendered React
I recently started using Django and as many Django lovers out there would say, there is nothing that beats its admin interface, auth and users out of the box. The issue is, the template syntax. That's why I am trying to integrate it with React, but I am struggling to figure out how to use Vite for development and production, but getting served from the Django server so the views are cached with Redis. I guess I am trying somehow to reinvent Next.js concept of Incremental Static Generation but in Django. What I am trying to achieve is a website where pretty much all text, titles, descriptions, images, etc. will be retrieved from a Django model that the admin can change, but it will barely be changed in the first place, thus the use of Redis an caching the views. A SPA where the html is rendered first and then the text is retrieved from an API is the solution I am trying to get away from as that affects the SEO. It could be considered Server Side Rendering (returns html with already parsed data) but caching the view. Thank you in advance.