Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Replace string in .html files with Django custom command
I need to export my django project to static files. I'm using django-distill. Everything works fine except hrefs in main folder directory. So I decided to replace them with custom command after files were generated. However after few attempts I don't know why this function doesn't work. For example if even when I print out soup it show me empty string. class Command(BaseCommand): help='change urls in each header to static version' def replace_urls(self): find_string_1 = 'href="/blog/"' find_string_2 = 'href="/contact/"' replace_string_1 = 'href="blog.html"' replace_string_2 = 'href="/contact.html"' exclude_dirs = ['media', 'static'] for (_, dirs, files) in os.walk(f'{settings.BASE_DIR}/staticpage/'): dirs[:] = [d for d in dirs if d not in exclude_dirs] for filepath in files: f = open(filepath, mode='r', encoding='utf-8') soup = BeautifulSoup(f, "lxml", from_encoding="utf-8") if find_string_1 in soup: soup.replace_with(replace_string_1) if find_string_2 in soup: soup.replace_with(replace_string_2) f.close() def handle(self, *args, **kwargs): try: self.replace_urls() self.stdout.write(self.style.SUCCESS(f'********** Command has been execute without any error **********')) -
Issue with displaying images in frontend
views.py: from PIL import Image img_list =os.listdir(final_path) frontend_images = [] for images in img_list: frontend_path = final_path+str(images) image = Image.open(frontend_path) frontend_images.append(image) print(frontend_images) return render(request,'images.html',{'images':frontend_images}) I am sending the images to the frontend for displaying in frontend images.html {% for img in images %} <img src='{{img}}'/> {% endfor %} Its not displayed in frontend is there other approach to retrieve images from directory and display it in frontend -
Cannot update a field in Django Rest framework
I have to update this 'completed' field in Rest API whenever required. when i go to the url, it is showing a createView but not update view. Also update is not working. How chould i change only 'completed' field to wither True or False whenever i requested a particular Url serializers.py class ToDoModelSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = [ 'content', 'completed', ] models.py class Todo(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.CharField(max_length=100) timestamp = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) def __str__(self): return self.content class Meta: ordering = ['timestamp'] views.py class UpdateCompleted(generics.UpdateAPIView): queryset = Todo.objects.all() serializer_class = ToDoModelSerializer permission_classes = (permissions.IsAuthenticated,) def update(self, request, *args, **kwargs): instance = self.get_object() instance.name = request.data.get("completed") instance.save() serializer = self.get_serializer(instance) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) -
Django - API Post Issue
Im working on a django project and I want to post data to an api. Here is the code: import pandas import requests excel_data_df = pandas.read_excel('workorders.xlsx') json_str = excel_data_df.to_json(orient='records', date_format='iso') // json_str = [{"id":null,"label":"Workorder 1","start":"2019-01-01T00:00:00.000Z","end":"2019-01-10T00:00:00.000Z","duration":9,"ctype":"bar"},{"id":null,"label":"Workorder 10","start":"2019-01-10T00:00:00.000Z","end":"2019-01-14T00:00:00.000Z","duration":4,"ctype":"bar"}] API_ENDPOINT = "http://127.0.0.1:8000/api/chart/data/" API_KEY = "dF8NbXRA.94Mj2xeXT3NZOtx1b575CvNvbs8JWo0D" source_code = json_str data = {'api_dev_key':API_KEY, 'api_option':'paste', 'api_paste_code':source_code, 'api_paste_format':'csv'} r = requests.post(url = API_ENDPOINT, data = data) I get this error: <h1>Error response</h1> <p>Error code: 405</p> <p>Message: Method Not Allowed.</p> <p>Error code explanation: 405 - Specified method is invalid for this resource.</p> Im using djangorestframework-api-key 1.4.1 to generate the API key. According to the documentation I have to add this to my settings.py: REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ "rest_framework_api_key.permissions.HasAPIKey", ] } which returns this error: <h1>Error response</h1> <p>Error code: 403</p> <p>Message: Forbidden.</p> <p>Error code explanation: 403 - Request forbidden -- authorization will not help.</p> -
Show ForeignKey in template with class based views
I have a class based DetailView with the model Property as the main model. That model has a foreign key relationship with the model PropertyImage where I store some images. I want to show all related images from PropertyImages in the template detail_view.html together with some details from Property. I know how to do it in a function based view and I tried a lot of things but I failed all the time. Maybe it's just some tiny thing but I don't get it to work. Here is my code: # models.py from django.db import models class Property(models.Model): title = models.CharField(max_length=140, default="Title",) description = models.TextField(max_length=2000) # ... and some more fields def __str__(self): return self.title class PropertyImage(models.Model): property = models.ForeignKey(Property, on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to='images/') figcaption = models.CharField(max_length=160) def __str__(self): return self.figcaption[:50] # views.py from django.views.generic import DetailView from .models import Property class PropertyDetailView(DetailView): model = Property template_name = 'property_detail.html' For quicker assessment look at the <!-- Here I'm stuck -->section: <!-- property_detail.html --> {% extends 'base.html' %} {% block content %} <div class="container"> <div class="property-entry"> <img src="{{ property.cover_image.url }}" alt="{{ property.title }}" class="img-fluid"> <h2>{{ property.title }}</h2> <p>Description: {{ property.description }}</p> <!-- Here I'm stuck --> {% for image in … -
Django - Keras - Memory stacks-up
I have three deep learning models running on AWS. When there's a call to access models, the memory gets stacked-up with each call without releasing when process ends. At one point, gets out of memory and throws exhaustion error from keras. What am i dealing with? Garbage collector? or the lazy_loader by tensorflow? or something that goes with Django? I have no clue what is happening. Thanks. -
How to have different permission classes for methods in DRF
I have a view similar to this: from django.http import HttpResponse from rest_framework import generics class MyView(generics.ListCreateAPIView): def get_queryset(self): # <view logic> return HttpResponse('result') def post(self, request): # <view logic x2> return HttpResponse('message_post_template') And I would like the GET request to have the permission class of IsAuthenticated and the POST request should have a permission class of HasAPIKey from Django REST Framework API Key. How can I do this? -
django template/views add-to-cart
I have problem, after pressing the 'add cart' button, it expects to add the product and its quantity to OrderProduct and Order. In templates / offers / cart I have no idea how to refer to this quantity and that after selecting it and pressing the 'Add to cart' button it adds the product to cart. Manually, this logic works in the Administrative Panel. offers/views.py def add_to_cart(request, product_id): product = get_object_or_404(Product, product_id=product_id) order_product, created = OrderProduct.objects.get_or_create( product=product, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # Check if the order item is in the order if order.products.filter(product__product_id=product.product_id).exists(): order_product.quantity += 1 order_product.save() else: order.products.add(order_product) else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.products.add(order_product) return redirect("offers:product", product_id=product_id) offers/urls.py urlpatterns = [ path('', views.index, name='products'), path('userproduct', views.userproduct, name='userproduct'), path('<int:product_id>', views.product, name='product'), path('<int:product_id>', views.add_to_cart, name='add-to-cart'), path('cart', views.cart, name='cart'), ] offers/models.py class Product(models.Model): product_name = models.CharField(max_length=100) category = models.CharField(max_length=50) weight = models.FloatField() description = models.TextField(blank=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.product_name def get_add_to_cart_url(self): return reverse("offers:add-to-cart", kwargs={ 'product_id': self.product_id }) class UserProduct(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product_name = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.FloatField() is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return str(self.user.username) … -
Python input filtered dynamically from another input [duplicate]
This question already has an answer here: How to get Interdependent dropdowns in django using Modelform and jquery? 2 answers I'm working on a Python project using Django. I need to build a form with multiples fields including one depending on another. To help the user, it includes an autocomplete system using autocomplete-light. The problem is the following : I need to filter the content of the second field according to the value of the first one (that the user has already filled). I kinda understand the way of doing it, by sending the value of the first one to the second one, but I don't know how to do it. Does anybody can help me please ? -
Updating one to one model using form in Django
I am very new to Python and Django and am stuck with this problem , which I think should be very simple to solve. model.py class UserDetails(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) billingAddress = AddressField(related_name='+',blank =True ) # Used django-address https://pypi.org/project/django-address/ shippingAddress = AddressField(related_name='+',blank =True) forms.py class AddressForm(forms.ModelForm): class Meta: model = UserDetails exclude = ['user'] views.py def address(request): form = AddressForm(request.POST or None) if request.method == 'POST' and form.is_valid(): zipCode = request.POST.get("ZipCode","") form = AddressForm(data=request.POST) detailForm = form.save(commit = False) detailForm.user = request.user baddressDict = {'raw':request.POST.get("billingAddress","")+", " + zipCode, 'postal_code': zipCode,} saddressDict = {'raw':request.POST.get("shippingAddress","")+", " + zipCode, 'postal_code': zipCode,} detailForm.billingAddress = baddressDict detailForm.shippingAddress = saddressDict detailForm.save() else: form = AddressForm() return render(request,'showcase/address.html',{'form': form}) What I am trying to do it update the shipping & Billing address for current user. The first time I am doing this it works but the second time it gives UNIQUE constraint failed: showcase_userdetails.user_id which obviously is cause it trying to add another row in the DB. How do i make sure it updates and not insert? Thanks, Gourav -
How to build a python-based auth microservice?
So, what I want to do is to build an app with microservice architecture. I'm going to write all the microservices using Python. I want to build a teaching platform, and I've already known which microservices I'm going to create. So, the application will consist of Teachers, Students, Booking, Notifications microservices. The question is, how to handle authorization with authentication? What I want to do is to create another microservice, which would handle all this auth stuff. But I want to be able to log in just once, and do not type any credentials when I would interact with other microservices. So, there are a few questions I've come up with: How to accomplish a goal of auth microservice, and which free services/libraries I may use for this. I want to handle auth on all my services, but log in just once. What is the most preferable way to write API Gateway? I have a pretty complicated business logic related to registration because students and teachers have a lot of differences. -
how to render django location field by id?
i have a model in django like this : ... class Post (models.Model) title = models.CharField(max_length=120) location = models.PointField(srid=4326, null=True, blank=True) objects = GeoManager() def __unicode__(self): return self.title def get_absoulute_url(self): return reverse("post_map", kwargs={ 'id':self.id }) ... and i want to render location place by id like this: ... path('post-map/<id>/map/',post_map,name='post_map') path('post-map/<id>/index/',home_page,name='post_map') ... an view.py: ... def map (request,id): name = serialize('geojson',get_objects_or_404(Post, id=id) return HttpResponse(name,content_type='json') def home_page(request): return render(request,'home_page.html') ... and home_page.html is: ... <!DOCTYPE html> <html> {% load static %} {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} <title> home </title> <style type="text/css"> #gis {width:80%; height:700px;} </style> <script type ="text/javascript" src="{% static 'js2/leaflet.ajax.js' %}" ></script> </head> <body> <h3>we are heroes!!<h3> <br> <script type="text/javascript"> function our_layers(map,options){ var datasets = new L.GeoJSON.AJAX("{% url 'post_map' %}",{ }); datasets.addTo(map); } </script> {% leaflet_map "gis" callback="window.our_layers" %} </body> </html> but i cant render it by id ,is there any way to solve this problem? i can save data and also can render all location to view map functiom with name = serialize('geojson',get_objects_or_404(Post, id=id) but i cant render in by each id for each post is there any way to solve it? -
How to query whole dataset from PostgreSQL using Django models and managers & render frontend with Ajax
I would like to fetch data from a PostgreSQL using Django models/managers and use this data to render my frontend furthermore. I have the following plain simple example where I just get the defined privatekey value in return but not the other information from the table. Estimated outcome: I would like to get all elements of a single row as one object. Models.py: from django.db import models import uuid # Create your models here. class AccountInformationManager(models.Manager): pass class AccountInformation(models.Model): version = models.CharField(max_length=20, blank=False) DID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) accountNumber = models.IntegerField(blank=False) broker = models.CharField(max_length=50, blank=False) leverage = models.CharField(max_length=10, blank=False) account_balance = models.FloatField(max_length=15, blank=False) account_profit = models.FloatField(max_length=15, blank=False) account_equity = models.FloatField(max_length=15, blank=False) account_margin = models.FloatField(max_length=15, blank=False) account_margin_free = models.FloatField(max_length=15, blank=False) account_margin_level = models.FloatField(max_length=15, blank=False) account_currency = models.CharField(max_length=20, blank=False) objects = models.Manager() class Meta: db_table = 'AccountInfo' Query.py: from django.db import models import sys sys.path.insert(0, r"C:\Users\Jonas\Desktop\Dashex") import os os.environ['DJANGO_SETTINGS_MODULE'] = 'Dashex.settings' import django django.setup() from Dashboard.models import AccountInformation //// query data account_information = AccountInformation.objects.all() print(account_information) Printed Output: <QuerySet [<AccountInformation: AccountInformation object (30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f)>, <AccountInformation: AccountInformation object (8b46c7c7-1bc8-4736-8dc5-7d5f012d594b)>]> Process finished with exit code 0 Why it doesn't return the whole data from the table like broker, accountNumberetc.? linked question: Additionally, if I use AJAX … -
How can I extend my existing Custom User Model created with AbstractBaseUser to have multiple user types like customer, trainer and author?
I have an existing custom user model which I created based on the Django doc to have email-based authentication. I want to extend the model to have multiple user types like Customers, Trainers, and Authors. I am not sure how to go forward and what is the best way to extend this? Also, have I made the right choice going with the AbstractBaseUser or should I have used the AbstractUser Class. -
How to get id from button modal to django views
I want to get the id from the modals button to select the id for the context object get id. the sample script is like this: <button type="button" class="btn btn-primary see-details" data-toggle="modal" data-target="#exampleModalLong" data-id="{{data.id}}">Detail</button> and I call the "data-id" from the button to javascript $(".see-details").on('click', function (){ var id = $(this).data('id'); $(".modal-bodys").html(` <div class="container-fluid"> <div class="row"> <div class="col-md-2"> <h1>{{students.name}}</h1> </div> </div> </div> `) }) I want to retrieve the id of the javascript variable to put into get id in the context in views.py from django.shortcuts import render,get_object_or_404 from profil.models import students def index(request): ID="get data-id from js" context = { 'students' : get_object_or_404(students, id=ID) } return render(request,'index.html',context) -
Trying to get the data from the dropdown list into views.py file in django
I want to get the data from the dropdown in HTML to the views.py file so that I can get the data from my database on the data which I will get from the dropdown. first try error: Request Method: POST Request URL: http://127.0.0.1:8000/admissions/ Django Version: 2.2.6 Exception Type: MultiValueDictKeyError Exception Value: 'state_dropdown' Exception Location: C:\django\lib\site-packages\django\utils\datastructures.py in getitem, line 80 Python Executable: C:\django\Scripts\python.exe Thanks in advance.. forms.py class state_form(Form): state_choices = ( ("Delhi", "Delhi"), ('west bengal', 'West Bengal'), ("Andhra Pradesh", "Andhra Pradesh"), ("Arunachal Pradesh", "Arunachal Pradesh"), ("Assam", "Assam"), ("Bihar", "Bihar"), ("Chhattisgarh", "Chhattisgarh"), ("Goa", "Goa"), ("Gujarat", "Gujarat"), ("Haryana", "Haryana"), ("Himachal Pradesh", "Himachal Pradesh"), ("Jharkhand", "Jharkhand"), ("Karnataka", "Karnataka"), ("Kerala", "Kerala"), ("Madhya Pradesh", "Madhya Pradesh"), ("Maharashtra", "Maharashtra"), ("Manipur", "Manipur"), ("Meghalaya", "Meghalaya"), ("Mizoram", "Mizoram"), ("Nagaland", "Nagaland"), ("Odisha", "Odisha"), ("Punjab", "Punjab"), ("Rajasthan", "Rajasthan"), ("Sikkim", "Sikkim"), ("Tamil Nadu", "Tamil Nadu"), ("Telangana", "Telangana"), ("Tripura", "Tripura"), ("Uttar Pradesh", "Uttar Pradesh"), ('Uttarakhand', 'Uttarakhand'), ) state_name=forms.ChoiceField(choices=state_choices) views.py def admissions(request): if request.method == "POST": a = request.GET['state_dropdown'] print(str(a)) else: context_dict = {} return render( request, 'buddyscholarship_html/admissions.html',{}) HTML code <form class="form-control mb-3" style="margin-top:500px;" method="post"> {% csrf_token %} <select class="col-lg-7 mb-4 mb-lg-0" name="state_dropdown"> <option value="select your state">select your state</option> <option value="Uttarakhand">Uttarakhand</option> <option value="West Bengal">West Bengal</option> <option value="Andhra Pradesh">Andhra Pradesh</option> <option value="Arunachal Pradesh">Arunachal Pradesh</option> … -
HTML page is not shown
when I click on about, it does not go in about.html page and not show any error. here is the link for calling <li><a href="{%url 'about'%}">About</a> </li> url url(r'^about/$',views.AboutView.as_view(),name = 'about') and, view,py class AboutView(TemplateView): template_name = 'about.html' -
django orm: combine result of two queries containing different fields
I have the following Django queries: my_timesheet_Q3_by_wp = my_timesheet_Q3.values('work_packet').annotate(wp_hours=Sum('logged_billable_hours')).order_by() returning [{'work_packet': 1152, 'wp_hours': Decimal('384.00')}] and: wps_details = WorkPacket.objects.values('id', 'number', 'name', 'type', 'purchase_order') returning: [{'purchase_order': 1, 'type': 1, 'id': 803, 'name': u'Consultancy', 'number': u'WP0001/1'}, {'purchase_order': 2, 'type': 1, 'id': 805, 'name': u'Consultancy', 'number': u'WP0002/1'}, {'purchase_order': 3, 'type': 1, 'id': 806, 'name': u'Consultancy', 'number': u'WP0003/1'}, ... the foreigh_key 'work_packet' (first model) is linked to the primary key 'id' (second model). I would like to combine the two queries to add 'number', 'name', 'type', 'purchase_order' to the first query, something like: [{'work_packet': 1152, 'wp_hours': Decimal('384.00'), 'purchase_order': xxx, 'type': xxx, 'id': xxx, 'name': u'someName'}] I know how to achieve this in plain sql but I am new to DJANGO orm -
Issue using i18n_patterns with API
I have an app which includes a website and an API. I have translated the website to a second language. The main language is currently English and the second one Farsi. I have used i18n_patterns in urlpatterns to redirect between the two languages. The issue is when using the API, it seems like Django redirects my request and since the data is sent using POST, it drops all data and gives me an empty result using GET. I tried taking the API url out of the urlpattern and then appending it which solves this issue, but that doesn't work since I need to have Unicode support for Farsi and since there is no i18n_patterns support this way, I get an unintelligible response. This is the Urlpattern: urlpatterns = i18n_patterns( path('admin/', admin.site.urls), path('mainapp/', include('mainapp.urls')), path('', include('mainapp.urls')), prefix_default_language=True ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns.append(path('api/', include('mainapp.api.urls'))) Is there any way I can solve this issue with the least possible change to the app? Any help, suggestion, or guidance would be very much appreciated. -
How can I integrate hbmqtt with Django?
I'd like to integrate a MQTT broker/server based on hbmqtt into a Django project. I'm providing a RESTful API for JS frontend integration as well. What are the general steps required to do so? BTW: I know about django_mqtt but it is GPL-2 licensed and no option for me. -
Django django.contrib.staticfiles.templatetags.static removed in 3.0: How could I replace the functionality?
I have the following code block where a corresponding .css file's path is returned. It is part of a Theme-Class that allows the user to change the website theme (dark and light) from a button in the profile view. def link(self) -> str: """ Returns the link where the CSS file for this theme is located """ return static('app_shared/colors_%s.css' % self.name()) The same problem when it occurs in an HTML-Template can be solved by changing {% load staticfiles %} to {% load static %}. Obviously for source code I will need another alternative. -
How to most effectivly query data from PostgreSQL asynchronously every X seconds?
Before going any further coding wise, I would like to consider and compare different approaches to query data from PostgreSQL DB asynchronously every X seconds. Project environment: Backend = Python based Django project, PostgreSQL DB, zeroMQ Pull socket Frontend = Basic HTML,CSS,JS stuff with some libraries like Vue, jQuery, etc. Background: I build a web based dashboard which will have to update its figures every 2 seconds using the latest data from the PostgreSQL DB which itself gets populated by zeroMQ datastream. Possible setups: 1.) AJAX + JS, client-side pull 2.) Axios + JS, client-side pull 3.) Psycopg2 + Python, server-side push 4.) Any other worth looking into? So which one would best fit in terms of lightweightness and performance? Talking about a possible peak, we assume to have around 5.000 - 10.000 users online -
Django query optimization for 3 related tables
I have 3 models: class Run(models.Model): start_time = models.DateTimeField(db_index=True) end_time = models.DateTimeField() chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, default=None, blank=True, null=True, on_delete=models.CASCADE) class RunProperty(models.Model): run = models.ForeignKey(Run, on_delete=models.CASCADE) property_name = models.CharField(max_length=50) property_value = models.CharField(max_length=500) class RunValue(models.Model): run = models.ForeignKey(Run, on_delete=models.CASCADE) run_parameter = models.ForeignKey(RunParameter, on_delete=models.CASCADE) value = models.FloatField(default=0) A Run can have any number of RunProperty (usually user defined properties, can be custom), and a few predefined RunValue (such as Average Voltage, Minimum Voltage, Maximum Voltage) that are numeric values. When I build a front end table to show each Run along with all of its "File" RunProperty (where the Run came from) and all of its "Voltage" RunValue, I first query the DB for all Run objects, then do an additional 3 queries for the Min/Max/Avg, and then another query for the File, then I build a dict on the backend to pass to the front to build the table rows: runs = Run.objects.filter(chamber__in=chambers) min_v_run_values = RunValue.objects.filter(run__in=runs, run_parameter__parameter__parameter_name__icontains="Minimum Voltage") max_v_run_values = RunValue.objects.filter(run__in=runs, run_parameter__parameter__parameter_name__icontains="Maximum Voltage") avg_v_run_values = RunValue.objects.filter(run__in=runs, run_parameter__parameter__parameter_name__icontains="Average Voltage") run_files = RunProperty.objects.filter(run__in=runs, property_name="File") This is not such a big problem for customer with ~10 to 30 Run objects in their database, but we have one heavy usage customer who … -
Django clean() change field requirement
I want to change the requirement of some modelForm fields as shown below. certs is a checkbox. If this checkbox is "True" the ca,cert and key fields shall be required. If not, they shall be left blank (null=True is set in models). class CreateMVPConnectionsForm(forms.ModelForm): class Meta: model = MVPConnections fields = '__all__' exclude = ['created_by_user', 'parent_project_id'] def clean(self): print("clean started") cleaned_data = super().clean() certs = cleaned_data.get('certs') ca = cleaned_data.get('ca') cert = cleaned_data.get('cert') key = cleaned_data.get('key') if certs == True: if ca and cert and key: pass else: raise ValidationError(_('If certs is checked, please fill in "ca", "cert" and "key".')) else: ca = forms.CharField(required=False) cert = forms.CharField(required=False) key = forms.CharField(required=False) Any suggestions on how to solve this? -
Django Lost connection to MySQL server during query
I have a Django Admin application which periodically gives "2013, 'Lost connection to MySQL server during query'" exception at various pages without any obvious reason, e.g. today the problem happens at /login page. My DB tables are relatively small, below 10k records. I noticed no correlation between the problem and database load, e.g. sometimes the problem happens at night when no one is using the database. I read multiple Stack Overflow articles describing similar issue, e.g. Lost connection to MySQL server during query and Lost connection to MySQL server during query?. Also read this: https://dev.mysql.com/doc/refman/5.7/en/error-lost-connection.html. Based on multiple articles I read on the issue, I tried to adjust MySQL DB variables, current values are: max_allowed_packet: 4194304 net_buffer_length: 16384 connect_timeout: 10 net_read_timeout: 30 wait_timeout: 28800 So far nothing helps, the problem just appears randomly and disappears by itself without me doing anything. I also noticed that it more often happens on the server while rarely happens on localhost (both server and localhost connecting to the same database). Any ideas would be very appreciated. Today's traceback from localhost: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/login/?next=/ Django Version: 2.1.7 Python Version: 3.7.4 Installed Applications: ['adminapp.apps.AdminappConfig', 'middleware.apps.MiddlewareConfig', 'adminactions', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', …