Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating Django Models Without Rounding off Decimal Fields
For now, when I save an amount like 5400.5789, it is being saved as 5400.58. However, I want it to be saved as 5400.57 only. I don't want to round off the decimal places. How can I achieve that? class PerTransaction(models.Model): amount = models.DecimalField(default=0, max_digits=10,decimal_places=2, verbose_name = "Transaction Amount") Database: PostgreSQL -
Optimising Gunicorn Configuration for High-Concurrency I/O-Intensive Tasks with Low CPU and Memory Usage
I'm currently managing a Django application hosted on a 16-core server. Despite having 25% maximum CPU and memory usage, performance starts to degrade at around 400 active connections according to Nginx statistics. Currently, we have 12 Gunicorn workers, which is lower than the recommended (2 * CPU) + 1. However, as per Gunicorn's documentation, 4-12 workers should handle hundreds to thousands of requests per second. Question about Worker Configuration: Has anyone successfully used a number of workers exceeding the 12 as mentioned, especially in scenarios with low CPU and memory usage? Any insights into optimal configurations for high-concurrency scenarios in such situations? Performance Optimization: Our application primarily involves I/O tasks. Despite optimizing database queries and having low CPU and memory usage, performance remains an issue. Would increasing the number of workers or introducing threads (summing up to (2 * CPU) + 1) be a viable solution for improving performance in I/O-bound scenarios with seemingly underutilized resources? This means setting workers to 33 if I use (2 * CPU) + 1, or maybe 10 workers with 3 threads? Additional Considerations: We are considering tweaking Gunicorn configurations, but want to ensure we're on the right track given the low CPU and memory … -
HTTP APIs vs Restful APIs
What is the major difference in HTTP and Restful API. How is each implemented? Which is better in which situation? And any other thing to be noted to understand the difference in a better way. I am learning DJANGO with DRF. And it is my first time working on Rest architecture. -
Django middleware is executed at every API call
I created a middleware to record the activity log for user login but it executes at every API call. The ActivityLog is to record the entries. Middleware.py class UserActivityMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Set a flag in the session to indicate that the user has been logged in during this session request.session['user_logged_in'] = request.session.get('user_logged_in', False) response = self.get_response(request) # Check if the user is authenticated, has just logged in, and hasn't been logged during this session if ( request.user.is_authenticated and request.user.last_login is not None and request.session.get('user_logged_in', False) is False and not request.path.startswith('/static/') and not request.path.startswith('/media/') ): print("reached middleware") print(f"User: {request.user.username}") print(f"Last Login: {request.user.last_login}") print(f"Session Flag: {request.session.get('user_logged_in')}") print(f"Request Path: {request.path}") # Log the user login activity ActivityLog.objects.create( user=request.user, action="Login", target_model="User", target_object_id=request.user.id, details=f"User {request.user.username} logged in at {timezone.now()}." ) # Set a flag in the session to indicate that the user has been logged in during this session request.session['user_logged_in'] = True return response What should I do to reduce it to a single execution i.e. when the user logs in? -
Django Autocomplete Light: multiple selection from List (not Model)
I know how to use DAL (Django Autocomplete Light) to allow a single selection, like in the tutorial: CHOICE_LIST = [ ['FR', 'France'], ['FJ', 'Fiji'], ['FI', 'Finland'], ['CH', 'Switzerland'] ] class CountryAutocompleteFromList(autocomplete.Select2ListView): def get_list(self): return CHOICE_LIST class CountryForm(forms.ModelForm): country = autocomplete.Select2ListChoiceField( choice_list=CHOICE_LIST, widget=autocomplete.ListSelect2(url='country-list-autocomplete') ) However, I can't find any lead in the documentation or DAL source code to implement multiple selection, e.g. to allow users to pick 2 countries or more. Has anyone a working example I could learn from? -
How do I modify the Django training project (poll voting system) so that it has a home page at the root of the domain?
mysite/urls.py (main app with a settings.py) from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('admin/', admin.site.urls), path("polls/", include("polls.urls")), path('', ?), ] polls/urls.py - Currently contains the following information. notice even though path("", ..) looks like "domainname.com/" root location, it is "domainname.com/polls/" is that became of the app_name = "polls" namespace?) How do I add a mapping for the root of the domain (domainname.com/) so I can add my own homepage? from django.urls import path from . import views app_name = "polls" # Namespace to url template tag can find correct url urlpatterns = [ # ex: /polls/ path("", views.index, name="index"), # ex: /polls/5/ path("<int:question_id>/", views.detail, name="detail"), # ex: /polls/5/results/ path("<int:question_id>/results/", views.results, name="results"), # ex: /polls/5/vote/ path("<int:question_id>/vote/", views.vote, name="vote"), ] I have noticed some github projects are mapping the home page like so videoapp/urls.py urlpatterns = [ path("admin/", admin.site.urls), path("", include("videos.urls")), ] And mapping them to the view like so videos/urls.py from django.urls import path from . import views # http://127.0.0.1:8000/ # http://127.0.0.1:8000/home # http://127.0.0.1:8000/videos # http://127.0.0.1:8000/videos/1 # http://127.0.0.1:8000/videos/video-1 urlpatterns =[ path("",views.home,name="home"), path("home",views.home), path("videos",views.videos,name="videos"), path("videos/<int:id>",views.videodetails,name="details"), ] However I cannot do this as it automatically is starting the url from 'polls/'. What is a … -
Complex Django Query Spanning Multiple Tables
Table set up for reference only: class CustomerInformation(Model): first_name = charfield() last_name = charfield() class CustomerCreditInformation(Model): customer = OneToOneField(CustomerInformation, on_delete=CASCADE) max_credit_amount = DecimalField( max_digits=10, decimal_places=2, verbose_name='Credit Amount') due_in = CharField(choices=PAYMENT_DUE_DATES, max_length=4, verbose_name='Payable before') Class Invoice(Model): financial_party = models.ForeignKey( CustomerInformation, on_delete=models.CASCADE, null=True, verbose_name="Submit Invoice To:") date_billed_original = models.DateField( verbose_name='Billed Date', editable=False, null=True) class InvoicePayment(models.Model, ListViewModelFunctions): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) amount = models.DecimalField( max_digits=12, decimal_places=2, verbose_name='Payment Amount') class Charges(models.Model, ListViewModelFunctions): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=12, decimal_places=2) Invoices could be created, but not billed, meaning charges may be created on invoices that have not been billed. Given the following table set up, is there a way to create a "single" query from the Customer table that accomplishes the following (listed in order of difficulty): Concat First/Last Name (simple concat here works no issues/already completed) Annotate the Customers Credit Max Amount (Simple annotate here works/already completed) Annotate outstanding charges for all billed invoices (the filter is what throws me off) Annotate The total outstanding based on the date billed being less than timezone.localdate() - timedelta(customercredit__due_in). The resulting query would return a data dict with: Name, Customer Credit Amount, Total Outstanding Invoices (billed to date), Total Outstanding Invoices from past due invoices only. … -
Django not picking up static files like css and js
my Django app failed to load static files and gave me a 404 file not found error while I'm sure that the files do exist there. And I'm pretty sure that it is looking for it in the right directory. I'm attaching the error screenshot along with my Django static settings and the code part of HTML where I call the static file. error screenshot app directory static file settings: STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')] STATIC_URL = '/static/' some CSS that I called in the HTML file (yes I did include load static): <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <linkhref="https://fonts.googleapis.com/css2family=Noto+Sans+JP:wght@100;300;400;700;900&display=swap" rel="stylesheet"> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'css/bootstrap-icons.css' %}" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/magnific-popup.css' %}" type="text/css"> <link href="{% static 'css/aos.css' %}" type="text/css" rel="stylesheet"> -
How to render in real-time the django model's field using django channels?
I already set up the connection between the server side which are the asgi.py, consumers, and routing, that is already listening to client side using javascript. But I don't know how to render out, in real time, the field in that one model to my javascript that'll will be shown in HTML. This is the JavaScript: var socket = new WebSocket(`ws://${window.location.host}/orders/`); socket.onmessage = function (e) { var data = JSON.parse(e.data); document.getElementById("testingMessage").innerText = data.message; }; This is the consumers.py so far: class OrderConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() await self.send(json.dumps({'message':"testing"})) async def disconnect(self, close_code): await self.disconnect() And this is the routing.py: from . import consumers from django.urls import path websocket_urlpatterns = [ path('time/', consumers.OrderConsumer.as_asgi()) ] This is the models.py model: class BillingAddress(models.Model): isComplete = ( ('NO', 'NO'), ('YES', 'YES'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) full_name = models.CharField(default='', null=True, max_length=1000) contact_number = models.CharField(default='', null=True, max_length=1000) full_address = models.CharField(default='', null=True, max_length=1000) message = models.CharField(default='', null=True, max_length=1000) total_price = models.CharField(default='', null=True, max_length=1000) is_complete = models.CharField(choices=isComplete, null=True, default='') def __str__(self): return self.full_name def save(self, *args, **kwargs): if self.full_name: self.slug = slugify(self.full_name) super(BillingAddress, self).save(*args, **kwargs) All I want to achieve is to render that one field from the model (full_name) through the HTML in real time. … -
Checking that model field is in url Django 4
My group project peeps and I have been stuck on this for a minute. We're making a travel web app and we have a destinations app and an attractions app. We want to check that the attraction.location is in the url so that it only displays that destinations attractions, otherwise it will show all attractions ever created, regardless of destination. We have tried multiple {% if ... in request.get_full_path %} and such and the tags we've tried are attraction.location and attraction.location.pk. Any advice would be so helpful. Here is the model and the attraction_list.html snipped that we are trying to put it in models.py class Attraction(models.Model): location = models.ForeignKey( Destination, on_delete=models.CASCADE, ) name = models.CharField(primary_key=True, max_length=255) description = models.TextField(blank=False) address = models.TextField() rating = models.IntegerField( blank=False, validators=[MaxValueValidator(5), MinValueValidator(1)] ) tags = models.TextField() numberReviews = models.IntegerField(default=1) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.name def get_absolute_url(self): return reverse("attraction_detail", kwargs={"pk": self.pk}) attraction_list.html {% for attraction in attraction_list %} {# trying to use if in statement to check if attraction.location is in the full path #} <div class="card"> <div class="card-header"> <span class="fw-bold"> <a href="{{ attraction.get_absolute_url }}">{{ attraction.name }}</a> </span> &middot; <span class="text-muted">by {{ attraction.author }} | {{ attraction.date … -
Json nested object array data request post method in Django
My JSON nested object array Input: { "rawdata": [ { "type": "Host_HostParameter", "cmdbid": "CMDB3248972067", "name": "hostname", "product": "hostproduct", "modified_at": "2023-12-11T11:59:34", "modified_by": "person_name", "assetinfo": { "description": ["description1","description2"], "status": ["Deployed"] } } ] } In Django models.py from django.db import models from django.core.validators import RegexValidator # Create your models here. class Host(models.Model): cmdbid = models.CharField(primary_key=True, max_length=15, validators=[RegexValidator('^CMDB[0-9]{11}','invalid CMDB ID')]) name = models.CharField(max_length=80) ## by default blank=False, null=False product = models.CharField(max_length=50) modified_at = models.DateTimeField() modified_by = models.CharField(max_length=50) class HostParameter(models.Model): fk = models.ForeignKey(Host, on_delete=models.CASCADE) ##fk is value cmdbid parameter_section = models.CharField(max_length=40) parameter = models.CharField(max_length=80) parameter_index = models.IntegerField() value = models.CharField(max_length=200, null=True) modified_at = models.DateTimeField() modified_by = models.CharField(max_length=50) In Django serializers.py from rest_framework import serializers from django.conf import settings from .models import Host,HostParameter """ ###Host### class HostSerializer(serializers.ModelSerializer): class Meta: model = Host fields = "__all__" ###HostParameter### class HostParameterSerializer(serializers.ModelSerializer): class Meta: model = HostParameter fields = "__all__" In Django views.py #####Host#### class HostViewFilter(FilterSet): """ Filter for Host """ class Meta: model = Host fields = '__all__' class HostView(viewsets.ModelViewSet): """ GET... Will list all available Host POST... Will create a new Instance parameters entry PUT... Will update a existing Instance parameters entry """ permission_classes = [DjangoModelPermissions] queryset = Host.objects.all() serializer_class = HostSerializer filter_class = HostViewFilter http_method_names = … -
Django-htmx: Understanding trigger_client_event from the django_htmx module
The other day someone suggested me to start using the django_htmx module to boost my htmx experience in the framework. One of the functionalities I'm more interested on is the trigger_client_event response modifier that seems to be able to trigger an event in the client. But I can't get it to work and the documentation offers no example of the client side code. Here's the code I'm using in the back-end and the client: from django.views import View from django_htmx.http import retarget, reswap, trigger_client_event class HxFormValidationMixin(View): hx_retarget = 'this' hx_reswap = 'innerHTML' hx_event = '' def form_invalid(self, form): response = super().form_invalid(form) return reswap(retarget(response, self.hx_retarget), self.hx_reswap) def form_valid(self, form): response = super().form_valid(form) return trigger_client_event(response, self.hx_event, {}) document.addEventListener('modal-hide', () => { document.querySelector('#assistantStudentModal').modal('hide'); }); Sadly the event is not being handled. As a note, the first code is a Mixin meant to be reused, in the view were I use it the hx_event is set to 'modal-hide'. Also, I guarantee that the #assistantStudentModal exists and its visible when the event should ocurr. What I'm doing wrong? Someone knows how to catch the event in the client? -
Django Function after action decorator is being ignored
I have this View in django and when I do the post request it ignores the logic in my function completely and will do a post and then return the object, I am wondering how I can have it follow my logic from django.utils.translation import ugettext_lazy as _ from django_filters.rest_framework import DjangoFilterBackend from rest_framework import mixins, serializers, viewsets from rest_framework.viewsets import ModelViewSet from apps.units.models import Unit from apps.api.mixins import DestroyModelMixin from apps.api.v1.decorators import action from apps.leads.models import Leads from .serializers import LeadSerializer from apps.api.v1.units.serializers import UnitSerializer class LeadsViewSet( mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.UpdateModelMixin, DestroyModelMixin, ): serializer_class = LeadSerializer queryset = Leads.objects.all() @action(methods=["POST"], detail=False,) def create_lead(self, request, pk=None, *args, **kwargs): try: date = request.body.get("date") user_id = request.body.get("user_id") unit_id = request.body.get("unit_id") existing_lead = self.queryset.filter(user_id=user_id, unit_id=unit_id).exists() if existing_lead: raise serializers.ValidationError(_("Lead already exists")) Leads.objects.create( user_id=user_id, unit_id=unit_id, date=date ) return ({"message":"Lead Created Succesfully"}) except Exception as e: raise serializers.ValidationError(_("Lead not created")) -
How to add translation support to Django constants?
I have a Django application with some dictionaries defined in constants.py. The values in the dictionary represent user-readable labels, and I want to add translation support, so Django i18n feature than auto-translate them based on locale. So I added to the top of my constants.py: from django.utils.translation import gettext_lazy as _ and then applied it like: { "code": _("some name to be translated"), .... } That seems to have worked somewhat, put I'm running into problems with Celery and multi-processing support, or anything that tries to import my models in anything but the most vanilla manner. Specifically, when trying to do any kind of multi-processing, Django now throws the error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. which is itself caused by a different error: django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time. and the traceback for that starts at my use of gettext_lazy in constants.py. So clearly, something I'm doing is not copacetic. Is there a best practice to applying translation support to constants in Django? -
Django - Left join parent and child tables?
I am new to Django. I am trying to figure out how to do a left join with the least number of database queries. I have searched stackoverflow and have spend days trying to figure this out. I have looked into using .select_related, I have tried a raw query and tried to see if it could be done with Q, but I still cannot figure this out. I would like to retrieve all States and linked Cities if any listed, Models.py class State(models.Model): name = models.CharField(max_length=25) abbreviation = models.CharField(max_length=2) def __str__(self): return str(self.id) class City(models.Model): name = models.CharField(max_length=25) population = models.IntegerField() state = models.ForeignKey(State, related_name="cities", on_delete=models.CASCADE) def __str__(self): return str(self.id) State Table ID Name Abbreviation 1 Texas TX 2 California CA 3 Illinois IL City Table ID Name Population State 1 Los Angeles 3769485 2 2 Dallas 1259404 1 3 Houston 2264876 1 Desired result |-------------- State -------------|----------------- City -------------------| ID Name Abbreviation ID Name Population State 1 Texas TX 2 Dallas 1259404 1 1 Texas TX 3 Houston 2264876 1 2 California CA 1 Los Angeles 3769485 2 3 Illinois IL Problem 1 (Using .select_related): cities_states = City.objects.all().select_related('state').order_by('state_id') Using .select_related does not give me any States (e.g. Illinois) that … -
Don't set language cookie in Django
We're trying to avoid setting the Django language cookie, as this is the only cookie our site uses, and we want to avoid the legal liability of setting cookies. But I can't seem to find a way to prevent Django from setting this cookie. -
code=H14 desc="No web processes running" method=GET path="/"
im deployed my app Django in Heroku but, the application not works, it show me that error, this is my repo https://github.com/zlcosio21/MoralGamesWeb the code of the application, the files enter image description here I tried changing the procfile and it doesn't work either. -
Does docker compose up -d --build clear db?
I am using a docker compose for my django app and postgres db. when I have a new migration docker compose up -d --build clears my data in db. I want to know what is wrong? --build may clear ? my yaml file: version: "3.9" services: db: image: postgis/postgis:14-3.2 volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=db - POSTGRES_USER=user - POSTGRES_PASSWORD=123456 ports: - "5434:5432" web: restart: always build: . command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "7000:8000" environment: - POSTGRES_NAME=db - POSTGRES_USER=user - POSTGRES_PASSWORD=123456 - UPLOAD_LOCATION_MEDIA=/srv/app/cdn/media - UPLOAD_LOCATION_IMAGE=/srv/app/cdn/image depends_on: - db -
( AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
I have this view in my django project class OrdersGranularity(generics.ListAPIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] serializer_class = GetOrdersSerializer def get(self, request, *args, **kwargs): granularity = self.request.query_params.get('granularity', 'day') if granularity == 'month': return self.get_orders_by_month() else: return self.get_orders_by_day() def get_orders_by_day(self): start_date_str = self.request.query_params.get('start_date') end_date_str = self.request.query_params.get('end_date') operator_pk = self.request.query_params.get('pk') statuses = self.request.query_params.get('status') queryset = Order.objects.all().order_by('-created_at') if start_date_str and end_date_str: try: start_date = datetime.strptime(start_date_str, "%Y-%m-%d").date() end_date = datetime.strptime(end_date_str, "%Y-%m-%d").date() queryset = queryset.filter(created_at__date__range=[start_date, end_date]) except ValueError: return Response({'error': 'Invalid date format'}, status=status.HTTP_400_BAD_REQUEST) if operator_pk and operator_pk.lower() != 'none': queryset = queryset.filter(operator=operator_pk) if statuses: statuses_list = statuses.split(',') queryset = queryset.filter(status__in=statuses_list) serializer = self.get_serializer(queryset, many=True) return Response({'results': serializer.data}) # Provide a simple structure def get_orders_by_month(self): start_date_str = self.request.query_params.get('start_date') end_date_str = self.request.query_params.get('end_date') operator_pk = self.request.query_params.get('pk') statuses = self.request.query_params.get('status') queryset = Order.objects.all() if start_date_str and end_date_str: try: start_date = datetime.strptime(start_date_str, "%Y-%m-%d").date() end_date = datetime.strptime(end_date_str, "%Y-%m-%d").date() queryset = queryset.filter(created_at__date__range=[start_date, end_date]) except ValueError: return Response({'error': 'Invalid date format'}, status=status.HTTP_400_BAD_REQUEST) if operator_pk and operator_pk.lower() != 'none': queryset = queryset.filter(operator=operator_pk) if statuses: statuses_list = statuses.split(',') queryset = queryset.filter(status__in=statuses_list) queryset = queryset.annotate( month=TruncMonth('created_at') ).values('month').order_by('month') serializer = self.get_serializer(queryset, many=True) if not serializer.data: return Response({'results': []}) return Response({'results': serializer.data}) when I send request to this endpoint like this http://localhost:8000/dashboard/OrdersGranularity/?granularity=day&start_date=2023-01-01&end_date=2023-12-31&status=done it works but when I … -
Choose a directory from user pc with django
I'm developing a django application (my first time using it) where I need to store a user directory on the database, for that I've extended the user model to add one charfield: from django.db import models from django.contrib.auth.models import User class Directory(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) xml_directory = models.CharField() That directory will be later used to iterate between its files. My problem now is that I cant find how to make the "Alterar" button to open a dialog box for the user to choose the directory. Does anyone have an idea of how I can achieve that? <!DOCTYPE html> {% extends 'base.html' %} {% block title %}XML{% endblock title %} {% block pagename %}Processar XML{% endblock %} {% block content %} <form action="{% url "save_directory" %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="xml_directory">Local dos Arquivos XML</label> <input class="form-control col-6" readonly type="text" id="xml_directory" name="xml_directory" placeholder="{{diretorio_xml}}"></input> <button class="btn btn-primary" >Alterar</button> <button class="btn btn-success" type="submit">Salvar</button> </div> </form> {% endblock %} </html> -
Django admin redirect issue (unintended redirect to '.../?e=1')
I'm trying to write a simple calendar app called 'cal' in django and I modify the event (model) registration for visualize the calendar also in the changelist_view (/admin/cal/event/). I wrote two functions (prev_month and next_month) that return a url with two parameters with the month and the year ('?month={month}&year={year}') to be displayed. When i go to this url, in server side, the page is rendered, but instead of sending the HTML it redirects to this URL /admin/cal/event/?e=1 and the month doesn't change. #admin.py @admin.register(Event) class EventAdmin(admin.ModelAdmin): def formatted_date(self, obj): return obj.event_date.strftime("%Y-%m-%d") formatted_date.short_description = 'Formatted Date' def changelist_view(self, request, extra_context=None): if extra_context is None: extra_context = {} year = int(request.GET.get('year', datetime.today().year)) month = int(request.GET.get('month', datetime.today().month)) d = date(year, month, day=1) cal = CalendarAdmin(d.year, d.month) html_cal = cal.formatmonth(withyear=True) extra_context['calendar'] = mark_safe(html_cal) extra_context['prev_month'] = prev_month(d) extra_context['next_month'] = next_month(d) return super().changelist_view(request, extra_context=extra_context) def prev_month(d): first = d.replace(day=1) prev_month = first - timedelta(days=1) month = str(prev_month.month) year = str(prev_month.year) return f'month={month}&year={year}' def next_month(d): days_in_month = calendar.monthrange(d.year, d.month)[1] last = d.replace(day=days_in_month) next_month = last + timedelta(days=1) month = str(next_month.month) year = str(next_month.year) return f'month={month}&year={year}' CalendarAdmin is a simple class to generate a calendar. I've tried everything, I modify the CalendarAdmin class, the EventAdmin class, the deafault … -
Unable to import oauth2_provider.contrib.rest_framework in view ,after installing django-oauth-toolkit djangorestframework
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', 'rest_framework', 'corsheaders', 'oauth2_provider', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ) } Please help to fix the issue ,as I unable to use from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope in my view -
Using multiple variable in a Django HTML page?
Essentially I need to pass a few variables into the same HTML page in Django, yet I can only seem to register one. Here is the View for the variable I want to use: @login_required def dtasks_24(request): usern = str(request.user) today = datetime.now().date() tomorrow = today + timedelta(days=1) tasks_due_tomorrow = Task.objects.filter(assigned_members__username="@pjj",due_date__in=[today, tomorrow]) dtasks_24 = tasks_due_tomorrow .count() return render(request, 'dashboard.html', {'dtasks_24': dtasks_24}) Here is how I am using it in the dashboard.HTML file: {{ dtasks_24 }} Here are my URLs: path('dashboard/', views.dashboard, name='dashboard'), path('dashboard/', views.dtasks_24, name='dtasks_24'), the variable dashboard work but dtasks_24 does not, I do not have a HTML file for dtasks_24. Thank you for any help -
Celery Flower not sending task status from API call
For a very long time we'd been using Celery and flower to handle tasks and have a process that starts these tasks with a call to a flower endpoint. Like so http://flower.com/api/task/send-task/task_name This used to give back both a task-id and a state value (specifically Pending). After upgrading from Celery 4.3.0 --> 5.3.4 and Flower 0.9.2 --> 1.2.0 we no longer get that state value back. This is being done in conjunction with django btw on python 3.8. Everything else in the process works fine, tasks are executed and run normally and the state is properly reported in the celery dashboard. It's just that this initial call to the API is missing this state value. Based on the code presented in the flower git repo it looked like the send-task would look for a backend initialized for the result, otherwise it won't attach the state. However our backend appears to be initialized without issue, as both the logs confirm the connection as well as the db having up to date records of task executions. Here is the celery config from the settings.py CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 57600} CELERYD_PREFETCH_MULTIPLIER = 1 CELERYD_TASK_TIME_LIMIT = 57600 CELERY_ACKS_LATE = … -
Deep Learning Model calling through FAST API
Is it possible to call a deep learning model which is working on several GBs of data to be called through an api which is made by Fast API? Or would DjangoREST or Flask be a better approach?