Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i fix migration problem in my Django project?
I have a migration problem: This is forms.py file enter image description here this is models.py enter image description here this is admin.py enter image description here -
Django template, how can i use if condition with using {% now 'F jS Y' %}
this is my template, how can i compare the date now with my myaccount.modifyDate ? <input name="temperature" value="{% if {% now 'F jS Y' %} >= myaccount.modifyDate %} 0.0 {% else %} {{myaccount.bodyTemperature}} {% endif %}" readonly></td> -
Better way of linking multiple models in Django [database]
I want to link the Subject model with Class in such a way that every student belonging of Class model will have same subjects included by user in Class. Inside models.py of school app. from django.db import models from accounts.models import School class Class(models.Model): connect_school = models.ForeignKey(School, on_delete=models.SET_NULL, null=True) class_list = models.CharField(max_length=95) def __str__(self): return self.class_list class Subject(models.Model): connect_class = models.ForeignKey(Class, on_delete=models.SET_NULL, null=True) subjects = models.CharField(max_length=95, null=True) def __str__(self): return self.subjects Inside models.py of student app: from django.db import models from django.utils import timezone import nepali_datetime from school.models import Class, Subject from accounts.models import School connect_school = models.ForeignKey(School, on_delete=models.CASCADE, null=True) ...name,gender, etc. ... Class = models.ForeignKey(Class, on_delete=models.CASCADE, null=True) subject = models.ManyToManyField(Subject) Inside models.py of accounts. from django.db import models from django.utils import timezone import nepali_datetime # from django.contrib.auth.models import User # Create your models here. class School(models.Model): school_name = models.CharField(max_length=50) ... username = models.CharField(max_length=100) password = models.CharField(max_length=95) ... principal = models.CharField(max_length=150, default='') .... -
AttributeError at /api/logout 'AnonymousUser' object has no attribute 'auth_token'
I have successfully deployed the login view and it returns the token, but when i try to logout it returns the following error. I am new to this so cant figure out the reason. These are my login and logout views. class LoginUserView(GenericAPIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) serializer.is_valid(raise_exception=True) new_data = serializer.data user = serializer.validated_data["user"] token, created = Token.objects.get_or_create(user=user) return response.Response(new_data, status=status.HTTP_200_OK) return response.Response({"token": token.key}, status=status.HTTP_200_OK) # return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Logout(GenericAPIView): def get(self, request, format=None): # simply delete the token to force a login request.user.auth_token.delete() return Response(status=status.HTTP_200_OK) -
DRF custom authentication class capture GET request parameters
I have a custom DRF authentication class like so: from rest_framework import authentication, exceptions class MyCustomAuthenticationClass(authentication.BaseAuthentication): def authenticate(self, request): try: # some codes print(request.GET.get('user_id', 'no user_id')) return (UserObject, None) except Exception as e: print(e) raise exceptions.APIException("Server error") I would like to capture parameter from my url path(/edit/<int:user_id>) in my custom authentication class for validation. So i tried to print it out to see if i can capture the parameter when calling a url But the console doesn't print out anything I can capture parameters like so in the normal APIView of DRF but not in custom authentication class Is my method of getting request parameters not correct? hope someone can tell me -
TypeError: Cannot create a consistent method resolution in django
I am learning django through the 'Django 3 by example' book, and right now i am trying to build an e - learning platform. But, I am getting a weird error in my views.py file. Here is my views file: from django.views.generic.list import ListView from django.urls import reverse_lazy from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from .models import Course class ManageCourseListView(ListView): model = Course template_name = 'educa/manage/educa/list.html' permission_required = 'educa.view_course' def get_queryset(self): qs = super().get_queryset() return qs.filter(owner=self.request.user) class OwnerMixin(object): def get_queryset(self): qs = super().get_queryset() return qs.filter(owner=self.request.owner) class OwnerEditMixin(object): def form_valid(self, form): form.instance.onwer = self.request.user return super().form_valid(form) class OwnerCourseMixin(object, LoginRequiredMixin, PermissionRequiredMixin): model = Course fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list') class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin): template_name = 'educa/manage/course/list.html' class CourseCreateView(OwnerEditMixin, CreateView): permission_required = 'educa.add_course' class CourseUpdateView(OwnerCourseEditMixin, UpdateView): permission_required = 'educa.change_course' class CourseDeleteView(OwnerCourseMixin, DeleteView): template_name = 'educa/manage/course/delete.html' permission_required = 'educa.delete_course' The error is on line 30. Here is the full error message: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Padma … -
Weighted average for specific student, from specific subject
I've been learning Python for few days already and I've tried to accomplish a small Django model of school. My goal for now is to be able to assign a weighted score to a student for a specific subject (for example physics) and then sum these weighted scores and return a weighted average for a student for his subject. For example, Student A has scores 3 (score) * 2 (weight), 3 * 3 in Physics and 2 * 4, 3 * 1 in Math. My goal is to return: Student A Physics average: 2.5 Student A Math average: 2.2 for now I've been trying to achieve it this way, but it doesn't work. class Score(models.Model): scale = models.PositiveIntegerField(choices=scales_list) student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) task = models.ForeignKey(Task, on_delete=models.CASCADE) weight = models.PositiveIntegerField(default=1) def _weighted_score(self): return self.scale * self.weight weighted_score = property(_weighted_score) def _weighted_average(self): qs = self.objects.all().annotate( score_sum = sum('scale'), weighted_sum = sum('weight'), weighted_avg = Sum((F('scale') * F('weight')), output_field=FloatField() ) / Sum('weighted_sum'), output_field=FloatField() ) return weighted_avg weighted_average = property(_weighted_average) Thanks -
Django - display items from a collection inside a template
I am building an e-commerce store with Django, and I have added some products to a collection. I want to be able to display each collection separately with the products that have been added to it. Here is my models.py code #Products model Fields class Product(models.Model): title = models.CharField(max_length = 100) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2,) image = models.ImageField(upload_to = "pictures") def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug, 'my_id': self.id}) #Collections model Fields class Collections(models.Model): title = models.CharField(max_length=100) products = models.ManyToManyField(Product) def __str__(self): return self.title def get_absolute_url(self): return reverse('collections', kwargs={'slug': self.slug, 'my_id': self.id}) Here is my Views.py: def get_redirected(queryset_or_class, lookups, validators): ... def collectionsPage(request, my_id, slug): article, article_url = get_redirected(Collections, {'pk': my_id}, {'slug': slug}) if article_url: return redirect(article_url) collections = Collections.objects.get(id=my_id) products = Product.objects.all() context = {"products": products, "Collections":collections,} return render(request, "collections.html", context) Here is my urls.py: urlpatterns = [ path('collections/<slug:slug>,<int:my_id>', views.collectionsPage, name="collections"), ] Here is my HTML Code: {% for collection in collections %} <form action="{{collection.products.get_absolute_url}}" method="post"> {% csrf_token %} <button class="polaroid" style="background-color:white; border:none"> <div> <img src="{{collection.products.imageURL}}" alt="iPhone image"> <h3 class="container">{{collection.products.title}}</h3> <h4 class="container">{{collection.products.price}}</h4> </div> </button> </form> {% endfor %} -
Keycloak introspect token - 500 Failed to establish a new connection
I am connecting a Django backend to Keycloak and am getting a 500 - Failed to establish a new connection error when I call the token introspection endpoint. I believe I have a localhost vs. Docker sort of config issue that is not allowing the endpoint to return. How should these be set up so this will work or how can I further debug? I have the following set up: Front end on localhost:3000 with a Keycloak client that is public (this redirects to the Keycloak and then returns a valid token) Backend in Django on localhost8000 with a confidential KeyCloak client, libray = 'django-keycloak-auth' Keycloak on Docker pointing to localhost8080 When I do an API call from the front end with a valid token, the backend uses the `django-keycloak-auth' library to call the introspection endpoint: http://localhost:8080/auth/realms/myproject/protocol/openid-connect/token/introspect with my client id and my client name but this fails with the below error: requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: /auth/realms/myproject/protocol/openid-connect/token/introspect (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fea20c3d370>: Failed to establish a new connection: [Errno 111] Connection refused')) When I test the token at this endpoint: http://localhost:8080/auth/realms/mobius-dev/protocol/openid-connect/userinfo I get a valid response. Items in the api call: body 'token=MY_TOKENA&client_id=backend&client_secret=MY_SECRET' encode_chunked False … -
Hot reloading properties in a Python Flask/Django app
Gurus, Wizards, Geeks I am tasked with providing Python Flask apps (more generally, webapps written in python) a way to reload properties on the fly. Specifically, my team and I currently deploy python apps with a {env}.properties file that contains various environment specific configurations in a key value format (yaml for instance). Ideally, these properties are reloaded by the app when changed. Suppose a secondary application existed that updates the previously mentioned {env}.properties file, the application should ALSO be able to read and use new values. Currently, we read the {env}.properties at startup and the values are accessed via functions stored in a context.py. I could write a function that could periodically update the variables. Before starting an endeavor like this, I thought I would consult the collective to see if someone else has solved this for Django or Flask projects (as it seems like a reasonable request for feature flags, etc). -
Unable to make any changes to view.py file
I'm hosting a web server with Django framework . Then , I'm using Notepad++ NppFTP to modify and upload those files . I can modify the html files and upload to ftp server instantly with Notepad++ NppFTP .But for updating view.py , I found that even though it says view.py 100% upload success , the web seems to be unchanged regarding to the new view.py file . Is that the way to modify the view.py file different to modifying HTML files ? -
How to change Wagtail's default language?
I'm using headless Wagtail and want to change the default backend language to Portuguese (pt-pt). Following wagtail's docs: # settings.py USE_I18N = True LANGUAGE_CODE = "pt-pt" Then why I try to publish a wagtail page I get the following error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/pages/11/edit/ Django Version: 3.1.2 Python Version: 3.9.0 Installed Applications: ['home', 'search', 'news', 'about_us', 'product', 'dashboard', 'wagtail_headless_preview', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'wagtail.api.v2', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders'] Installed Middleware: ['django.middleware.locale.LocaleMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Traceback (most recent call last): File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\django\core\handlers\exception.py", line 52, in inner response = get_response(request) File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\django\core\handlers\base.py", line 195, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\django\views\decorators\cache.py", line 49, in wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\wagtail-2.11rc1-py3.9.egg\wagtail\admin\urls_init.py", line 170, in wrapper return view_func(request, *args, **kwargs) File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\wagtail-2.11rc1-py3.9.egg\wagtail\admin\auth.py", line 179, in decorated_view response = view_func(request, *args, **kwargs) File "C:\Users\diogo\OneDrive - Universidade de Tras-os-Montes e Alto Douro\Marfon\venv\lib\site-packages\django\views\generic\base.py", line 85, in … -
Retrieving object by email from object manager class
I am using Django 3.10 I am extending the User model, to create a custom user model. I want the unique attribute on the User object to be the email. When creating the object, if an object with the same email exist, an Integrity error will be raised and trapped, and the existing object is returned instead. I am not sure the best way to implement this functionality. This is my code so far: from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class FooUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password=None, username=None, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) if username: extra_fields['username'] = username user = self.model(email=email, **extra_fields) user.set_password(password) try: user.save() except IntegrityError as e: if not 'creating_superuser' in extra_fields user = FooUserManager.get(email=email) # <- obviously won't work ... else: raise e return user def create_superuser(self, email, password, username, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) extra_fields['creating_superuser'] = True if extra_fields.get('is_staff') is … -
I want to find experienced Django developers to work in their projects
I would like to find Django developers who want help on their projects and I can learn by helping them and also get some advice about my job. -
Data don't appear in html page in Django
i have problem with my data , it's don't appear in my html page i tried do this but nothing happen model.py : class BestArticals(models.Model): name = models.CharField(max_length=240) url = models.URLField(default="",max_length=240) image = models.ImageField(upload_to='images/',null=True, blank=True) def get_image(self): if self.image and hasattr(self.image, 'url'): return self.image.url else: return '/path/to/default/image' def __str__(self): return self.name veiws.py : def Best_Articals(request): best_posts = BestArticals.objects.all() context = {'best_posts' : best_posts} return render(request,'android/side_bar_good_posts.html',context=context) html page : {% for post in best_posts %} <ul style="text-align:right"> <li> <img src="{{post.get_image}}" height="80px" width="80px"> <a href="{{post.url}}" style="color:black"> {{post.name}} </a> </li><br> </ul> {% endfor %} what is the problem here -
How to create an object whose name is passed as a parameter
I want to create an object before i save an object related to it, how can i do that? In my Item model i have tags ManyToManyField. I want to create or update Item passing a Tag name as a parameter even if Tag object with this name is not created yet. models.py class Tag(models.Model): name = models.CharField(primary_key=True, max_length=50, unique=True, db_index=True) items_num = models.BigIntegerField('Number of Items', default=0) class Item(models.Model): category = models.ForeignKey('Category', on_delete=models.DO_NOTHING) tags = models.ManyToManyField('Tag') user = models.ForeignKey('users.User', on_delete=models.CASCADE) name = models.CharField(max_length=30) description = models.CharField(max_length=300, blank=True) main_image = models.ImageField(default='main_image_test_path') CHEAP = 'CH' MIDDLE = 'MI' EXPENSIVE = 'EX' VERY_EXPENSIVE = 'VE' MOST_EXPENSIVE = 'ME' PRICE_CHOICES = [ (CHEAP, 'Cheap'), (MIDDLE, 'Middle'), (EXPENSIVE, 'Expensive'), (VERY_EXPENSIVE, 'Very Expensive'), (MOST_EXPENSIVE, 'Most Expensive') ] price = models.CharField( max_length=2, choices=PRICE_CHOICES, default=CHEAP ) status = models.BooleanField(default=1) # 1 - Active, 0 - Inactive serializers.py class ItemListSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField(many=True, queryset=Tag.objects.all()) category = serializers.SlugRelatedField(slug_field='name', queryset=Category.objects.all(),) user = UserSerializer(read_only=True,) class Meta: model = Item fields = ('id', 'name', 'category', 'tags', 'user', 'price', 'status',) def validate_tags(self, value): print(value) if len(list(set(value))) != len(value): raise serializers.ValidationError('All tags must be unique') return value def create(self, validated_data): validated_data['user'] = self.context['request'].user for tag in validated_data['tags']: tag.items_num += 1 tag.save() validated_data['category'].items_num += 1 validated_data['category'].save() … -
How come I can set these fields with Postman even though my perform_create method is setting these fields at save with the requested user?
Here is my serializer class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' My model for items class Item(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) title = models.CharField(max_length=200) #need to add images description = models.TextField() price = models.CharField(max_length=50) created_on = models.DateTimeField(auto_now_add=True) Here is the viewset class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer permission_classes = [IsOwnerOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) brand_qs = Brand.objects.filter(owner=self.request.user) if brand_qs.exists: serializer.save(brand=brand_qs[0]) So, when using postman I am still required to enter the user and brand fields, and can make the user field any user I want, doesn't save with the requested user. -
Pagination or limit range happybase
Need make to filter in happybase django or a pagination. similar in sql SELECT * FROM tabla LIMIT 1,10 -
Django limiting Foreign Key values based on model field choice
Currently I have two tables, user types and user subtypes, that needs to be related based on condition. For example.: The UserType USER_A can only be related to UserSubtypes TYPE_A and TYPE_B entries The UserType USER_B can only be related to UserSubtypes TYPE_C entries The UserType USER_C can only be related to UserSubtypes TYPE_D entries class UserTypes(models.Model): USER_TYPES = [ ("USER_A", "USER_A"), ('USER_B', 'USER_B'), ('USER_C', 'USER_C'), ] account_type = models.ForeignKey(UserSubtypes) user_type_name = models.CharField(choices=USER_TYPES, default="USER_A") class UserSubtypes(models.Model): USER_SUBTYPES = [ ("TYPE_A", "TYPE_A"), ('TYPE_B', 'TYPE_B'), ('TYPE_C', 'TYPE_C'), ('TYPE_D', 'TYPE_D'), ] user_type_name = models.CharField(choices=USER_TYPES) How can I achieve this kind of conditional relationship? -
With python, getting and passing values in json data
there is a "data" coming in json. I show it with "columnar", but because there are more than one row, it creates a new table. What I really want to do is show it all in one painting. How can we achieve this? data = "{'symbol': 'APPLE', 'positionAmt': '-0.001', 'entryPrice': '268.83000'} {'symbol': 'BLACKBERRY', 'positionAmt': '-0.001', 'entryPrice': '390.12000'}" headers = ["Symbol", "positionAmt", "Entry", "Side"] for sym in data: if sym['positionAmt'][:1] == "-": result = [ [sym['symbol']], ] table = columnar(result, headers=headers) print(table) Whenever a new line comes up, the table header "symbol" increases. -
I want to add a search functionality to each and every word in my home page and display it in another html template in django app
For Eg. My home page contains a register button, a contact us button, an About us button, and a few more like this. So if someone types about us in the search tab then the search functionality should point it towards the about us button. Please share your answers if this is possible in Django. -
Unable to Retrieve Multiple image in Django Post detail Page after succesfull upload in admin page
I have a BLOG/NEWS website with the following Model.py, Views.py and and a post_detail.html page which i can successfully upload an image or file in the admin page panel when creating a post but cannot retrieve the image in my post_detail.html page. I mean am unable to Retrieve Multiple image on my blog Post when i do the following code and after a succesful upload of images on the admin panel . I need help in solving this problem amicably. And i have my admin.py configured accurately which make provision for uploading multiple images on a specific post in django Models.py class Post(models.Model): image = models.ImageField(upload_to="images/") title = models.CharField(max_length=150) summary = models.CharField(max_length=250) class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) images = models.ImageField(blank=True, upload_to='images') @property def image_url(self): return self.get_absolute_url() def get_absolute_url(self): return self.image.url Views.py class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['related_posts'] = Post.objects.filter(category=self.object.category).order_by('?')[:2] Context['multiple_image']= PostImage.objects.all() return context post_detail.html <div class="w-full md:flex md:-mx-2 "> {% for image in mutiple_images %} <div class="w-full md:w-1/2 px-2"> <a href="{{ postimage.get_absolute_url }}"> <img class="object-cover w-full h-24 m-2 rounded-lg" src="{{ postimage.images.url }}" alt=""> </a> </div> {% endfor %} </div> Unfortuanately the image refuse to appear in the detail page and i strongly believe … -
Django ORM -- Why is blank=True/null=False failing with default="" (and blank=False/null=True with default=None as well)
I have the following model: class MyModel(models.Model): # normal fields calculated_field = models.CharField(max_length=4, blank=True, null=False, default="") def save(self, *args, **kwargs): self.calculated_field = self.function_to_calculate_field_value() super(MyModel, self).save(*args, **kwargs) This is calculated based on values from another model where MyModel has a ManyToMany relationship. This works with my forms and does what I want. When I bulk upload data via a JSON command, though, I get a NOTNULL constraint failed error despite the default value being an empty string. I've tried switching it up like so: calculated_field = models.CharField(max_length=4, blank=False, null=True, default=None) But this gives me this error in the console: {'calculated_field': ['This field cannot be blank.'] I know I'm not supposed to set a CharField to null=True and blank=True, but I'm seriously running out of ideas here. Why are neither of these options working? -
Remove shopping cart django
how can I delete a user's shopping cart automatically after a certain time (for example, after a one day)? my view: def remove_cart(request, id): url = request.META.get('HTTP_REFERER') Cart.objects.get(id=id).delete() return redirect(url) my models : class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) variant = models.ForeignKey(Variants, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() create = models.DateTimeField(auto_now_add=True) -
mysql 5.7 breaking tests ( mysql connection gone )
I am facing a test failures while updating a code from mysql5.6 to 5.7. Only one test which is using multiprocessing.Process is failing. MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') The above exception was the direct cause of the following exception Is there any change in related with threading in mysql5.7 or i am missing some thing ?