Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Не могу выставить правильную временную зону в Django [closed]
Я в самом начале изучения Django. Извиняюсь за глупы вопрос) Создал проект в самом начале не указал временную зону, добавил записи в базу данных и провел миграции. Как правильно исправить временную зону? Чтоб ранее добавленные записи выводились в нужной временной зоне. Пробовал изменить в settings настройку "UTC" на "UTC+6" выдает ошибку. Спасибо. TIME_ZONE = 'UTC' -
celery task received but not executed (eventlet, django)
I faced a problem that when running celery with eventlet and remote database (Redis) tasks come but are not executed, before that I used gevent and it worked correctly with both local and remote databases, but it does not have the ability to stop tasks, I tried all the options I found on the Internet and on StackOverflow, but none of them helped. I add my settings there Django settings: # settings.py CELERY_BROKER_URL = REDIS_CONN_URL + "0" CELERY_RESULT_BACKEND = REDIS_CONN_URL + "0" CELERY_WORKER_CONCURRENCY = 1000 Celery settings: import os import ssl from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SailAPI.settings") celery_app = Celery( "SailAPI", broker_use_ssl={"ssl_cert_reqs": ssl.CERT_REQUIRED, "ssl_ca_certs": ssl.get_default_verify_paths().cafile}, redis_backend_use_ssl={"ssl_cert_reqs": ssl.CERT_REQUIRED, "ssl_ca_certs": ssl.get_default_verify_paths().cafile}, ) celery_app.config_from_object("django.conf:settings", namespace="CELERY") celery_app.conf.update( enable_utc=True, timezone="UTC", worker_concurrency=8, worker_pool="eventlet", ) celery_app.conf.beat_schedule = { "update_user_status": { "task": "user_app.tasks.update_user_status", "schedule": crontab(hour="4", minute="0", day_of_week="sat"), } } celery_app.autodiscover_tasks() The problem is that tasks that are added to the queue are not executed. I use an eventlet (because it has the ability to stop tasks that are running) and when I run it locally (Windows) with a local database (redis) it works fine, accepts tasks, executes them, stops at the command, but when I threw the code on the server (Linux) and ran … -
text are going out of the container and it's appearing in just one line and goes out of the page
I am trying to add some texts to my project-details section using rich text uploading field in Django admin. There it should be in a paragraph as I have added them in my Django admin project description but it's showing a line and also it goes out of the container and, but it gives space on the left side of the container but not in the right side of container and it goes out of page 😥 here is my project-details.html page: {% extends "base.html" %} {% load static %} {% static "images" as baseUrl %} {% block title %}{{projectdetails.title}}{% endblock %} <!--header block --> {% block header %} <!-- Slider Start --> <section class="section about"> <div class="container">{{projectdetails.desc|safe}}</div> </section> <!--slider ends --> <!-- footer Start --> {% block footer %} <!--Essential Scripts --> {% block Scripts %} {% endblock %} {% endblock %} {% endblock %} here is my project.html page: {% extends "base.html" %} {% load static %} {% static "images" as baseUrl %} {% block title %}Project{% endblock %} <!--header block --> {% block header %} <!-- slider starts --> </div> <div class="typing"> <p class="type4"></p> </div> <!-- section portfolio start --> <section class="section box"> <div class="container"> <div class="row … -
Why is my form calling the wrong Django view?
The flow of my app is as follows: A file is submitted on the transcribe.html page first which then redirects to the transcibe-complete.html page where the user can click to beginning transcription. Why is the 'transcribeSubmit' view being called instead of the 'initiate_transcription' view when the user clicks the 'click to transcribe' button on the 'initiate_transcription' page? Each page has their own JS file to ensure that forms are submitted separately. html: (transcribe.html): <form method="post" action="{% url 'transcribeSubmit' %}" enctype="multipart/form-data" > {% csrf_token %} <label for="transcribe-file" class="transcribe-file-label">Choose audio/video file</label> <input id="transcribe-file" name="file" type="file" accept="audio/*, video/*" hidden> <button class="upload" id="transcribe-submit" type="submit" >Submit</button> </form> (transcribe-complete): <form method="post" action="{% url 'initiate_transcription' %}" enctype="multipart/form-data"> {% csrf_token %} <label for="output-lang--select-summary"></label> <select class="output-lang-select" id="output-lang--select-summary" name="audio_language"> <option value="detect">Detect language</option> <option value="zh">Chinese</option> <option value="en">English</option> <option value="es">Spanish</option> <option value="de">German</option> <option value="jp">Japanese</option> <option value="ko">Korean</option> <option value="ru">Russian</option> <option value="pt">Portugese</option> </select> </div> <div class="transcribe-output"> <button id="transcribe-button" type="submit">Click to Transcribe</button> </div> </form> JS: const form = document.querySelector('form'); form.addeventlistener('submit', function (event) { event.preventdefault(); const formdata = new formdata(form); const xhr = new xmlhttprequest(); xhr.open('post', form.getattribute('action'), true); xhr.onreadystatechange = function () { console.log("ready state: ", xhr.readystate); console.log("status: ", xhr.status); } xhr.responsetype = 'blob'; xhr.send(formdata); }); views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = … -
Render the Django REST Framework uploading system with an HTML script
I have developed a simple file-upload system using Django REST Framework using this tutorial How to upload files to AWS S3 with Django. Basically the system allows user to upload files to an AWS S3 bucket. This is what the users currently see: This is the following django project structure: DROPBOXER-MASTER | |--- dropboxer | |--- settings.py |--- urls.py |--- wsgi.py |--- uploader | |--- views.py |--- urls.py |--- serializers.py |--- models.py |--- apps.py |--- templates |--- index.html |--- manage.py |--- requirements.txt This is the dropboxer/urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include # new urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('rest_framework.urls')), # new path('', include('uploader.urls')), # new ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is the dropboxer/settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*****************************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
ERROR [internal] load metadata for docker.io/library/python:3.9-alpine3.13
I'm new to docker, trying to build a website by following a online course but i was struck with this error in the beginning itself FROM python:3.9-alpine3.13 LABEL maintainer="rohitgajula" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user Error is [+] Building 1.3s (4/4) FINISHED docker:desktop-linux => [internal] load .dockerignore 0.0s => => transferring context: 191B 0.0s => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 492B 0.0s => ERROR [internal] load metadata for docker.io/library/python:3.9-alpine3.13 1.3s => [auth] library/python:pull token for registry-1.docker.io 0.0s ------ > [internal] load metadata for docker.io/library/python:3.9-alpine3.13: ------ Dockerfile:1 -------------------- 1 | >>> FROM python:3.9-alpine3.13 2 | LABEL maintainer="rohitgajula" This is the error i'm getting i dont understand whats the error here. -
Django html href query last object pass id to url tag
I have a button in my base template that needs to direct to a form to edit the last object in my model. model: class Cast(models.Model): id = models.AutoField(db_column='Id') startdate = models.DateTimeField(db_column='StartDate') enddate = models.DateTimeField(db_column='EndDate') View: def castend(request, id): context ={} obj = get_object_or_404(Cast, id = id) form = EndCastForm(request.POST or None, instance = obj) if request.method == 'POST': cast=Cast.objects.last() if form.is_valid(): form.save() cast.refresh_from_db() cast.endcastcal() cast.save() return HttpResponseRedirect("/wwdb/casts/%i/castenddetail" % cast.pk) context["form"] = form return render(request, "wwdb/casts/castend.html", context) url path('casts/<id>/castend/', views.castend, name='castend'), base.py This if/else statement determines if the enddate field is populated, the Start Cast button is passed to the view. Else the End Cast button is passed to the view. The End Cast button requires an id argument passed to the url. <div class="top-button-container stickey-top"> {% if cast.objects.last.enddate %} <button type="button" class="btn btn-danger btn-lg btn-block"> <a class="nav-link" href="{% url 'caststart' %}">Start Cast</a> </button> {% else %} <button type="button" class="btn btn-danger btn-lg btn-block"> <a class="nav-link" href="{% url 'castend' %}">End Cast</a> </button> {% endif %} </div> Start cast form This form is how the user inputs most of the information for an entry. Once the form is submitted, the view redirects to the endcast form, using the cast object to pass … -
Best practice to set user to admin
I am currently thinking what would be the best procedure to set a user to admin on a webapp after they have subscribed. Briefly for information: On this website users can sign up for subscriptions that give them admin rights. The payment is done via PayPal. After users have paid successfully the backend (in my case Django) receives the Paypal webhook with all necessary information about which user should be set to admin. This works so far. Afterwards a confirmation mail is sent out automatically. The problem with the whole thing is that the authprovider in the frontend pulls information like the user role from the JWT tokens. When the access token is updated with the refresh token, it gets the information like user role from the refresh token (at least that's how it's handled in Django). This means that if users have subscribed to be admins, they already are according to the database, this information reaches the frontend only when you log out and then log in again. This doesn't seem to me to be the best solution. Also problematic is that the PayPal webhook takes a few seconds longer to arrive in my backend. That is, after purchase … -
is MERN is better then Django for remote jobs and for joining startups?
I am a university student and I have been working on Django projects from 8-9 months, and I have made like 7 projects and 1 is in progress for practicing and mastering Django, But one of my senior said to me, that getting Django remote jobs & freelancing is relative hard compare MERN stack so should switch to MERN stack? to get clarity so that I choose a right path. -
Send actual email to real recipient when developing Django app
I just wanna know if there is any way to send emails to someone, like my own email, in development in order to test the style and everything. Is there anything built-in in Django or any free SMTP service out there to help me with that? REMEMBER: I wanna get the email in my inbox not in console. -
Is it possible to split HTML view and Python back-end across different servers (IIS) in Django?
I have a Django application where I want to separate the HTML views and the Python back-end logic into two different servers for architectural and security reasons. Specifically, I want one server to handle all the HTML rendering and another server to handle the Python back-end logic like database queries, API calls, etc. Is it possible to do this while still leveraging Django's capabilities? If so, how can I achieve this split? If it is not doable, may you explain why ? Thank you in advance for your help. -
NoReverseMatch on Django URL when more than one present
I have a table with a list of data values on it. One of the columns contains a link to another page. Sometimes there could be one link, sometimes two and sometimes n. When there is only one link present the code works as expected, the pattern matches and it goes to the expected page. Whenever there is more than one link present it fails. It will still build the url correctly, I can see the full correct url in my search bar on my browser but I get a NoReverseMatch error. Error: Exception Type: NoReverseMatch Exception Value: Reverse for 'thelink' with arguments '('64f75fake8012b456073fake', '')' not found. 1 pattern(s) tried: ['thelink/(?P<table>[^/]+)/(?P<row>[^/]+)\\Z'] urls.py path('thelink/<str:table>/<str:row>', views.thelink, name='thelink'), html where it works and breaks: <td> {% for table, row in data %} <a href="{% url 'thelink' table row %}" type="button" class="badge badge-info"> link </a>&nbsp; {% endfor %} </td> Generated HTML from the html code: Working: <a href="/thelink/64f75fake8012b456073fake/64f75be82fakeb456073fake" type="button" class="badge badge-info">link</a> Not Working: <a href="/thelink/64f75fake8012b456073fake/64f75be82fakeb45603fake1" type="button" class="badge badge-info">link</a> <a href="/thelink/64f75fake8012b456073fake/64f75be82fakeb45603fake2" type="button" class="badge badge-info">link</a> <a href="/thelink/64f75fake8012b456073fake/64f75be82fakeb45603fake3" type="button" class="badge badge-info">link</a> Note: I did alter the ids and links but you can assume those are correct. I have also tried looking at these solution(s): sol1, sol2 -
Django form in template
I was trying to build a form that make the user able to upload a picture from the website to Media\Images folder. i try this but it dosent work models.py from django.db import models # Create your models here. class imgUpscalling(models.Model): Image = models.ImageField(upload_to='images/') forms.py from django import forms from .models import imgUpscalling class ImageForm(forms.ModelForm): class Meta: model = imgUpscalling fields = ('Image',) views.py def img_upscaler(request): context = {'from': ImageForm()} return render(request, "upsc_main.html",context) template.html <h1>Image Upscaler & Enhanced Resolution</h1> <h2>Select the Image</h2> <form method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> can you notify me with the mistakes i did in the code? because the form is not shown in the template. thanks a lot in advance -
How do I properly set PYTHONPATH when invoking the Django Python shell?
I'm using Python 3.9.9 for a Django 3 project. I would like to invoke my Python shell, via "python3 manage.py shell", so I have set these variables ... $ echo $PYTHONSTARTUP /home/myuser/cbapp/shell_startup.py $ echo $PYTHONPATH/myuser /home/myuser/cbapp/ My startup script is very simple ... $ cat /home/myuser/cbapp/shell_startup.py from cbapp.services import * from cbapp.models import * However, when I change to my project directory, activate my virtual environment, and attempt to invoke the shell, I get these errors complaining about not being able to find Django ... $ cd /home/myuser/cbapp $ ./venv/bin/activate $ python3 manage.py shell Traceback (most recent call last): File "/home/myuser/cbapp/manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/myuser/cbapp/manage.py", line 21, in <module> main() File "/home/myuser/cbapp/manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? However, Django has already been installed in my virtual environment ... $ ls /home/myuser/cbapp/venv/lib/python3.9/site-packages/django/ apps conf core dispatch http __main__.py __pycache__ template test utils bin contrib db forms __init__.py middleware shortcuts.py … -
Sending Audio file from Django to Vue
I'm trying to send gtts generated audio file from Django to Vue via HttpResponse. Django's views.py: f = open('path/of/mp3/file', 'rb') response = HttpResponse() response.write(f.read()) response['Content-Type'] = 'audio/mp3' response['Content-Length'] = os.path.getsize('path/of/mp3/file') return response and when vue receives the response data, it is like the below: data: '��D�\x00\x11C\x19�\x01F(\x00\x00\x04 �&N�""""���ޓ�������\x7F���B\x10���w�����…���_�F��1B��H���\x16LAME3.100�����������������������' # and so on I guess it is because the bytes have been converted to string over the transfer and I have to convert it back to the audio file. But no matter whether using blob or other suggested methods, I could not convert it to an mp3 file to be played in javascript. How could I achieve this? -
how to fix django login problems
I was working on django project but I could not login into my django app after successful registration(confirmed from admin side). I have added phone number field to registration page, help me fix the login code, i am new to programming help me out please my code looks like this: This is my view.py ````def register_view(request): """Registration view.""" if request.method == 'GET': # executed to render the registration page register_form = UserCreationForm() return render(request, 'netflix/register.html', locals()) else: # executed on registration form submission register_form = UserCreationForm(request.POST) if register_form.is_valid(): User.objects.create( first_name=request.POST.get('firstname'), last_name=request.POST.get('lastname'), email=request.POST.get('email'), phone=request.POST.get('phone'), username=request.POST.get('email'), password=make_password(request.POST.get('password')) ) return HttpResponseRedirect('/login') return render(request, 'netflix/register.html', locals()) def login_view(request): #Login view. if request.method == 'GET': # executed to render the login page login_form = LoginForm() return render(request, 'netflix/login.html', locals()) else: # get user credentials input username = request.POST['email'] password = request.POST['password'] # If the email provided by user exists and match the # password he provided, then we authenticate him. user = authenticate(username=username, password=password) if user is not None: # if the credentials are good, we login the user login(request, user) # then we redirect him to home page return HttpResponseRedirect('/logged_in') # if the credentials are wrong, we redirect him to login and let him … -
How to check Fullcalendar V5 Refetch Events Success / Failure
I was fetching events from the server dynamically for fullcalendar var calendar = new FullCalendar.Calendar(document.getElementById('calendar'), { themeSystem: "bootstrap5", businessHours: false, initialView: "dayGridMonth", editable: true, headerToolbar: { left: "title", center: "dayGridMonth,timeGridWeek,timeGridDay", right: "today prev,next", }, events: { url: '/api/lesson_plans/', method: 'GET', success: function () { eventsLoadSuccess = true; }, failure: function () { eventsLoadSuccess = false; notyf.error('There was an error while fetching plans.'); }, textColor: 'black' }, dateClick: function(plan) { var clickedDate = plan.date; var today = new Date(); // Today's date if (clickedDate >= today) { $('#addPlanModal input[name="start"]').val(moment(clickedDate.toISOString()).format('YYYY-MM-DD HH:mm:ss')); $('#addPlanModal').modal('show'); } }, eventClick: function (plan) { $.ajax({ method: 'GET', data: { plan_id: plan.event.id }, success: function(data) { if (data.form_html) { $('#ediPlanFormContainer').empty(); $('#ediPlanFormContainer').html(data.form_html); $('#editPlanForm #plan_id').val(plan.event.id); initDatePicker(["id_edit_start", "id_edit_end"]); $('#editPlanmodal').modal('show'); } else { notyf.error('Error While Fetching Plan Edit Form.'); console.error('No form HTML found in the response.'); } }, error: function(xhr, textStatus, errorThrown) { console.error('Error:', textStatus, errorThrown); } }); }, eventDrop: function(plan) { updateEvent(plan.event); }, }); calendar.render(); It works properly but on reload events I wanted to check if the reload was successful or not but the refetchevents function doesn't return anything so I was trying to implement my own way but I am stuck now I need some help. $('#reload_plans').click(function () { if … -
I have telegram api to get messages. I want to show all messages on a django web page
Using the code below I am able to get all messages AND THE parts of message ( youtube url ) that need to be shown on web page. It is now required to show this data on a django based web page. Question is where do I start. For data that is coming from telegram, how can it be shown directly on the web page. ? from telethon import TelegramClient, events, sync from telethon.tl.functions.messages import (GetHistoryRequest) from telethon.tl.types import MessageMediaWebPage, WebPage, WebPageEmpty client = TelegramClient(session_name, api_id, api_hash) client.start() channel_entity=client.get_entity(channel_username) posts = client(GetHistoryRequest( peer=channel_entity, limit=100, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) for message in client.iter_messages(chat, reverse=True): if type(message.media) == type(None): continue if not type(message.media) == MessageMediaWebPage: continue if type(message.media.webpage) == WebPageEmpty: continue if hasattr(message.media.webpage, 'display_url'): print('+++ display_url ', message.media.webpage.display_url) Can I call a for loop inside the views. Another concern is, every time the page loads it will query data from telegram. And this can take long time. Is their a way to cache data that comes from an api so that subsequent reads are coming from the cache. -
Problems with saving and editing cards, changed/added models and stopped saving/editing cards
Here's what the terminal gives out [03/Oct/2023 16:15:52] "GET /create/?csrfmiddlewaretoken=xgcCZx4x2RjaTeFT5Sn6OBqC3k9VZUBO69tG4zJMiNuVwne9NTX1LXpdRJqn03AZ&original_name=222&author=1&case_category=3&defendant=%D0%9F%D0%B5%D1%82%D1%80%D0%BE%D0%B2&article=200&sides_case=3&preliminary_hearing=20.09.2023 HTTP/1.1" 200 8459 Model class BusinessCard(models.Model): '''7. Модель карточки по делу''' original_name = models.CharField( unique=True, max_length=100, verbose_name='номер дела' ) author = models.ForeignKey( User, models.SET_NULL, blank=True, null=True, related_name='cards', verbose_name='Автор карточки' ) case_category = models.ForeignKey( Category, blank=True, null=True, on_delete=models.SET_NULL, related_name='cards', verbose_name='Категория дела' ) defendant = models.CharField( max_length=150, verbose_name='подсудимый' ) under_arrest = models.BooleanField( verbose_name='под стражей' ) article = models.PositiveSmallIntegerField( verbose_name='Статья УК РФ' ) pub_date = models.DateTimeField( auto_now_add=True, verbose_name='Дата создания/изменения карточки' ) sides_case = models.ManyToManyField( SidesCase, verbose_name='Поля сторон по делу' ) preliminary_hearing = models.DateField( verbose_name='Дата предварительного слушания/(с/з)' ) class Meta: ordering = ('pub_date',) verbose_name = 'Карточка на дело' verbose_name_plural = 'карточка на дело' def __str__(self): return self.original_name views @login_required def card_create(request): '''Шаблон создание карточки''' template = 'create_card.html' form = CardForm(request.POST or None) if form.is_valid(): card = form.save(commit=False) card.author = request.user card.save() form = CardForm() return redirect('business_card:profile', request.user) return render(request, template, {'form': form}) @login_required def card_edit(request, post_id): '''Шаблон редактирования карточки''' card = get_object_or_404( BusinessCard.objects.select_related( 'case_category', 'author'), id=post_id ) if request.user != card.author: return redirect('business_card:business_card_detail', card.pk) form = CardForm(request.POST or None, instance=card) if form.is_valid(): form.save() return redirect('business_card:business_card_detail', card.pk) form = CardForm(instance=card) context = { 'form': form, 'is_edit': True, 'card': card, } return render(request, 'create_card.html', context) forms … -
The most recent rows in for each type/agent in Django
I have a table with lots of data. This table is written by some scripts. It works like a "check in", where each agent is checking in in some period of time. It looks like below. id agent status timestamp 1 tom ok 2023-03-16 12:27:03 2 jeff degraded 2023-08-31 00:01:13 100 tom ok 2023-10-03 12:00:00 101 jeff ok 2023-10-03 11:59:00 I'd like to pick the most fresh line per each agent. So in above example I'd like to get row 100 and 101. I tried many different ways but still not getting what I want. I use MySQL, so distinct is not for me this time. On one hand there is a way to make distinct values per agent, like below: AgentCheckin.objects.all().values('agent').distinct() But it's just a name of an agent. I need to get whole query set with all the information. I think this kind of use case should be somehow common in multiple web apps, but looking here is SO, it's not that common with ultimate answer. -
i am getting "OperationalError at /admin/login/" no such table: auth_user"post docker container deployment
I have created a Django project locally(on a EC2 instance),it was running successfully without any issues. I was getting this error at first, but, then i fixed it using "python manage.py migrate". i containerized it and then pushed the same on the docker hub. i pulled the same image on the another ec2 instance and executed the docker run command. The page got hosted on the current ec2 instance, then, I entered the username and password, then, i got this error. -
How to convert large queryset into dataframes in optimized way?
A django queryset of more than 5 lakhs records when converting into dataframes is getting into OutOfMemory issue. query_data is returning around 6 lakh rows but pandas is unable to process this much data and got stuck. How can we optimize or prevent this. query_data = MyObjects.objects.filter().values() df = pd.DataFrame.from_records(query_data) -
I have python django backend for webscarpping project. As input i give the website name and it scrapes data. But it takes too long time. How to scale?
In my project for 10 websites on 20000 records. It takes too much time to scrape. I have introduced multi-threading for the same. But still i see lot of time consumption. Is there a way i can scale my servers and make it faster ? Currently using multi-threading. But want to know how to scale servers and resolve issue. -
My Fullstack app is having issues after being deployed with Digital Ocean
So I developed fullstack application which has Django for backend and React for frontend. I am using Digital Ocean as host for my Django project and Railway for my React project. Locally everything works perfectlly but once I deployed it, thats where it started giving some errors. I am new to DevOps and deploying projects in general so bear with me. I checked my deploy loggs and everything seems to be in order, my url is also correct, which points to my digital ocean server app and works fine I tested it with postman. To give you an example of the issue , user creates a message and then after its done it redirects him to the home page. Instead of seeing the message on home dashboard, its basically empty. Then when I navigate away and come back to home page message is there, but then when I do navigate away and come back again to home page message is gone. So I have this really weird error which I really dont understand why is it occouring. So I am turning to stackoverflow community for help. Could it be because of plan package that I have on digital ocean? Like … -
Django database function to extract week from date (if week starts on Saturday)
loads_of_dedicated_customers = Load.objects.filter(customer__is_dedicated=True).exclude(load_status='Cancelled').values('customer__name').annotate(year=ExtractYear('drop_date'), week=ExtractWeek('drop_date').annotate( loads_count=Count('id'), sum_revenue = Sum('billable_amount'), sum_miles = Sum('total_miles'), rate_per_mile = ExpressionWrapper(F('sum_revenue') / NullIf(F('sum_miles'), 0), output_field=DecimalField(max_digits=7, decimal_places=2)), ) I have this query that groups by year and week. However, I need the results by week where the week starts on Saturday. Is there a simple way to do this or should I create a week columns in the table and save it there? Thanks!