Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I improve this Django query?
I have this Django query which is taking several minutes to run. stat_type = 'Some String' obj = xxx # some brand object query = Q( Q(stat_type__icontains=stat_type) & Q(Q(brand=obj) | Q(organisation__in=obj.organisation_set.active()))) result = ViewStat.objects.filter(query).aggregate(one=Count('id', filter=Q(created__gte=timezone.now() - relativedelta(months=int(1)))), \ three=Count('id', filter=Q(created__gte=timezone.now() - relativedelta(months=int(3)))), twelve=Count('id', filter=Q(created__gte=timezone.now() - relativedelta(months=int(12)))), all=Count('id', filter=Q(created__gte=timezone.now() - relativedelta(months=int(999))))) Models class Brand(models.Model): ... class Organisation(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) ... class ViewStat(models.Model): stat_type = models.CharField(max_length=21) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, blank=True, null=True) organisation = models.ForeignKey(Organisation, on_delete=models.SET_NULL, blank=True, null=True) I have roughly 80k Organisations, 700 Brands and 10 million ViewStats. How can I improve query performance? -
How to convert png to jpeg with pillow in django?
I want that when users upload a png image it converts to jpeg before saving it into the database. if it is in another format then do not need to convert. I write this code but this not converting png to jpeg. from io import BytesIO from PIL import Image from django.core.files import File def compress(image): im = Image.open(image) # create a BytesIO object im_io = BytesIO() # save image to BytesIO object if im.format == "RGB": iim = im.convert("RGB") iim.save(im_io,"JPEG", quality=70) else: im.save(im_io,im.format, quality=70) # create a django-friendly Files object new_image = File(im_io, name=image.name) return new_image where I'm wrong. -
Django Error - django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
i get the following error: , line 140, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. I'm not sure why this is happening. The variables created for the choices are created before calling them so I don't think its the order of the model classes. Can anyone please help? models.py from django.db import models from model_utils import Choices from datetime import date # Create your models here. class GeoChoice(models.Model): country = models.CharField(max_length=50) region = models.CharField(max_length=50) subRegion = models.CharField(max_length=50) class ChannelChoice(models.Model): channel = models.CharField(max_length=50) subChannel = models.CharField(max_length=50) class CreationConversionChoice(models.Model): creation_conversion = models.CharField(max_length=50) class SpendStatusChoice(models.Model): spendStatus = models.CharField(max_length=50) class SpendTypeChoice(models.Model): spendType = models.CharField(max_length=50) class Year(models.Model): year = models.IntegerField() REGION = [(i,i) for i in GeoChoice.objects.values_list('region', flat=True).distinct()] SUBREGION = [(i,i) for i in GeoChoice.objects.values_list('subRegion', flat=True).distinct()] COUNTRY = [(i,i) for i in GeoChoice.objects.values_list('country', flat=True).distinct()] CHANNEL = [(i,i) for i in ChannelChoice.objects.values_list('channel', flat=True).distinct()] SUBCHANNEL = [(i,i) for i in ChannelChoice.objects.values_list('subChannel', flat=True).distinct()] CREATION_CONVERSION = [(i,i) for i in CreationConversionChoice.objects.values_list('creation_conversion', flat=True).distinct()] SPENDSTATUS = [(i,i) for i in SpendStatusChoice.objects.values_list('spendStatus', flat=True).distinct()] SPENDTYPE = [(i,i) for i in SpendTypeChoice.objects.values_list('spendType', flat=True).distinct()] MONTHS = [(1, 'Jan'), (2, 'Feb'), (3, 'Mar'), (4, 'Apr'), (5, 'May'), (6, 'Jun') ,(7, 'Jul'), (8, 'Aug'), (9, 'Sep'), (10, 'Oct'), (11, 'Nov'), (12, 'Dec')] … -
Django/admin form: how to initialize data with username (access to request object)?
I want to cutsomize admin forms but I am lost below my code I want to initialize pro_log with username of user connected but failed to access request object Which method I should overide and how can I get request object I've read I should override save_model or save_form methods of Modeladmin that return object but how to do that to get access to user in ModelForm? class ProjetFormAdmin(forms.ModelForm): OUINON = Thesaurus.options_list(1,'fr') pro_nom = forms.CharField(label="Nom du projet") pro_log = forms.CharField(label="Log utilisateur", initial='') pro_act = forms.TypedChoiceField(label="Projet en cours ?", widget = forms.Select, choices = OUINON, required=False, empty_value=None) class ProjetAdmin(SimpleHistoryAdmin): list_display = ('pro_nom','pro_log', 'pro_act',) form = ProjetFormAdmin -
Django transactions: how to run lots of sql query in the save mehod
I want to save more them 100 rows in my MySQL database, I have seen that experienced people are saying to use Django transactions. I'm using Django 3, wanted to know how to rite it and any resource that can help. in my views.py I have used from Django.db import transaction D is small in the code @transaction.commit_manually def single_user_images(request, *args, **kwargs): if request.method == 'GET' and username: # I want to save the details here # Receive the data else: #code Please describe with an example if u have. Thanks. -
Django 2.0.13 -> 2.1 upgrade causes std library function to not find module (AttributeError)
Upgrading Django 2.0.13 -> 2.1.0 (or greater) causes the following error when calling runserver, migrate etc. On Django 2.0.13 (and any lower) does not throw this error. Traceback (most recent call last): File "/usr/lib/python3.6/logging/config.py", line 390, in resolve found = getattr(found, frag) AttributeError: module 'mysite' has no attribute 'mymodule' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/logging/config.py", line 565, in configure handler = self.configure_handler(handlers[name]) File "/usr/lib/python3.6/logging/config.py", line 715, in configure_handler klass = self.resolve(cname) File "/usr/lib/python3.6/logging/config.py", line 393, in resolve found = getattr(found, frag) AttributeError: module 'mysite' has no attribute 'mymodule' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/me/mysite/manage.py", line 20, in <module> execute_from_command_line(sys.argv) File "/home/me/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/me/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/me/venv/lib/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/me/venv/lib/python3.6/site-packages/django/utils/log.py", line 76, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python3.6/logging/config.py", line 802, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python3.6/logging/config.py", line 573, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'console': module 'mysite' has no attribute 'mymodule' This error is thrown in class BaseConfigurator(object): The same issue is also with python3.8 Tracing the error to settings.py -> LOGGING LOGGING … -
django construct condition in save model
I have Contact model and I want to construct it to have only 1 record with field is_active=True. but I don't want to raise error, I want it to notify me and don't save the record if there is an contact record with is_active=True before. "Contact can't have more than 1 active contact at same time." class Contact(models.Model): name = models.CharField(max_length=30) is_active = models.BooleanField(blank=True) def save(self, *args, **kwargs): if self.is_active: if Contact.objects.filter(Q(is_active=True), ~Q(id=self.id)): // raise ValidationError("Contact can't have more than 1 active contact at same time.") return super(Contact, self).save(*args, **kwargs) -
How can I store my static files to some other github repo?
I am doing a Django Project and I want to store some files (which should be accessible from the project w,r) to some github project as I don't want to store the files and the projects in the same repo. Any suggestion of doing that? -
Django IntegrityError: Key is not present in table (but query of key works)
I have a strange problem with Django tests. The issue only occurs when I ran the test command python3 manage.py test. Background information: I have a subscription model with a custom save method which sends info mails, create bills and lessons and more. After the subscription is saved into the database with the super().save(using=using, *args, **kwargs) command, the method self.create_lessons() get's called and this method causes the IntegrityError on creation of the lessons, saying that the subscription doesn't exists in the table. To check if the subscription really doesn't exists in the subscription table I have added a query s = Subscription.objects.get(id=self.id) and printed it to the console print(s). The query and the print command are working fine, but i still get the integrity error. Whats really confusing, at least for me, is that the error only occurs when I run the python3 manage.py test command. When I run the webserver and create subscriptions with the admin panel or the shell everything is running like it should. Even stranger is that the error disappears for a while (2-3 successful executions of the test command) when I make a change to the code which doesn't really matter. For example a comment … -
Couldnt spawn debuggee: embedded null byte error
I'm developing a Django project. When I try to debug this project via VS Code, I get the following error. E+00000.046: /handling #1 request "launch" from Adapter/ Handler 'launch_request' (file '/Users/dervisoglu/.vscode/extensions/ms-python.python-2020.5.86806/pythonFiles/lib/python/debugpy/wheels/debugpy/launcher/../../debugpy/launcher/handlers.py', line 18) couldn't handle #1 request "launch" from Adapter: Couldn't spawn debuggee: embedded null byte How can I sollve this error ? -
Call popup delete modal using django DeleteView()
I am trying pop up delete message using bootstrap4 modal. But the page is loading as a normal page not a modal form.The modal is in employee_delete.html file and modal trigger button is in employee_list.html file. Somehow i think my javascript is not working. employee_list.html: the modal delete button is in this html file {% extends "base.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> <div class=""> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-6"> <h2><b>Employees</b></h2> </div> <div class="col-sm-6"> <a href="{% url 'employee:employee-add' %}" class="btn btn-success" data-toggle="modal"> <span ></span> <i class="material-icons"></i> <span data-feather="plus"></span>Add New Employee </a> <!--<a href="#deleteEmployeeModal" class="btn btn-danger" data-toggle="modal"><i class="material-icons">&#xE15C;</i> <span>Delete</span></a>--> </div> </div> </div> <table class="table table-striped table-hover"> <thead> <tr> <!-- Table header--> <th> <span class="custom-checkbox"> <input type="checkbox" id="selectAll"> <label for="selectAll"></label> </span> </th> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Department</th> <th>Designation</th> <th>Email</th> <th>Address</th> <th>Phone</th> <th>Actions</th> </tr> </thead> <tbody> <!-- Loop for showing employee list in a table--> {% for employee in employees %} <tr> <td> <span class="custom-checkbox"> <input type="checkbox" id="checkbox1" name="options[]" value="1"> <label for="checkbox1"></label> </span> </td> <td>{{employee.e_id}}</td> <td>{{employee.first_name}}</td> <td>{{employee.last_name}}</td> <td>{{employee.department}}</td> <td>{{employee.designation}}</td> <td>{{employee.email}}</td> <td>{{employee.address}}</td> <td>{{employee.phone_number}}</td> <td> <a href="{% url 'employee:employee-update' employee.id %}" class="edit" data-toggle="modal"> <i class="material-icons" data-toggle="tooltip" title="Edit"></i> <span data-feather="edit-2"></span> </a> <a href="{% … -
Error while extending on 500 error django custom view
I'm triying to define a custom 500 error for my django app by just placing my 500.html file in the templates folder. {% extends "base.html" %} {% load static %} {% block body %} <div class="container"> <div class="row"> UPS, algo fue mal. </div> </div> {% endblock %} Whitout the first line( extending the skeleton of the web) it works, but with it i got this meesage: A server error occurred. Please contact the administrator. I'm dooing the exact same thing for the 404 errors, and I works perfectly. I'm completly lost here. -
SQL Query to Django Query
I'm trying to figure out how can I convert below SQL query into Django query select main_project.name, (main_contacts.first_name) as Name, group_concat(main_property.property_id) as Properties, sum(main_property.area), (main_contacts.first_name||main_project.name) as CONPROP from main_project INNER join main_property on main_property.project_id = main_project.id INNER join main_property_owner ON main_property_owner.property_id = main_property.id INNER JOIN main_contacts ON main_contacts.id = main_property_owner.contacts_id group by CONPROP models.py class Contacts(models.Model): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15, null=True, blank=True) mobile = models.CharField(max_length=10, unique=True) email = models.EmailField(unique=True, null=True, blank=True) def __str__(self): return f'{self.first_name} - {self.mobile}' class Project(models.Model): name = models.CharField(max_length=100) address = models.ForeignKey(Address, on_delete=models.CASCADE) def __str__(self): return self.name class Property(models.Model): added_on = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='creator', limit_choices_to={'is_staff': True}) property_id = models.CharField(max_length=10, unique=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='properties') owner = models.ManyToManyField(Contacts, blank=True) area = models.DecimalField(max_digits=20, decimal_places=2) internal = models.TextField(null=True, blank=True) external = models.TextField(null=True, blank=True) def __str__(self): return self.property_id I've learned that it will be done using 'annotate' but somehow I'm unable to do it. -
Django / Ubuntu 20 - How change to a previous version of GDAL
first of all, thanks for your help. I'm new to django, and I'm developing a site where you have to enter coordinates in some forms and then they should be editable. So far, so good, I haven't had any problem creating that, however, as I read, in some of the more recent versions, the order in which GDAL reads the coordinates was changed, so the positions appear inverted when reading data from geospatial databases. In other words, the coordinates are entered right (from PgAdmin they look right) but are read wrong when you load them into a leaflet map with Django. I asked about how to correct this (Link to my previous question) but got no answer and haven't been able to solve it myself. Therefore, the only thing I can think of is to try with previous versions of GDAL, however, I'm not quite sure how to do it. I followed the next steps to install it: pip3 install gdal sudo apt-get install gdal-bin libgdal-dev sudo apt-get install python3-gdal Thanks in advance -
Unable to import modules from aws lambda layer
I have a requirements file for my pip packages. I installed it in a target folder and zipped the contents and uploaded it on AWS lambda layer. Requirements.txt asgiref==3.2.3 certifi==2019.11.28 chardet==3.0.4 cloudevents==0.2.4 decorator==4.4.1 Django==3.0 idna==2.8 jaeger-client==4.2.0 jsonpath-ng==1.4.3 pbr==5.4.4 ply==3.11 pytz==2019.3 requests==2.22.0 six==1.13.0 sqlparse==0.3.0 urllib3==1.25.7 aws-xray-sdk mysql-connector-python gunicorn After this I made a dummy lambda function to check if the layer is working or not. import json import django def lambda_handler(event, context): # TODO implement return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') } I get the error: Unable to import module 'lambda_function': No module named 'django' -
Django manager annotate first element of m2m as fk
Let's say I have these models. class AdventureWaypoint(models.Model): adventure = models.ForeignKey("Adventure", on_delete=models.CASCADE) waypoint = models.ForeignKey("Waypoint", on_delete=models.CASCADE) created_timestamp = models.DateTimeField(auto_now_add=True) class Waypoint(models.Model): name = models.CharField(max_length=255) class Adventure(models.Model): waypoints = models.ManyToManyField("Waypoint", through='AdventureWaypoint', related_name='waypoints') objects = AdventureManager() How could I write a manager that annotates first_waypoint to every queryset? I tried the following, but unfortunately Subquery doesn't work as expected. Couldn't use F as well. class AdventureManager(models.Manager): def get_queryset(self): qs = super(AdventureManager).get_queryset() first_waypoint = AdventureWaypoint.objects.filter(adventure_id=OuterRef("id")).order_by('created_timestamp').first().waypoint return qs.annotate(first_waypoint=Subquery(first_waypoint, output_field=models.ForeignKey("Waypoint", on_delete=models.CASCADE, null=True, blank=True))) Do I have to resort to raw SQL or how can this be done via Django ORM? -
I will not let anyone enter my backend URL - Django rest framework
This problem I want to know how to secure my back and request a URL. At first, I didn’t put any authcation on my project. Now what I want to do is aunt - if anyone visits my URL, I will not let them see that page. Can anyone help with this? -
Django forms render error messages below input field?
How do I render error messages in django forms as "This field is required" if form is submitted blank. This is my forms.py class StudentForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class StudentExtraForm(forms.ModelForm): class Meta: model = models.Student fields = ['classes', 'roll', 'blood_group', 'phone', 'dob', 'gender', 'address', 'status', 'image'] def __init__(self, *args, **kwargs): super(StudentExtraForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' This is form.html <form class="forms-sample" action="{% url 'student:add_student' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form1.non_field_errors }} {{ form2.non_field_errors }} <div class="form-group"> {{ form1.first_name.errors }} <label for="{{ form1.first_name.id_for_label }}">First Name:</label> {{ form1.first_name }} </div> <div class="form-group"> {{ form1.last_name.errors }} <label for="{{ form1.last_name.id_for_label }}">Last Name:</label> {{ form1.last_name }} </div> <div class="form-group"> {{ form1.username.errors }} <label for="{{ form1.username.id_for_label }}">Username:</label> {{ form1.username }} </div> <div class="form-group"> {{ form1.email.errors }} <label for="{{ form1.email.id_for_label }}">Email:</label> {{ form1.email }} </div> <div class="form-group"> {{ form1.password.errors }} <label for="{{ form1.password.id_for_label }}">Password:</label> {{ form1.password }} </div> <div class="form-group"> {{ form2.classes.errors }} <label for="{{ form2.classes.id_for_label }}">Select Class:</label> {{ form2.classes }} </div> <div class="form-group"> {{ form2.roll.errors }} <label for="{{ form2.roll.id_for_label }}">Roll No:</label> {{ form2.roll }} </div> <div class="form-group"> … -
Why does PyCharm show an empty Django Model Dependency Diagram
The PyCharm Pro IDE has a convenient feature called a Django Model Dependency Diagram, which visualizes the relations between your Django models. However, every so often, this diagram turns up blank, or does not work at all, without any error messages (except in the logs). There's a related issue here: https://youtrack.jetbrains.com/issue/PY-39831 What could possibly cause the Django Model Dependency Diagram to turn up empty? -
Delete firebase token not accepting token in parameters
I created an endpoint on my API to DELETE a firebase token. The token is given in parameters. This is my test unit, that works fine: @patch("pyfcm.FCMNotification.clean_registration_ids") def test_delete_firebase_token(self, fcm_mock): fcm_mock.return_value = "thetokengeneratedbyfirebase" token = "dummytoken" # create token FirebaseConnectionFactory(user=self.author, token=token) # delete token url = reverse("user-firebase", kwargs={"user_pk": self.author.pk}) response = self.client.delete(url, data={"token": token,}, format="json",) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIsNone( FirebaseConnection.objects.filter( token=token, user_id=self.author.pk ).first() ) This is my view: def delete(self, request, user_pk): """ Delete Firebase token. """ user = request.user if int(user.pk) != int(user_pk): raise PermissionDenied serializer_class = self.get_serializer_class() serializer = serializer_class(data=request.data, context={"user_pk": user_pk}) serializer.is_valid(raise_exception=True) token = serializer.validated_data.get("token") FirebaseConnection.objects.filter(token=token, user_id=user_pk).delete() return Response({}, status=status.HTTP_200_OK) serializer: class FirebaseDeleteSerializer(serializers.ModelSerializer): class Meta: model = FirebaseConnection fields = ("token",) # noinspection PyMethodMayBeStatic def validate_token(self, token): user_pk = self.context["user_pk"] validate_token_helper(token) if not FirebaseConnection.objects.filter(token=token, user_id=user_pk).exists(): raise serializers.ValidationError( "You don't have permission to perform this action." ) return token So when I try this endpoint, I can't give the token in parameters. It gives an error that it's not valid. I guess that's because the ':' symbol in string? But I'm not sure how to solve it properly. Validation says I'm not sending token at all. -
Wagtail: How to remove summary items on the admin homepgae
I am trying to remove/customize the summary items on the admin homepage with the recommended hook construct_homepage_summary_items. Add or remove items from the ‘site summary’ bar on the admin homepage (which shows the number of pages and other object that exist on the site). I manage to add my own items but struggle to remove all of the default items. @hooks.register("construct_homepage_summary_items") def add_my_summary_items(request, items): items.append(MySummaryItem(request)) items.pop(0) items only includes my custom items and wagtail.admin.site_summary.PagesSummaryItem but not those for images and documents. Removing items with pop doesn't seem to be as elegant as it could be either. I hoped for some way along the lines of the construct_main_menu hook: menu_items[:] = [item for item in menu_items if item.name != 'explorer'] But I could not find a name identifier or an equivalent. How would I go on about it? -
Multiple objects returned in Django
So I have my code below, whenever I run it in admin and try to view that object returns and error: Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one c2 -- it returned 2! How do I resolve this error? models.py: from django.db import models import datetime import pytz from django.utils import timezone class c1(models.Model): name = models.CharField(max_length=30, default="Other") def __str__(self): return self.name class c2(models.Model): c1 = models.ForeignKey(c1, on_delete=models.CASCADE) name = models.CharField(max_length=30, default="Other") def __str__(self): return self.name class c3(models.Model): c2 = models.ForeignKey(c2, on_delete=models.CASCADE) name = models.CharField(max_length=30, default="Other") def __str__(self): return self.name class Task_manager(models.Manager): def create_Task(self, title): Task1 = self.create(title=title) return Task1 class Task(models.Model): STATUS = ( ('ONGOING', 'ONGOING'), ('COMPLETED','COMPLETED'), ) search=models.CharField(max_length=300, choices=search_title, default="OTHER") c1=models.ForeignKey(c1, on_delete=models.SET_NULL, null=True) c2=models.ForeignKey(c2, on_delete=models.SET_NULL, null=True) c3=models.ForeignKey(c3, on_delete=models.SET_NULL, null=True) title=models.CharField(max_length=30,default="Other") created=models.DateTimeField(default=timezone.now()) objects=Task_manager() class Meta: ordering = [ '-created'] def __str__(self): return self.title -
Like button without refreshing a Page using jQuery in Django
I have a view that controls my like and dislike functions perfectly. But I want a scenario were authenciated users can like a page without refreshing the whole Page. Here's my code for better understanding... Thanks in advance My View: def like_post(request): user = request.user if request.method == "POST": post_id = request.POST.get('post_id') post_obj = Blog.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value=='Like': like.value='Dislike' else: like.value = 'Like' like.save() return redirect('blog') Models: LIKE_CHOICES = { ('Like', 'Like'), ('Dislike','Dislike') } class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,blank=True) post = models.ForeignKey(Blog, on_delete=models.CASCADE,blank=True) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=15) def __str__(self): return self.user My HTML Html <div class="like-section"> {% if request.user.is_authenticated %} <form action="{% url 'like_post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" value="{{blog.id}}"> {% if user not in blog.liked.all %} <button class="btn btn-sm btn-info" id="like" type="submit"><i class="fas fa-thumbs-up"></i></button> {% else %} <button class="btn btn-sm btn-info" id="like" type="submit"><i class="fas fa-thumbs-down"></i> </button> {% endif %} </form> {% endif %} </div> <small class="like-count{{blog.id}}">{{blog.liked.all.count}} Likes</small> And lastly my jQuery: <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(); var post_id = $(this).attr('value'); $.ajax({ type:'POST', url: '{% url "like_post" %}', data:{'id':post_id, 'csrfmiddlewaretoken':'{{csrf_token}}'}, success: function(data){ $('#like-section').html(data) } }); }); }); </script> I still … -
KeyError in BaseInlineFormset django
i'm trying to show error message in my formset , and i override clean method in baseinlineformset but it raise this error KeyError at /template/template-name/ 'quantity' class MyBaseInlineFormSet(BaseInlineFormSet): def clean(self): super(MyBaseInlineFormSet, self).clean() for form in self.forms: product = form.cleaned_data['product'] qnt = product.quantity_storage quantity = form.cleaned_data['quantity'] if quantity > qnt: print(f'quantity : {quantity} qnt : {qnt} test') #this show: (quantity : none 3 : test why quantity will bo none !? raise forms.ValidationError('you not have enough products') MyCustomInlineFormSet = inlineformset_factory( Parent,Child,form=ChildForm,formset=MyBaseInlineFormSet,extra=1) i also tried to display the massage from my form class def clean_quantity(self): product= self.cleaned_data.get('product') qnt = product.quantity_storage quantity = self.cleaned_data.get('quantity') if quantity > qnt: raise forms.ValidationError('you not have enough products') return quantity but the massage will show only if my parent class has an error ! and this is my views.py def get_context_data(self,*args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['formset'] = MyCustomInlineFormSet(self.request.POST) data['formset'].full_clean() else: data['formset'] = MyCustomInlineFormSet() return data def form_valid(self,form): context = self.get_context_data() formset= context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid() and form.is_valid() and formset.cleaned_data!={}: formset.instance = self.object formset.save() return super().form_valid(form) i also called the error massage in my template in this format {% if formset.quantity.errors %} <div class="error mx-auto"> {{formset.quantity.non_field_errors}} {{formset.quantity.errors}} </div> {% endif %} is there … -
Django File update not saving to folder
I am trying to update a form in which there is a input type file. But while saving the changes, name of the file is updated to database (MySQL) but not storing in folder. While uploading for the first time it works perfectly. upload_to option of FileField in modals is working fine and file is uploading to that upload_to path. But When I am trying to update the file, only file name name is updating to database. I can't share complete code due to non disclosure agreement with client. Few other fields are also there in form and everything is updating in database correctly. Only file is not uploading to specified path. Any help is appreciated. I tried many solutions available but none of them are working. Models.py Class Task(models.Model): attached_resources = models.FileField(upload_to='project/images/task/',default='') edit-task.html <form method="post" action="/app/task-detail/" enctype="multipart/form-data"> {% csrf_token %} <input name="task_file" type="file"> </form> views.py def task_detail(request): if request.method == 'POST': task_id = request.POST['task_id'] task_file = request.FILES['task_file'] task_to_edit = Task.objects.filter(id=task_id).update(attached_resources=task_file)