Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Progress-bar percentage is not the percentage of uploaded file
My progress bar is working but not with the percentage of the uploaded file. I don't know why. Could someone have a look on my code please. I couldn't figuring out the issue. Upload.js $(document).ready(function() { $('form').on('submit', function(event) { event.preventDefault(); var formData = new FormData($('form')[0]); $.ajax({ xhr : function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { var percent = Math.round((e.loaded / e.total) * 100); $('#progressBar').attr('aria-valuenow', percent).css('width', percent + '%').text(percent + '%'); } }); return xhr; }, type : 'POST', url : '/upload', data : formData, processData : false, contentType : false, success : function() { alert('File uploaded!'); } }); }); }); upload.html <form class="" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> {{form}} <button type="submit" class="btn btn-success" name="button">Upload</button> <button type="button" class="btn btn-danger">Cancel</button> </div> </form> <div class="progress"> <div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div> </div> output (the form is not processing and the progress bar doesn't depend on the percentage of the percentage of the uploaded file (since the form is not processing when submitting) -
Django channel sends duplicate messages
When user sending a message, same message sent. Here is comsumer.py code async def receive(self, text_data): message= json.loads(text_data) await self.channel_layer.group_send( self.chat_id, { 'type': 'send_message', 'text': message['text'], 'created': str(message['created']).replace(' ', 'T'), }, ) async def send_message(self, event): print(event) await self.send(text_data=json.dumps(event)) I could see the same message being sent through the log. websocket: {'type': 'send_message', 'text': 'ㅡㅡ', 'image': '', 'created': '2021-05-25T18:05:54.471893'} websocket: {'type': 'send_message', 'text': 'ㅡㅡ', 'image': '', 'created': '2021-05-25T18:05:54.471893'} websocket: {'type': 'send_message', 'text': 'ㅡㅡ', 'image': '', 'created': '2021-05-25T18:05:54.471893'} websocket: {'type': 'send_message', 'text': 'ㅡㅡ', 'image': '', 'created': '2021-05-25T18:05:54.471893'} I'm using python 3.7, channels 3.0.2, channels-redis 3.2.0 and django 3.1.4 -
No such file or directory: file: /usr/lib/python3/dist-packages/supervisor/xmlrpc.py line: 560
When i trying to use this command "sudo supervisorctl reread" I get this error [Errno 2] No such file or directory: file: /usr/lib/python3/dist-packages/supervisor/xmlrpc.py line: 560 -
return render with get_context_data()
The scenario is I'm trying to render a specific class section and list of students that doesn't belong to any sections yet. How can I achieve this using function based views? Here's my code that doesn't work but at least this is the idea: def get_students(request, pk): section = Section.objects.get(id=pk) def get_context_data(self, **kwargs): context = super(get_students(request, pk), self).get_context_data(pk) context['section'] = section context['students'] = Account.objects.filter(Q(is_student=True) | Q(is_assigned=False)).order_by( 'last_name', 'first_name') return context return render(request, 'driver-list-modal.html', get_context_data(pk)) The template that I picture would contain the class section name and a table of unassigned students with a checkbox to include them to that section if selected. Thank you for answering! -
Filtering by natural key?
I don't have the ids of the objects I want because they were created by bulk_create: and bulk_create doesn't return objects with ids so I need to fetch them by their natural keys. Is it possible to fetch the objects by filtering by natural key? I've found nothing in the documentation. We can already do: id_list = [10,3,5,34] MyModel.objects.filter(id__in=id_list) I'd like the same thing with natural key: NK_list = [('bob','carpenter'),('jack','driver'),('Leslie','carpenter')] chosen_persons = Person.objects.filter(natural_key__in=NK_list) My model looks like this: class PersonManager(models.Manager): def get_by_natural_key(self, name, job): return self.get(name=name, job=job) class Person(Models.model): name = models.CharField(max_length=200) job = models.CharField( max_length=200) objects = PersonManager() class Meta: unique_together = [['name', 'job']] def natural_key(self): return (self.name, self.job) -
Data validation error in Django Serializer
Model: class Group(models.Model): emp = models.ForeignKey(Employee, on_delete=models.CASCADE) #try user name = models.CharField(max_length=500, default=0) groupmodels = models.ManyToManyField(GroupModels) sender_clients = models.ManyToManyField(Client) I am sending the data from frontend like the following: {'name': 'dcwhjbe', 'emp': 15, 'sender_clients': [{'id': 3}], 'receiver_clients': [], 'warehouses': [], 'groupmodels': []} But there is some problem in data validation Serializer class GroupsSerializer(serializers.ModelSerializer): groupmodels = GroupModelsSerializer(many=True) sender_clients = ClientSerializer(many=True) receiver_clients = ReceiverClientSerializer(many=True) warehouses = WarehouseSerializer(many=True) class Meta: model = Group fields = "__all__" def create(self, validated_data): print("v data", validated_data) items_objects = validated_data.pop('groupmodels', None) sc_objects = validated_data.pop('sender_clients', None) rc_objects = validated_data.pop('receiver_clients', None) ware_objects = validated_data.pop('warehouses', None) prdcts = [] sc = [] rc = [] ware = [] for item in items_objects: i = GroupModels.objects.create(**item) prdcts.append(i) instance = Group.objects.create(**validated_data) print("prdcts", prdcts) if len(sc_objects)>0: for i in sc_objects: inst = Client.objects.get(pk=i) sc.append(inst) . . . . return instance print("v data", validated_data) is never called except I get this in the response: sender_clients: [{user: ["This field is required."]}] Is it because it is trying to create a sender client ? I just want to add the already created sender_clients to Group -
Cannot use QuerySet for "\"User\": Use a QuerySet for \"User\"."
I am working on a django project, python version 3.8 with django version 3.2.3 and I have created a friend request model that currently only needs to make a friend request table entry. The request contains two parameters, the senders unique id, and the receiver's unique id. It then makes a friend request entry in the FriendshipRequest table (as described by the model shown below). The view.py is as shown below. @csrf_exempt def friend_request(request): if request.method != 'POST': return r.method_not_allow_405() try: client_json = json.loads(request.body) sent_user_id = client_json['sent_user_id'] received_user_id = client_json['received_user_id'] sent_user = models.User.objects.filter(unique_id=sent_user_id) received_user = models.User.objects.filter(unique_id=received_user_id) try: models.Friend.objects.add_friend(sent_user=sent_user, received_user=received_user, message="") return r.json_response(0, "friend request successful") except Exception as e: return r.json_response(-2, str(e)) # except Exception as e: return r.json_response(-2, str(e)) # catch errors made by sent_user, received_user lines, or json (no errors in this case) There are four main models defined, the User which represents the User information, I've only kept the relevant unique_id variable in the snippet. The FriendshipRequest model which represents a friend request, and uses a ForeignKey for the user that sent the request and the user that received it. There is a FriendshipManager model that manages friend request, and in this snippet only contains add_friend function, … -
Django Model field handle if foreign key is empty string
I currently maintain on Django admin multiple database, here's what current looks: class Notes(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) created_at = models.DateTimeField() updated_at = models.DateTimeField() created_by = models.CharField(max_length=255, blank=True, null=True) modified_by = models.CharField(max_length=255, blank=True, null=True) note = models.TextField() I have created router for allowing relations between User & Notes, which I want to do like this: class Notes(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) created_at = models.DateTimeField() updated_at = models.DateTimeField() created_by = models.ForeignKey(User, models.DO_NOTHING, null=True, db_column='created_by', related_name='created_by') modified_by = models.ForeignKey(User, models.DO_NOTHING, null=True, db_column='modified_by', related_name='modified_by') note = models.TextField() but due to default value on that database state is empty string (or ''), I received error ["'' is not a valid UUID."] So far what I did for handling this issues were creating new methods like def created_by_user(self): user = '' if not self.created_by: return user try: user = User.objects.get(pk=self.created_by) except User.DoesNotExist: pass return user created_by_user.short_description = _('Created by') is there any better solutions where Django admin handle this error? I've red and far solutions I found were : create migrations to make those fields default value is nullable (which I would not to approach, due to legacy database) using previous methods (which I think it's going to be expensive) using multiple types fields (?) … -
Django-Filters returns incorrect data
I have two models Products and Categories. I am using django-fliters to filter my queryset but in some cases its returning incorrect data. When I filter the products with parameter ParentCaregory = 1, it filters the correct data. But when I filter the products with parameter ParentCaregory = 3 it returns incorrect data As you can see its returning incorrect data. These are my models: class Categories(models.Model): parent_category = models.CharField(max_length=100) second_level_category = models.CharField(max_length=100) third_level_category = models.CharField(max_length=100) product = models.ForeignKey(to=Products, on_delete=models.CASCADE) class Products(models.Model): product_id = models.BigIntegerField(primary_key=True) # creating primary key sku = models.CharField(max_length=100) name = models.CharField(max_length=100) And this is the Filter Class I am using from django_filters import rest_framework as filters from data_tool.models import Products class DataFilter(filters.FilterSet): brand = filters.CharFilter(lookup_expr='iexact') shop_url = filters.CharFilter(lookup_expr='iexact') warranty = filters.CharFilter(lookup_expr='iexact') weight = filters.CharFilter(lookup_expr='iexact') categories__parent_category = filters.CharFilter(lookup_expr='iexact') categories__second_level_category = filters.CharFilter(lookup_expr='iexact') categories__third_level_category = filters.CharFilter(lookup_expr='iexact') marketplace_status = filters.CharFilter(lookup_expr='iexact') product_status = filters.CharFilter(lookup_expr='iexact') refund_and_return_policy = filters.CharFilter(lookup_expr='iexact') attribute_set = filters.CharFilter(lookup_expr='iexact') warrenty = filters.CharFilter(lookup_expr='iexact') class Meta: model = Products fields = ['brand', 'shop_url', 'warranty', 'weight', 'categories__parent_category', 'categories__second_level_category', 'categories__third_level_category', 'marketplace_status', 'product_status', 'refund_and_return_policy', 'attribute_set', 'warrenty'] -
How to pass input type "File" to another html [closed]
I have created a submit and edit claims form. When I submit the claim, I want the details of the receipt to show on editclaim as well. This is my submitclaim.html <label for="receipt">Receipt: </label> <input id="receipt" type="file" name="receipt_field"> In the editclaim.html <label for="receipt">Receipt: </label> <input id="receipt" type="file" name="receipt" value={{claims.receipt}}> The current database I'm using is sqlite. It is embedded into my web application. -
How to print sql query from django as Dubug is False
From doc how can I see the raw SQL queries Django is running? I can get sql executed by >>> from django.db import connection >>> connection.queries But it's only available while Debug = True How to print sql as Debug is False? Thanks -
How to update and create at the same time using nested serializers and viewsets in DRf?
my models: class User(AbstractUser): password = models.CharField(max_length=128, blank=True, null=True) email = models.EmailField(max_length=254, unique=True) dial_code_id = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100, unique=True) username = models.CharField(max_length=150, unique=True, blank=True, null=True) is_active = models.BooleanField(default=True) class Meta: db_table = "my_user" class UserLocation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='location') latitude = models.DecimalField(max_digits=8, decimal_places=3) longitude = models.DecimalField(max_digits=8, decimal_places=3) address = models.TextField() class Meta: db_table = "user_location" I have to update 'first_name', 'last_name' and at the same time I have to create an object in the 'UserLocation' table for the same user. For that I have created a viewset class BasicInformationViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = BasicInformationSerializer def list(self, request, *args, **kwargs): custom_data = { "status": False, "message": 'Method Not Allowed', } return Response(custom_data, status=status.HTTP_200_OK) def create(self, request, *args, **kwargs): custom_data = { "status": False, "message": 'Method Not Allowed', } return Response(custom_data, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data) if serializer.is_valid(): serializer.save() custom_data = { "status": True, "message": 'Successfully added your basic information', } return Response(custom_data, status=status.HTTP_200_OK) else: custom_data = { "status": False, "message": serializer.errors, } return Response(custom_data, status=status.HTTP_200_OK) Serializer for the above views: class UserLocationSerializer(serializers.ModelSerializer): latitude = serializers.DecimalField(max_digits=8, decimal_places=3, required=True) longitude = serializers.DecimalField(max_digits=8, decimal_places=3, required=True) address = serializers.CharField(required=True) class Meta: model = UserLocation … -
Is there any way to make a separate view for common header in DJango
I want to make a common header file and separate view for each template page in django. so that every time I dont have to write header code in each template's view -
Is there any method to optimize the below code instead of creating for every model
I have made global search functionality for my Django web app based on user roles. But Instead of adding permission in every model, how to make a common function and add it to every model to get the API. Your suggestions and guides will be highly appreciated. Please help me with this problem. Thank you in advance. from django . shortcuts import render from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status # Create your views here. from apps. events.models import Event from apps. events.serializers import EventSerializer from apps. inquiry. models import Newinquiry, from apps. inquiry.serializers import NewinquirySerializer from apps.customer_po.models import PoDetail from apps.customer_po.serializers import POSerializer from apps.customer.models import Customer from apps.customer.serializers.customer import CustomerSerializer from django .db.models import Q class SearchView(APIView): def get(self, request): user = self.request.user data = {} q = request.GET.get('q','') customer_obj = Customer.objects.filter(Q(customer__icontains=q) | Q(country__icontains=q) | Q (industry__industry__icontains=q) | Q(location__icontains=q) | Q(outcome__icontains=q) | Q(contact_person__icontains=q)) data['customers'] = CustomerSerializer(customer_obj, many=True, context={'request': request}).data if user.groups.name in ['CEO', 'Admin']: resp = {'data':CustomerSerializer(Customer.objects.all(), many=True).data} elif user.groups.name == 'Manager': resp = {'data':CustomerSerializer(Customer.objects.filter( Q(created_by=user) | Q(created_by__reports_to=user) ), many=True).data} else: resp = {'data':CustomerSerializer(Customer.objects.filter(assigned_to=user), many=True).data} return Response(resp, status=status.HTTP_200_OK) # events_obj = Event.objects.filter(Q(status_type__icontains=q) | Q(customer_name__customer__icontains=q) | Q(activity_type__icontains=q) | Q(priority_type__icontains=q) | Q(visibility_type__icontains=q) | Q(organization_type__icontains=q) |Q(contact_name__icontains=q) … -
How to always get the top value based of the marks of each group
views.py stats = models.Group.objects.raw( f""" WITH CTE AS (SELECT S.Group_id, S.name, SUM(GQ.mark) AS "group_highest",GQ.date FROM SQUADS S INNER JOIN GROUP G ON G.Group_id = S.Group_id INNER JOIN GROUP_QUESTIONS GQ ON GQ.trainee_id = G.trainee_id group by G.trainee_id ORDER BY G.group_id ASC, "group highest" DESC) SELECT * FROM CTE """ ) stat = stats[0] for question_part in question_parts: if question_part["group_id"] == statss.group_id: models.GroupStat.objects.filter(group_id=question_part["group_id"]).update( group_highest=stat.group_highest, ) else: pass Group_id name group_highest date 1 A 17.5 2021-05-25 12:44:23.852450 2 A 16 2021-05-01 16:48:12.251089 3 A 18 2021-05-01 16:20:10.233873 1 A 16 2021-05-01 16:09:39.073816 2 B 17 2021-04-30 17:46:08.747425 3 B 13.5 2021-04-29 18:45:45.984880 1 B 15 2021-04-15 13:20:44.623553 2 B 1.5 2021-04-12 13:32:06.105785 Goal:What i am trying to achieve here is that after i edit the marks of each participant, i use the SQL query above to update the value of group_highest in the table GroupStat according to which participant has the highest marks according to their group. Problem: stat = stats[0] only updates the first value of the sql and does not get the highest value of each squad What i have tried so far: i have tried using date to get the first of every value however lets say i change the … -
Error : attempted relative import with no known parent package
I try to import the model.py file in populate_reusumeeditor.py But It keeps giving this error: ImportError: attempted relative import with no known parent package I have imported everything correctly even pycharm is not showing any error. Here is model.py file: from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=200,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic, on_delete= models.CASCADE) name = models.CharField(max_length=264, unique = True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage, on_delete=models.CASCADE) date = models.DateField() def __str__(self): return str(self.date) here populate_reusumeeditor.py file import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Resumemake.settings') import django django.setup() import random from .resumeeditor.models import AccessRecord,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['search','Social','Marketplace', 'News', 'Games'] def add_topics(): t = Topic.objects.get_or_create(top_name = random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): top = add_topics() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic = top, url = fake_url, name = fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg, date = fake_date)[0] if __name__== '__main__': print('Populating Script!') populate(20) print('Populating complete!') Here is the flow of the project : -
How to save JSON data in database
I am building a BlogApp and I am stuck on a Error. What i am trying to do :- I am trying to access user location using ipinfo AND i am trying to save city into DataBase. $.get("http://ipinfo.io", function (response) { $("#ip").html("IP: " + response.ip); $("#address").html("Location: " + response.city + ", " + response.region); $("#details").html(JSON.stringify(response, null, 4)); }, "jsonp"); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <hr/> <div id="ip"></div> <div id="address"></div> <hr/>Full Location: <pre id="details"></pre> models.py class Location(models.Model): user = models.ForeignKey(User,null=True,on_delete=models.CASCADE) city = models.CharField(max_length=30) I am new in django and I have no idea how can i save it in DataBase. Any help would be Appreciated. Thank You in Advance. -
How to stop Django from using response csrf token for the next request
I need to configure django csrf tokens such that every request has to have a new token. I put the following code inside my views: from django.middleware.csrf import rotate_token def login(request): rotate_token(request) This seems to work in changing the token for each request. The issue is that whenever I go to a new page, the request token uses the value of the response token from the previous page: My settings file: CSRF_USE_SESSIONS = False ACCOUNT_PASSWORD_EXPIRY = 60*60*24*30 ACCOUNT_PASSWORD_USE_HISTORY = True SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_DOMAIN = 'localhost' SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SAMESITE = 'Strict' X_FRAME_OPTIONS = 'DENY' PASSWORD_RESET_TIMEOUT = 720 SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_HSTS_SECONDS = 15768000 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True CSRF_COOKIE_SAMESITE = None REQUEST_LOGGING_ENABLE_COLORIZE = True SESSION_COOKIE_PATH = '/myproject' SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_AGE = 1800 How do I change my code so that the CSRF token from the request is different from the previous response? -
Django filter. What is more efficient - .filter(date__range) or .all() and filter via Python
I have quite a large database table (1M+ rows) that experiences issues when filtering results in Django. Currently the filter logic is the following: results = Result.objects.filter(date__range=(date_from, date_to)) for result in results: # do stuff On some periods it causes a crash (probably due to memory exhaustion) I am wondering, would it be more efficient replacing it with the following: results = Result.objects.all().order_by('-id') for result in results: if result.date > date_to: continue if result.date < date_from: break # do stuff In theory, since .all() creates a lazy QuerySet, it might perform better than range filtering in database with 1M+ rows. Also would be interesting to know about memory consumption in both cases. Maybe there is another solution how to do it more efficiently and in constant memory? Thanks! -
Is there a way to track state when using Django Allauth
I am trying to take advantage of allauth DefaultAccountAdapter by modifying the get_signup_redirect_url method, right now it produces nothing. Reason for this is found in the documentation: ACCOUNT_SIGNUP_REDIRECT_URL (=settings.LOGIN_REDIRECT_URL) The URL (or URL name) to redirect to directly after signing up. Note that users are only redirected to this URL if the signup went through uninterruptedly, for example, without any side steps due to email verification. If your project requires the user to always pass through certain onboarding views after signup, you will have to keep track of state indicating whether or not the user successfully onboarded, and handle accordingly. To track state, I am using session and trying to set a random session value in the SignupView. I may not be doing it correctly or have downright missed the whole point. I have tried to set it up in the dispatch method like so def dispatch(self, request, *args, **kwargs): ret = super(UserSignupView, self).dispatch(request, *args, **kwargs) self.request.session['random_id'] = 'random_value' # request.session['random_id'] = 'random_value' request.session.modified = True return ret # and was hoping to access it in my get_signup_redirect_url like this def get_signup_redirect_url(self, request): url = super(CustomAdapter, self).get_signup_redirect_url(request) if 'random_value' in request.session: url = 'new_url' # url = settings.ACCOUNT_SIGNUP_REDIRECT_URL return resolve_url(url) … -
How to send an email automatically to someone who write a new post at blog right after he create a new post
There are quite a few youtube or instructions online but I could not find anything to apply this to blog/create. What I mean by that, I would like to have email to be sent automatically to the guy who create a new post. Here is the blog/views.py below; class PostCreate(LoginRequiredMixin, CreateView): model = Post fields = [ 'title', 'content', 'head_image', 'category', 'tags' ] def form_valid(self, form): current_user = self.request.user if current_user.is_authenticated: form.instance.author = current_user return super(type(self), self).form_valid(form) else: return redirect('/blog/') I did setup settings.py like below: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'example@gmail.com' # my email address I put EMAIL_HOST_PASSWORD = '****************' # the password I put EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' I have a project to do right now... I don't have much time to review and study again... I am such a beginner... looking forward to having some help from here -
AttributeError: 'ManyToManyField' object has no attribute 'ManyToManyField'
I am trying to add multiple ManytoMany in a single model but it is showing the following error: AttributeError: 'ManyToManyField' object has no attribute 'ManyToManyField' Model: class Group(models.Model): emp = models.ForeignKey(Employee, on_delete=models.CASCADE) #try user name = models.CharField(max_length=500, default=0) models = models.ManyToManyField(GroupModels, related_name = 'models') sender_clients = models.ManyToManyField(Client, related_name = 'senderClient') receiver_clients = models.ManyToManyField(ReceiverClient, related_name = 'receiverClient') warehouses = models.ManyToManyField(Warehouse, related_name = 'warehouse') Is it not the correct way to add multiple m2m fields? Complete Traceback Traceback (most recent call last): File "c:\users\rahul sharma\anaconda3\lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\users\rahul sharma\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Rahul Sharma\PycharmProjects\packs_backend\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Rahul Sharma\PycharmProjects\packs_backend\venv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Rahul Sharma\PycharmProjects\packs_backend\venv\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\Rahul Sharma\PycharmProjects\packs_backend\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\Rahul Sharma\PycharmProjects\packs_backend\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Rahul Sharma\PycharmProjects\packs_backend\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Rahul Sharma\PycharmProjects\packs_backend\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Rahul Sharma\PycharmProjects\packs_backend\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "c:\users\rahul sharma\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen … -
How to fix cant connect my sql server 127.0.0.1 connection django google cloud refused Err 111
enter image description here Error showing cant connected mysql server on 127.0.0.1 error 111 -
Get all model instances that don't have a related model
I've got two model instances. One of them has a foreign key to another. class Color (models.Model): color_name = models.CharField(max_length=200, null=True, blank=True) class Car(models.Model): brand = models.CharField(max_length=200, null=True, blank=True) color = models.ForeignKey(Color, on_delete=models.CASCADE, null=True, blank=True) Within django, what is the most efficient way that I can find all model instances of Color that aren't related to at least one Car. -
Django content type table data migration while upgrading from 1.6 to 2.2 with legacy database
I am Upgrading my django project from version 1.6 to 2.2. I'm already having a legacy database with lot of generic relations in the project. Can anyone help to how should the django_content_type table should be populated. If I will go for new migrations, the content_type table data may be corrupted and there is chance to break all the generic relations. Should I use the same data of the django_content_type table from the exisiting db and fake the initial migrations. Will it work?? Can django handle the rest of the part? as the relations will not break? Is there any chance to occur a problem for future migrations ?? Or Is there any other method for creating entries in the tabledjango_content_type? Also, any documentation or links regarding this could possibly a great help! Thanks in Advance!!!