Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to change django crispy forms login error?
How can I change the error that django crispy forms displays when a user fails to enter username and password? This is the image that currently appears to me when I go to make a wrong login, I would like to replace the internal writing and in addition I would like to center it This is my login view This is forms.py file: from django import forms from django.contrib.auth.forms import UserCreationForm from .models import MyUser ######### FORM PER LA REGISTRAZIONE DELL'UTENTE FINALE ######### class FormRegistrazione(UserCreationForm): username = forms.CharField(max_length=30, label="Nome Utente", required=True, widget=forms.TextInput(attrs={'placeholder': 'Pablitos123', 'class': 'text-left'})) first_name = forms.CharField(max_length=30, label="Nome", required=True, widget=forms.TextInput(attrs={'placeholder': 'Mario', 'class': 'text-left'})) last_name = forms.CharField(max_length=30, label="Cognome", required=True, widget=forms.TextInput(attrs={'placeholder': 'Rossi', 'class': 'text-left'})) email = forms.CharField(max_length=30, required=True, widget=forms.EmailInput(attrs={'placeholder': 'esempio@esempio.it', 'class': 'text-left'})) password1 = forms.CharField(max_length=30, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Inserisci la tua password', 'class': 'text-left'})) password2 = forms.CharField(max_length=30, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Inserisci nuovamente la tua password', 'class': 'text-left'})) indirizzo = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': 'Via/Piazza Roma, 25', 'class': 'text-left'})) citta = forms.CharField(max_length=50, label="Città", required=True, widget=forms.TextInput(attrs={'placeholder': 'Roma', 'class': 'text-left'})) CAP = forms.CharField(max_length=5, label="CAP", required=True, widget=forms.TextInput(attrs={'placeholder': '56123', 'class': 'text-left'})) ######### FUNZIONE PER CANCELLARE GLI help_text DAL FORM ######### def __init__(self, *args, **kwargs): super(FormRegistrazione, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None ######### CAMPI DEL … -
Sort By Descending Date Django
models.py class Record(models.Model): date = models.DateTimeField() .... class Balance(models.Model): record = models.ForeignKey(Record) .... views.py balances = Balance.objects.filter(record__date__week=current_week).order_by("-record") this will order the balance entries based on when the records were created not on the date from Record. How can I sort these queries for Balance based on Record Date. -
Django dynamic creation of table in database
I'm trying to find a way to dynamically create table in database (SQLite3). What I'm trying to do is to get file from user and based on rows in file create table with the same amount of columns. Everything I found is from 6-10 years so it doesn't work anymore. -
Generic Formset with M2M Field not saving Entry correctly
After a long struggle I found out how to design my code but it is still faulty. The model Form is has a (Sub)Formset that is created over modelformset_factory. SinglePrescriptionFormset = modelformset_factory( PrescriptionLine, form=PrescriptionLineForm, fields='__all__', extra=0, can_delete=True) The model Form itself is as follows: class PrescriptionForm(forms.ModelForm): class Meta: model = Prescription exclude = ['handed_out', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('patient'), Field('note'), HTML('<hr class="style2">'), Fieldset('Drugs', Formset('line_prescription')), HTML('<hr class="style1">'), ButtonHolder(Submit('submit', 'save')), ) ) def clean(self, *args, **kwargs): return super().clean(*args, **kwargs) and the Create View is designed like this: class PrescriptionCreate(generic.CreateView): model = Prescription template_name = 'doc_aide/write_prescription4.html' form_class = PrescriptionForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.POST: context['line_prescription'] = SinglePrescriptionFormset( self.request.POST) else: context['line_prescription'] = SinglePrescriptionFormset() context['form'].fields['patient'].initial = Patient.objects.get( pk=self.kwargs['patient']) return context def form_valid(self, form): context = self.get_context_data() prescriptionlines = context['line_prescription'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if prescriptionlines.is_valid(): prescriptionlines.instance = self.object prescriptionlines.save() return super().form_valid(form) def form_invalid(self, form): print('Form invalid') print(form.errors) return super().form_invalid(form) def get_success_url(self): return reverse('doc_aide:prescription_detail', kwargs={'pk': self.object.pk}) The problem now is that when I save one prescription the subformset data is changed from previous saves. I need … -
Uploading multiple webcam images to Django servers
I am creating a form, which takes the following data from the user: 'name', 'email', 'mobile_no', 'photo', 'id_proof'. Out of these, the simple text type data can easily be sent over the network to the server using POST method.However, the fields, photo and id_proof will be uploading images, and these images will be captured by the webcam of the user. A normal Form could be used, but the problem is that 1 page can have n number of such forms.Eg. if a page has 4 forms of such type, there will be 8 images to be uploaded. Hence, I can't even send the data over the server and then convert it to a file, as it will simply reduce the efficiency of the system as n increases.How can I convert the images into a file, and then send it over so that my Django application saves these images? I referred to this question: How to send captured webcam image and save to server via input field, but this provides solution only for sending a single image file and nothing else. -
How to solve 'NoneType' object has no attribute 'attname' in Django?
I have created a simple model in django models and I have migrated it to my sqllite database. I also created a form that inherits from my model and I have referenced all fields from the form. I am rendering the form to a template but there arises an exception 'NoneType' object has no attribute 'attname'. My code is as follows: models.py from django.db import models class Company(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) telephone = models.IntegerField() email = models.EmailField(max_length=50) date_created = models.DateTimeField(auto_now_add=True) def __init__(self): return self.name forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms import re from django.core.exceptions import ValidationError from .models import * class CustomerForm(forms.ModelForm): class Meta: model = Company fields = "__all__" Views.py from django.shortcuts import render from .forms import * from django.contrib.auth.models import Group def upload(request): form = CustomerForm() return render(request, 'registration/templates/upload.html', {'form':form}) urls.py from django.urls import path from . import views urlpatterns =[ path('upload/', views.upload, name='upload'), ] upload.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <form action="" method="post"> {% csrf_token %} {{ form}} </form> {% endblock %} Traceback Internal Server Error: /upload/ Traceback (most recent call last): File "C:\Users\SERU\Desktop\School Projects\Clearance_System\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response … -
Best practices for organizing and managing Django email templates
I'm building an app with over 20 different email notifications and I want to provide a nice way for the product team to verify the copy for each of these emails. I'm considering building two views, one to list all the email templates and another to display their content. I did some googling and have not yet found a better approach. Does there exist a better method for managing email templates in Django? -
Python or JavaScript? What is better for development a simple web game? [closed]
I am planing to develop a simple web game like this site for kids. A sample image of the aforementioned site. Which platfrom is better for developing such simple games? Python (Django, Flask, ...) or Javascript (Node.js, React, ...) ? My main parameter is ease to deploy (like free and cheap hosting solutions). -
Paginator url erorr in django
I am trying to make a paginator for my articles django page. but when I try to go to next pages I get an error ("page not found" and "No Article matches the given query.") and I don't know where I am doing wrong. I appreciate your help... ########## My views.py: from django.core.paginator import Paginator from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse, Http404 from .models import Article, Category # Create your views here. def home(request): context = { "articles": Article.objects.published() } return render(request, 'website/home.html', context) def detail(request, slug): context = { "article": get_object_or_404(Article.objects.published(), slug=slug) } return render(request, 'website/detail.html', context) def article(request, page=1): articles_list = Article.objects.published() paginator = Paginator(articles_list, 2) articles = paginator.get_page(page) context = { "articles": articles, "category": Category.objects.filter(status=True) } return render(request, 'website/article.html', context) def category(request, slug): cat = get_object_or_404(Category, slug=slug, status=True) context = { "category": cat.articles.filter(status='Published') } return render(request, 'website/category.html', context) ####### My urls.py from django.urls import path from .views import home, detail, article, category app_name = 'website' urlpatterns = [ path('', home, name='home'), path('article/<slug:slug>', detail, name='detail'), path('article', article, name='article'), path('article/<int:page>', article, name='article'), path('category/<slug:slug>', category, name='category') ] The related part of article.html page: <div class="blog-pagination"> <ul class="justify-content-center"> {% if articles.has_previous %} <li class="disabled"><a> href="{% url 'website:article' … -
KeyError at /shops/profile/mannu
Hello django developers !. I hope you all are fine.. :) Well here i want to get the shop_owner from shop detail view to the get context data function so i can count the total products of that particular shop.. models.py class ShopProfile(models.Model): shop_owner = models.OneToOneField(User, related_name='shop_profile', on_delete=models.CASCADE) shop_address = models.CharField(_("shop address"), max_length=255) views.py class ShopProfileDetailView(DetailView): model = ShopProfile template_name='shops/shop_profile.html' def get_context_data(self,*args, **kwargs): context = super(ShopProfileDetailView, self).get_context_data(*args, **kwargs) user = context['shop_owner'] #getting error here context["products_count"] = Product.objects.filter(product_owner=user).count() return context -
Having an attribute issue with my django project. I'm doing an ecommerce website with this code
I'm trying to fix this issue with my project and this error shows up and I can't seem to fix it. Is there a way to fix it? its saying that cannot import name 'Product' from 'store.models' [ -
How to do account activation through email using Djoser and React Native?
I am currently doing the authentication for my React Native based application using Djoser in the backend. However, for account activation Djoser sends a link containing the uid and a token. I want this link to open a page on my app while I obtain the uid and token from the link. I need to send the uid and token in the link as the body in my activation request from my react native app.Please suggest how that can be done. Any help would be appreciable because I'm stuck on this particular part. -
django: Make better looking multiple select menus in admin as displayed in auth>user tables
I have a User model that has these two fields: permissions = models.ManyToManyField(Permission) groups = models.ManyToManyField(Group) I register the model in the admin. When I view the user model that I made in the admin section I get a multiple select menu that looks like this. I would much prefer the much better-looking menu like the one that is in the auth user model that comes built into Django admin (looks like this) Any ideas on what I need to do to be able to access this sort of select menu? Thanks for your help. Django newb from PHP (finally) -
django access already existing table as you would a table created via a model
I am using the django-background-tasks packages to run a couple of tasks. This package creates two tables in my database (BackgroundTask & BackgroundTaskCompletedtask). I would like to create a page that reads the BackgroundTaskCompletedtask so I can check the status of of the background tasks. However I do not know how to access this database. For example, with a table I have created via model: class Set(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) code = models.CharField(max_length=64) ... I can used Set.objects.order_by('-releaseDate', 'name') to access that table. However when I try to use BackgroundTaskCompletedtask.objects... I can seem to import it in my views.py file. how to I access a table created via a package that doesn't exists in my model.py file. -
drf-yasg: Show custom pagination for ListAPIView in Swagger docs
I have following ListAPIView and custom pagination class in Django REST framework: views.py class pricetrend(generics.ListAPIView): queryset = Variants.objects.annotate(timestamp=TruncMonth('variantTimestamp')).values('timestamp').annotate(average_price=Avg('price')) serializer_class = PricetrendSerializer pagination_class = PricesPagination custom pagination class class PricesPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' def get_paginated_response(self, data): prices = [dict(item)['average_price'] for item in data] try: total_average_price = sum(prices)/ len(prices) except Exception as e: total_average_price = 0 return Response({ 'count': self.page.paginator.count, 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'total_average_price': round(total_average_price), 'results': data, }) Currently, I am trying to figure out how the custom pagination class can be shown in the Swagger API docs generated by drf-yasg. I already customized the PaginatorInspector from drf_yasg.inspectors but don't know where I need to put that in order to use it for the above mentioned ListAPIView. custom PaginatorInspector from drf_yasg.inspectors import PaginatorInspector from drf_yasg import openapi class LimitOffsetPaginatorInspectorClass(PaginatorInspector): def get_paginated_response(self, paginator, response_schema): """ :param BasePagination paginator: the paginator :param openapi.Schema response_schema: the response schema that must be paged. :rtype: openapi.Schema """ return openapi.Schema( type=openapi.TYPE_OBJECT, properties=OrderedDict(( ('count', openapi.Schema(type=openapi.TYPE_INTEGER) if has_count else None), ('next', openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI, x_nullable=True)), ('previous', openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI, x_nullable=True)), ('total_average_price', openapi.Schema(type=openapi.TYPE_INTEGER)), ('results', response_schema), )), required=['results'] ) As I am using other ListAPIViews with the default pagination class specified in settings.py, the custom pagination class should only be … -
Can't install psycopg2-binary or psycopg2 into virtualenv on Apple M1
I get the following trying to install either psycopg2-binary or psycopg2 on a fresh install of macOS Big Sur. Apple M1 Big Sur 11.2 Python 3.8.2 Pip 21.0.1 $ pip install psycopg2-binary --no-cache-dir Collecting psycopg2-binary Downloading psycopg2-binary-2.8.6.tar.gz (384 kB) |████████████████████████████████| 384 kB 25.7 MB/s ERROR: Command errored out with exit status 1: command: /Users/m1/company-app/api/.venv/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/9y/z49zz0951k3gkbnp0mb4f13w0000gn/T/pip-install-ccqum8r8/psycopg2-binary_08a234e704634109bb83b0b7c6b8ca28/setup.py'"'"'; __file__='"'"'/private/var/folders/9y/z49zz0951k3gkbnp0mb4f13w0000gn/T/pip-install-ccqum8r8/psycopg2-binary_08a234e704634109bb83b0b7c6b8ca28/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/9y/z49zz0951k3gkbnp0mb4f13w0000gn/T/pip-pip-egg-info-ybwazise cwd: /private/var/folders/9y/z49zz0951k3gkbnp0mb4f13w0000gn/T/pip-install-ccqum8r8/psycopg2-binary_08a234e704634109bb83b0b7c6b8ca28/ Complete output (23 lines): running egg_info creating /private/var/folders/9y/z49zz0951k3gkbnp0mb4f13w0000gn/T/pip-pip-egg-info-ybwazise/psycopg2_binary.egg-info writing /private/var/folders/9y/z49zz0951k3gkbnp0mb4f13w0000gn/T/pip-pip-egg-info-ybwazise/psycopg2_binary.egg-info/PKG-INFO writing dependency_links to /private/var/folders/9y/z49zz0951k3gkbnp0mb4f13w0000gn/T/pip-pip-egg-info-ybwazise/psycopg2_binary.egg-info/dependency_links.txt writing top-level names to /private/var/folders/9y/z49zz0951k3gkbnp0mb4f13w0000gn/T/pip-pip-egg-info-ybwazise/psycopg2_binary.egg-info/top_level.txt writing manifest file '/private/var/folders/9y/z49zz0951k3gkbnp0mb4f13w0000gn/T/pip-pip-egg-info-ybwazise/psycopg2_binary.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- WARNING: Discarding https://files.pythonhosted.org/packages/fc/51/0f2c6aec5c59e5640f507b59567f63b9d73a9317898810b4db311da32dfc/psycopg2-binary-2.8.6.tar.gz#sha256=11b9c0ebce097180129e422379b824ae21c8f2a6596b159c7659e2e5a00e1aa0 (from https://pypi.org/simple/psycopg2-binary/) (requires-python:>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I ran into the same issue with SYSTEM_VERSION_COMPAT=1 … -
how do you assign a foreign key to a boolean field in another table in django
hello i am trying to assign a foreign key to a boolean field in my User table which is called seller here is my code for my code of which is want to have a foreign key assigned to my seller field, which is a boolean field class MyMarketplaceManager(BaseUserManager): def create_user(self, business_name, foods, seller): if not business_name: raise ValueError("Users must have a email") if not seller: raise ValueError("Users must have a password") if not foods: raise ValueError("Sellers must have a menu") user = self.model( business_name=business_name, seller=seller, food_item=foods ) user.save(user=self.db) return user class Marketplace(models.Model): business_name = models.CharField(max_length=32, default="", primary_key=True) seller_id = models.ForeignKey(User, on_delete=models.CASCADE) foods = ArrayField(models.CharField(max_length=200), blank=True) objects = MyMarketplaceManager() the seller id field is what i want to assign the seller field to i have seen on another question which asks about a primary key which was this How to set foreign key to a field of another model? but it didn't have anything about other fields can anyone help? -
Reverse Match Arguments
Can someone please explain or direct me to the documentation on the best way to fix this Error? I have two apps in this project. django.urls.exceptions.NoReverseMatch: Reverse for 'proj_full' with arguments '('',)' not found. 1 pattern(s) tried: ['project\\/(?P<pk>[0-9]+)\\/$'] This is my View def CustomerDetailView(request, pk): customer = Customer.objects.get(id=pk) projects = customer.project_set.all() context = {'customer':customer, 'projects':projects} return render(request, 'customer/full.html', context) This is my Template <div class="card-body"> <table class="table-hover table bordered"> <thead> <tr> <th>Project Name</th> <th>Description</th> <th>Upload Date</th> <th></th> </tr> </thead> <tbody> <tr> {% for projects in projects %} <td>{{projects.projName}}</td> <td>{{projects.description}}</td> <td>{{projects.dateCreated}}</td> <td><a href="{% url 'proj_full' project.id %}" class="btn btn-default p-0">View</a></td> </tr> {% endfor %} </tbody> </table> </div> This is my Project App URL List from django.urls import path from . import views urlpatterns = [ path('list/', views.ProjectListView.as_view(), name='proj_list'), path('add/', views.ProjectCreateView.as_view(), name='proj_add'), path('edit/<int:pk>/', views.ProjectUpdateView.as_view(), name='proj_edit'), path('delete/<int:pk>/', views.ProjectDeleteView.as_view(), name='proj_delete'), path('<int:pk>/', views.ProjectDetailView, name='proj_full') ] This is my Customer App URL List from django.urls import path from . import views urlpatterns = [ path('list/', views.CustomerListView.as_view(), name='cust_list'), path('search/', views.CustomerSearchView.as_view(), name='cust_search'), path('add/', views.CustomerCreateView.as_view(), name='cust_add'), path('edit/<int:pk>/', views.CustomerUpdateView.as_view(), name='cust_edit'), path('delete/<int:pk>/', views.CustomerDeleteView.as_view(), name='cust_delete'), path('<int:pk>/', views.CustomerDetailView, name='cust_full'), ] -
How to mock googleapiclient in a Django test environment
I'm trying to mock googleapiclient.discovery in a django unittest, I looked at how at this post which shows how to mock googleapiclient.discovery in general, so I tried this: ... @mock.patch("myapp.views.googleapiclient.discovery") def test_get_instances(self, mock_discovery): mock_discovery.build.return_value.service.return_value.instances.return_value.aggregatedList.return_value = {# some mock values} ... This gave a "Module not found error", stating that "myapp.views" is not a package The views.py question is in the standard location for Django apps: mysite/myapp/views.py views.py: ... from googleapiclient import discovery def get_instances(proj_id, servicekey) service = discovery.build('compute','v1', credentials=generate_credentials(servicekey)) request = service.instances().aggregatedList(project=project_id) ... I'm new to mocking so any advice is warmly welcome -
Unable to find root cause of warning message indicated as [django.request:230]
The log file contains warnings about "Unauthorized" access to certain API URLs. The warning's indicator says "[django.request:230]", and I suppose it means the trigger is line 230 of a source code file related to django.request. However, I'm unfamiliar with Django and PyCharm IDE, so I couldn't find out exactly which file. I hope to find out the root cause of this warning message and address it. Any hints will be highly appreciated. Log events: [03/Feb/2021 09:54:07] WARNING [django.request:230] Unauthorized: /api/rest-auth/user/ [03/Feb/2021 09:54:07] WARNING [django.request:230] Unauthorized: /api/products/meta/debt/ [03/Feb/2021 09:54:07] WARNING [django.request:230] Unauthorized: /api/products/meta/reg/ -
Django: object has no attribute 'update'
I want to update first one record of the database. This result can be two or more results. This works. TelegramAppUserConfig.objects.filter(user=user).update(json="hoge") This should result just one result. But this doesn't work. Django: object has no attribute 'update' TelegramAppUserConfig.objects.filter(user=user).first().update(json="hoge") TelegramAppUserConfig.objects.filter(user=user)[0].update(json="hoge") How can I code for that? Thanks. -
Django rest framework router urls is not working
So, I have such viewset. class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() permission_classes = (IsAuthenticated, ) @action(detail=True, methods=['PUT']) def set_description(self, request, pk=None): profile = self.get_object() serializer = DescriptionSerializer(data=request.data) if serializer.is_valid(): profile.description = request.data['description'] profile.save() else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @action( detail=True, methods=['post'], serializer_class=ImageSerializer ) def add_image(self, request, pk=None): instance = self.get_object() serializer = self.get_serializer(instance, data=self.request.data) serializer.is_valid(raise_exception=True) image = serializer.save(profile=request.user.profile) image_id = image.id return Response(serializer.data, {'image_id': image_id}) @action( detail=True, methods=['delete'], serializer_class=ImageSerializer ) def delete_image(self, request, pk): instance = self.get_object() instance.delete() return JsonResponse(status=status.HTTP_200_OK) My urls.py: from django.urls import path, include from rest_framework.routers import DefaultRouter from . import views from . import viewsets app_name = 'profile_' router = DefaultRouter() router.register('', viewsets.ProfileViewSet) urlpatterns = [ path('', views.ProfileView.as_view(), name='profile'), ] urlpatterns += router.urls And finally there is a couple of available urls (showed by python3 manange show_urls) /profile/<pk>/add_image/ profile_.viewsets.ProfileViewSet profile_:profile-add-image /profile/<pk>/add_image\.<format>/ profile_.viewsets.ProfileViewSet profile_:profile-add-image /profile/<pk>/delete_image/ profile_.viewsets.ProfileViewSet profile_:profile-delete-image /profile/<pk>/delete_image\.<format>/ profile_.viewsets.ProfileViewSet profile_:profile-delete-image /profile/<pk>/set_description/ profile_.viewsets.ProfileViewSet profile_:profile-set-description /profile/<pk>/set_description\.<format>/ profile_.viewsets.ProfileViewSet profile_:profile-set-description I not copied all of them but you can see there is all paths I need provided by default router. So, I trying to change profile's description from JS this.update(`http://127.0.0.1:8000/profile/${this.user_id}/set_description/`, data, 'PUT') Update is a function which getting url, some king of data and a request method (And it works ok, because I … -
How can I optimise requests/second under peak load for Django, UWSGI and Kubernetes
We have an application that experiences some pretty short, sharp spikes - generally about 15-20mins long with a peak of 150-250 requests/second, but roughly an average of 50-100 requests/second over that time. p50 response times around 70ms (whereas p90 is around 450ms) The application is generally just serving models from a database/memcached cluster, but also sometimes makes requests to 3rd party APIs etc (tracking/Stripe etc). This is a Django application running with uwsgi, running on Kubernetes. I'll spare you the full uwsgi/kube settings, but the TLDR: # uwsgi master = true listen = 128 # Limited by Kubernetes workers = 2 # Limited by CPU cores (2) threads = 1 # Of course much more detail here that I can load test...but will leave it there to keep the question simple # kube Pods: 5-7 (horizontal autoscaling) If we assume 150ms average response time, I'd roughly calculate a total capacity of 93requests/second - somewhat short of our peak. In our logs we often get uWSGI listen queue of socket ... full logs, which makes sense. My question is...what are our options here to handle this spike? Limitations: It seems the 128 listen queue is determined by the kernal, and the … -
Optimize code of a function for a search filter in django with variable numbers of keywords - too much code, i'm a beginner
Hello great community, i'm learning django/python development, i'm training myself with development of a web app for asset inventory. i've made a search filter, to give result of (for example) assets belonging to a specific user, or belonging to a specific department, or belonging to a specific brand, model or category (computers, desks, ecc..) now (after a lot) i've done with multiple keyword search (for example) if somebody type in the search box the department and the category and obtain the relative results (for example all desk in a specific department, or all computer of a specific model in a specific department). i've made it in a "if" check form that split the keyword in single words, count it and apply progressive filtering on the results of the previous keys in sequence. but i'm not satisfact of my code, i think it's too much "hardcoded" and instead of creating an IF condition for each number of keyword (from 1 to 3) i wish like to code something that is not so dependent in the number of keyword, but is free. Here's the code of the view, i hope someone can give me the right direction. def SearchResults(request): query = request.GET.get('q') … -
How to display pdf from an HttpResponse in Django after jquery post request?
I am using xhtml2pdf to introduce pdf report downloads on my platform. The intention is to send a dictionary with some data via ajax to the view so that it triggers the render_to_pdf function in utils.py. The problem is that, although everything seems to be working, since the request works and the data is sent, the pdf is not generated. Any idea about this? Thank you in advance! views.py def ViewPDF(request, *args, **kwargs): if request.is_ajax(): print('ajax') else: print('NOT ajax') s_id = kwargs['pk'] customer = request.user search = searches_history.objects.get(id=s_id) product_id = search.product b = Products.objects.get(id=5) if product_id== b: print(b) search1 = ofac_lists.objects.filter(name__contains=search) context = {'id': customer, 'search_id' : s_id ,'nombre_buscado': search, 'results' : search1, 'date': search.date_created } pdf = render_to_pdf('core/reports/free_search.html', context) return HttpResponse(pdf, content_type='application/force-download') else: context = {'id': customer, 'nombre_buscado': search, 'date': search.date_created } pdf = render_to_pdf('core/reports/free_search.html', context) return HttpResponse(pdf, content_type='application/pdf') utils.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: # Force pdf download response = HttpResponse(result.getvalue(), content_type='application/pdf') response['Content-Disposition'] = 'inline; filename=" .pdf"' return response # view pdf in browser # return http.HttpResponse(result.getvalue(), mimetype='application/pdf', content_type='application/force-download') return HttpResponse('We had some errors %s ' % cgi.escape(html)) main.js var url = '/pdf/'+query['s_pk'] $.ajax({ …