Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What happens when I log to stdout and stderr
I am switching my logging config in my django app away from a specific file and instead logging directly to the console (stdout & stderr) to allow the underlying system to handle, via 12 factor app. However, I am worried about pushing this to production because I cannot find an article about how my underlying system will handle the logs. I am running on Ubuntu 20.04. Is there any configuration I need to do on the server to actually capture this output? Is there any articles / resources that explain how this whole process works? Frankly right now I am rather mystified. Any help is greatly appreciated. -
Cannot assign "1": "Event.created_by" must be a "User" instance
Im stil getting errors like: Cannot assign "1": "Event.created_by" must be a "User" instance. or Cannot assign "admin": "Event.created_by" must be a "User" instance. my model: class Event(models.Model): name = models.CharField('the name of the event', max_length=255) created_at = models.DateTimeField(default=timezone.now, validators=[LessThanNowValidator()]) additional_data = models.CharField(max_length=300, blank=True, default='') created_by = models.ForeignKey(User, on_delete=models.CASCADE) class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) api_token = models.CharField(max_length=100, blank=True, null=True, unique=True) def __str__(self): return f"{self.user.username}" my view: class EventApiView(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = Event.objects.all() serializer_class = EventSerializer @action(methods=['POST'], detail=False) def post(self, request): raw = json.dumps(request.data) data = json.loads(raw) name = data.get('name') additional_data = data.get('additional_data') created_by = data.get('created_by') event_data = { 'name': name, 'additional_data': additional_data, 'created_by': created_by #also tried "request.user.username" } event = Event.objects.create(**event_data) serializer = EventSerializer(data=event_data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
pylint message: "django not configured"
I'm building a python webapp with django. When I run prospector -X on the project, I get the following error from one of the .py files Line: 1 pylint: django-not-configured / Django was not configured. For more information run pylint --load-plugins=pylint_django --help-msg=django-not-configured I've tried following: github and stackoverflow but they didn't work. prospector 1.5.1 pylint 2.11.1 astroid 2.8.3 Python 3.7.0 What should I do? -
How to get a button outside of a form to line up with button inside of form?
I feel like this is relatively simple styling, but i cant for the life of me figure out how to do it. My code: <div class="container py-5"> <div class="pull-left" style="margin-right:5px"> <form method="post"> {% csrf_token %} <p> <h3> Do you want to delete <em>"{{ entry.title }}"</em> posted on {{ entry.date_created|date:'Y-m-d' }}? </h3> </p> <button class="btn btn-danger" type="submit" value="Confirm">Confirm</button> </form> </div> <a href="{% url 'entry-detail' entry.id %}"> <button class="btn btn-secondary">Cancel</button> </a> </div> I want both the Confirm and Cancel buttons to be aligned next to eachother, but if I put the Cancel besides the Confirm button or in a div inside of the form it too performs the delete action. In Django using Bootstrap. -
Need to create required foreign key pointing to User, Django model
I need to create required field with foreign key pointing to User. Is this correct? created_by = models.ForeignKey(User, on_delete=models.CASCADE, default='') -
Django Bootstrap modal is giving an error
I am using jQuery script excecuted on an on("click") event to do following: ajax call to Django url / view that populates a 'modal' template. modal template's HTML is then appended to an empty modal div. ajax success event then does show() modal div. Everything appears to work successfully eg I get the modal to show, with populated modal template content, but I am also getting the following error: Uncaught TypeError: Illegal invocation selector-engine.js:22 at Object.findOne (selector-engine.js:22) at De._showElement (modal.js:221) at modal.js:143 at b (index.js:242) at backdrop.js:53 at b (index.js:242) at v (index.js:248) at ke._emulateAnimation (backdrop.js:125) at ke.show (backdrop.js:52) at De._showBackdrop (modal.js:328) Any ideas what is happening here? Using Bootstrap 5, jquery-3.6 Empty div: <div id="modal-div"></div> Script: var modalDiv = $("#modal-div"); $(".open-modal").on("click", function() { $.ajax({ url: $(this).attr("data-url"), success: function(data) { modalDiv.html(data); $("#photo-modal").modal('show'); }, }); }); Modal template HTML: <div id="photo-modal" class="modal-container"> <p>{{ photo.id }}</p> </div> -
How can I set custom template for change password in Django
I have template like this <form method="POST"> {% csrf_token %} {{ form }} <button>Change password</button> </form> I have a class in views.py like this class PasswordsChangeView(PasswordChangeView): form_class = PasswordChangingForm template_name = 'external/change-password.html' success_url = reverse_lazy('password_success') I have a form like this class PasswordChangingForm(PasswordChangeForm): old_password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'type' : 'password'})) new_password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'type' : 'password'})) new_password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'type' : 'password'})) class Meta: model = External fields = ['old_password', 'new_password1', 'new_password2'] I set the template name but by default it takes the django admin site for changing the password not my custom one. Can anyone help me please? -
While im trying to migration . the error showing
return getattr(self._connections[self._alias], item) File "C:\Users\mehdy\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\connection.py", line 62, in getitem conn = self.create_connection(alias) File "C:\Users\mehdy\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py", line 204, in create_connection backend = load_backend(db['ENGINE']) File "C:\Users\mehdy\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py", line 111, in load_backend return import_module('%s.base' % backend_name) File "C:\Users\mehdy\AppData\Local\Programs\Python\Python310\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "C:\Users\mehdy\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\postgresql\base.py", line 29, in raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found. PS C:\Users\mehdy\projects\mehdy> -
app running but whenever uploading file i get "Truncated or oversized response headers received from daemon process" in django
whenever i activate django logging in deployed app using apache with mod_wsgi i get Truncated or oversized response headers received from daemon process same thing happens whenever i activate logging in settings.py. this is example of the logging code LOGGING = { 'version': 1, 'loggers': { 'django': { 'handlers': ['file', 'file2', 'file3'], 'level': 'DEBUG' } }, 'handlers': { 'file': { 'level': 'CRITICAL', 'class': 'logging.FileHandler', 'filename': '../logs/debug5.log', 'formatter': 'simpleRe', }, 'file2': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '../logs/debug6.log', 'formatter': 'simpleRe', }, 'file3': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '../logs/debug7.log', 'formatter': 'simpleRe', } }, 'formatters': { 'simpleRe': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', } } } -
Getting id of instance in form and save in it
I am building a Blog App and I am working on a feature in which A user can report comment so I created another model for storing reports so i am saving which comment is reported But I placed report form in detail view so report form will be below the comment in post detail page, In which I am not getting the comment id when reporting. models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=1000) class Comment(models.Model): commented_by = models.ForeignKey(User, on_delete=models.CASCADE) body = models.CharField(max_length=1000) class ReportComment(models.Model): reported_by = models.ForeignKey(User, on_delete=models.CASCADE) reported_comment = models.ForeignKey(Comment, on_delete=models.CASCADE) text = models.CharField(max_length=1000) views.py def blog_detail_page(request, blog_id): post = get_object_or_404(Blog, pk=blog_id) if request.method == 'POST': reportform = CommentReportForm(data=request.POST) if FlagCommentForm.is_valid(): form = reportform.save(commit=False) # Saving in this line flagForm.reported_comment = reportform.id form.reported_by = request.user form.save() return redirect('home') else: reportform = CommentReportForm() context = {'reportform':reportform, 'post':post} return render(request, 'blog_detail_page.html', context) blog_detail_page.html {{post.title}} {% for comment in post.comment_set.all %} {{comment.body}} <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ reportform }} </table> <button type="submit">Save</button> </form> </div> {% endfor %} What have I tried :- I have also tried by using loop like :- comments = post.comment_set.all() for com in comments: if request.method == 'POST': ...... … -
media files getting downloaded with .html extension Django
I have a problem in Django, all the media files uploaded on the site are getting downloaded as .html despite having extensions like .mp3, .wav, .zip and .mp4. I have tried changing the content type but nothing is working. Here is my views.py: def post(self, request, pk, type, *args, **kwargs): if type == 'item': item = Item.objects.get(id=pk) item_media = ItemMedia.objects.get(item=item) #order data check if item.price != 0: if request.user.is_authenticated: orderDataCheck = OrderData.objects.filter(item=item, user=request.user) orderDataCheck_count = orderDataCheck.count() #Checking if an item is part of the purchased album try: purchase_acheck = OrderData.objects.filter(album__id=item.album.id, user=request.user, item_type='album').count() except: purchase_acheck = 0 if orderDataCheck_count > 0 or request.user.id == item.business_owner.id or purchase_acheck > 0: #Return an mp3 image_buffer = open(item_media.file.path, "rb").read() response = HttpResponse(image_buffer) response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(item_media.file.path) return response #return redirect(item.upload_file.url) else : return HttpResponse('<h4>Error, You do not have access to this product!</h4>') else: return redirect('accounts:login_page') -
How to process time consuming task in DJango?
Can anyone let me know how to process asynchronous HTTP requests in general (or in DJango specifically)? I actually have a web app which needs to generate a report in backend and output to a excel file. Its a time consuming process, and takes upto 5 minutes to be completed. I am actually new to asynchronous requests and am pretty much confused with so many jargons like message queues, message brokers, RabbitMQ, Celery.... -
Connection aborted error using Django and database code
I have a problem with Django and database postresql. I am trying to fetch some data with the following code: resultQuery=Usuario.objects.filter(correo=strmail,contrasena=strpwd) So far all is good, also I get the record count, but after a little while the server seems to disconnect and I get this error: ConnectionAbortedError: [WinError 10053] Se ha anulado una conexión establecida por el software en su equipo host When I don't use database code it seems to be fine, it only happens when I start using some database code. Thanks -
Django REST FileUpload Parser does not work with images
I am very new to Django. I am trying to develeop a web service using REST Framework. The client will send me image or pdf and I will do some image processing on this files. When i send a multipart/formdata request from Postman with attachment, pdf files are saved correctly, but images are not. views.py class FileUploadView(APIView): parser_classes = (FileUploadParser,) def post(self, request, format="file"): file_obj = request.FILES['file'] #file_name = default_storage.save(file_obj.name, file_obj) filename = 'filename' with open(filename, 'wb+') as temp_file: for chunk in file_obj.chunks(): temp_file.write(chunk) return Response(file_obj.name, status.HTTP_201_CREATED) Can you help me? What am i doing wrong? -
Finding database records that has the same date with specific timezone in django
So I have making a webpage that allows the end user to choose start date and end date. Then the reactjs frontend will send a POST request with a payload that containing the start date and end date chosen on the datepicker provided by the react-datepicker. After passing the start date and end date to the django server, I would like to group the records that have same date and come up with total number of records for each day then return a list of totals. Note that in the django server( settings.py ) has USE_TZ=true, TIME_ZONE='Asia\Kuala Lumpur'. Would like to have a list of totals in such format [ totalFirstDay, totalSecondDay, totalThirdDay, totalFourthDay, ... ] This is my current attempt to get my desired results def getTotalRecordsEachDay(request): ## for example request.POST['startDate'] == "2021-09-30T16:00:00.000Z" startDate = timezone.now().strptime(request.POST['startDate'], '%Y-%m-%dT%H:%M:%S.%fZ')+timedelta(days=1) ## for example request.POST['endDate'] == "2021-10-30T16:00:00.000Z" endDate = timezone.now().strptime(request.POST['endDate'], '%Y-%m-%dT%H:%M:%S.%fZ')+timedelta(days=2, microseconds=-1) totalFoundEachDay = [] sameDay = startDate.date() ## In Mode.py, createDate = models.DateTimeField(default=timezone.now) statistics = models.MemberCard.objects.filter(createDate__date__range=[startDate, endDate]) if len(statistics) > 0: noOfRecord=0 totalRecordsSameDay = 0 for item in statistics: noOfRecord+=1 if(sameDay == item.createDate.date()): totalRecordsSameDay+=1 if(noOfRecord == len(statistics)): totalFoundEachDay.append(totalRecordsSameDay) else: totalFoundEachDay.append(totalRecordsSameDay) sameDay = sameDay + timezone.timedelta(days=1) totalRecordsSameDay = 0 if(sameDay == item.createDate.date()): totalRecordsSameDay+=1 … -
IsADirectoryError while merging project with template Django
I'm fairly new to Django and I've been creating an app using the startproject and startapp calls but with a few tweaks based on TwoScoops' recommendations that follow cookiecutter. I was trying to now merge my work into a template provided Soft UI Dashboard that uses Bootstrap 5. Unfortunately, while doing that, I've run into a few conflicts which I have been successful at solving so far, but the one I''m stuck with right now is [Errno 21] Is a directory: '/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/jarvisai/templates/home' Here's the traceback code: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/upload/ Django Version: 3.2.8 Python Version: 3.9.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jarvisai.home', 'jarvisai.books'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/jarvisai/home/views.py", line 34, in pages html_template = loader.get_template('home/' + load_template) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/template/loader.py", line 15, in get_template return engine.get_template(template_name) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/template/backends/django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/template/engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/template/engine.py", line 125, in find_template template = … -
Sum values based on same keys in dict and make array
Hi guys I have data like this [ { 'name': 'snow 7', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 2, 'rows_processed': None, 'pipelines': 2 }, { 'name': 'snow 5', 'count': 2, 'rows_processed': 4, 'pipelines': 2 }, { 'name': 'snow 4', 'count': 2, 'rows_processed': None, 'pipelines': 2 } ] and i want to sum the values of rows_processed and pipelines based on name key like for snow 6 pipelines sum will be 4 and so on, basically the final data should look like this. { "Rows Processed": [0, 0, 4, 0], "Pipelines Processed": [1, 4, 2, 2] } how can i make data like above? this is what i have done so for rows_processed = {} pipeline_processed = {} for batch in batches: for label in batches.keys(): rows_processed[label] = rows_processed.get(batch['rows_processed'], 0) + batch['rows_processed'] if batch['rows_processed'] else 0 for batch in batches: for label in batches.keys(): pipeline_processed[label] = pipeline_processed.get(batch['pipelines'], 0) + batch['pipelines'] if \ batch['pipelines'] else -
Display django intergerfield model as dropdown select with range min and max values for each option (django-filters)
Hi trying to display this model class Item(models.Model): number = models.IntegerField() like this: dropdown I am using django-filters and have the following filters.py file: class ItemFilter(django_filters.FilterSet): number = django_filters.RangeFilter() class Meta: model = Item fields = ['number'] The above works great for showing a range but I have to enter the min and max values manually What I would like to do is set predefined options with values for the min and max range of the RangeFilter Ideally, if I could set values into the below html that would be great <select data-style="btn-white" class="selectpicker"> <option>0-10</option> <option>10-50</option> <option>100-250</option> <option>250-500</option> <option>500-1000</option> <option>1000-2000</option> <option>2000+</option> </select> Any ideas would be appreciated -
Javascript- how to show table row based on checkbox
I want to display the table row based on the checkbox selection where I need to display only the particular row. I'm noob in JavaScript how could I able to achieve it. I Have tried many javascript snippet from the stackoverflow as well but it didn't worked as expected.pls.help me out to get this.Thanks in advance Here is my html <div>Country</div> <div class="row" name="country_checkbox" id="id_row" onclick="return filter_type(this);"> <ul id="id_country"> <li><label for="id_country_0"><input type="checkbox" name="country" value="NORTHAMERICA" placeholder="Select Country" id="id_country_0"> NORTHAMERICA</label> </li> <li><label for="id_country_3"><input type="checkbox" name="country" value="LATAM" placeholder="Select Country" id="id_country_3"> LATAM</label> </li> <li><label for="id_country_2"><input type="checkbox" name="country" value="ASIA" placeholder="Select Country" id="id_country_2">ASIA</label> </li> </ul> </div> <table class="datatable" id='table_id'> <thead> <thead> <tr> <th>Region</th> <th> Area </th> <th> Country </th> </tr> </thead> <tbody> <tr id="trow"> {% for i in database%} <td>i.Region</td> <td>i.Area </td> <td>i.Country</td> {% endfor %} </tr> </tbody> -
Sum values of same keys from dict and make array [closed]
Hi guys I have data like this [ { 'name': 'snow 7', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 2, 'rows_processed': None, 'pipelines': 2 }, { 'name': 'snow 5', 'count': 2, 'rows_processed': 4, 'pipelines': 2 }, { 'name': 'snow 4', 'count': 2, 'rows_processed': None, 'pipelines': 2 } ] and i want to sum the values of rows_processed and pipelines based on name key like for snow 6 pipelines sum will be 4 and so on, basically the final data should look like this. { "Rows Processed": [0, 0, 4, 0], "Pipelines Processed": [1, 4, 2, 2] } how can i make data like above? this is what i have done so for rows_processed = {} pipeline_processed = {} for batch in batches: for label in batches.keys(): rows_processed[label] = rows_processed.get(batch['rows_processed'], 0) + batch['rows_processed'] if batch['rows_processed'] else 0 for batch in batches: for label in batches.keys(): pipeline_processed[label] = pipeline_processed.get(batch['pipelines'], 0) + batch['pipelines'] if \ batch['pipelines'] else -
str' object has no attribute 'get Django Python
Now I have one more problem. Could you please help? Thank You in advance :) An error: AttributeError: 'str' object has no attribute 'get'. . And the code password_form = PasswordsForm(request.POST or None) if password_form.is_valid(): password = password_form.save() try: for i in password.text: value = (alphabet[i]) klucz = 10 new_value = int(value) + klucz if new_value > 70: new_value = new_value - 70 for key, value in alphabet.items(): if value == str(new_value): print(key, end='') return '' except KeyError: return ('Nie znaleziono wartości' + i + ' w słowniku!') return render(request,'kod.html', {'key': key}) return render(request, 'start.html', {'password_form': password_form}) ``` I would be grateful for answer ! Natalia -
ImportError: attempted relative import with no known parent package DJANGO
I am following a tutorial on how to work with django and i cant figure out what this error happens. This is Admin.py from django.contrib import admin from .models import Genre, Movie class GenreAdmin(admin.ModelAdmin): list_display = ('id', 'name') admin.site.register(Movie) admin.site.register(Genre, GenreAdmin) and this is models.py: from django.db import models from django.utils import timezone class Genre(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Movie(models.Model): title = models.CharField(max_length=255) release_year = models.IntegerField() number_in_stock = models.IntegerField() daily_rate = models.FloatField() genre = models.ForeignKey(Genre, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) There are in the same parent folder. -
How to override existing '/api/products/' to return more fields in Django-osacr-api?
Django-oscar-api-override setup I am new to Oscar Api, And I need to added extra fields to the default '/api/products' response. Additional fields to add: description, meta_title, meta_description, rating, attributes from oscar.core.loading import get_class from rest_framework import serializers from oscarapi.serializers import checkout, product from oscarapi.serializers.product import ( ProductImageSerializer, ProductLinkSerializer) class MyProductLinkSerializer(ProductLinkSerializer): images = ProductImageSerializer(many=True, required=False) class Meta(ProductLinkSerializer.Meta): fields = ('url', 'id', 'title', 'images', 'rating', 'meta_title', 'meta_description') I tried the above code from documentation to see if it overrides. But no luck. Can you please help to add additional fields to the default response ? or point me any sample project repo where you they overrided default response. Thank you in advance. -
'undefined likes' twitter like project
Recently I started working on a twitter like clone to learn some python and django. I have successfully added "tweets" and got them to display some basic text on my homepage. My issue is with the like button. I am attempting to have a like button that will display the total amount of likes on that "tweet". For now I am using a random int just to display the likes. However the button just displays "undefined Likes". I thought it was going to be pretty straight forward however i am still new to all this so any help pointing me in the right direction would be appreciated. Thanks all. views.py: import random from django.http import HttpResponse, Http404, JsonResponse from django.shortcuts import render from .models import Prediction # Create your views here. def home_view(request, *args, **kwargs): return render(request, "pages/home.html", context={}, status=200) def prediction_list_view(request, *args, **kwargs): """ REST API VIEW Consume by JavaScript or Swift/Java/iOS/Andriod return json data """ qs = Prediction.objects.all() predictions_list = [{"id": x.id, "content": x.content, "likes": random.randint(0, 122)} for x in qs] data = { "isUser": False, "response": predictions_list } return JsonResponse(data) def prediction_detail_view(request, prediction_id, *args, **kwargs): """ REST API VIEW Consume by JavaScript or Swift/Java/iOS/Andriod return json data … -
TypeError: object of type 'Listeningfilter' has no len()
this error appear when using django-filter with pagination. this my filter.py, view.py code. I need to add pagination to django-filter I display data in html table. the error appear in this Listening_filter = paginator.get_page(page_number) line. class Listeningfilter(django_filters.FilterSet): listentime = django_filters.DateFromToRangeFilter( label='By Date Range', method='filter_by_range', widget=RangeWidget(attrs={'class': 'datepicker', 'type': 'date'}) ) class Meta: model = Listening fields = [ 'listentime', 'serviceshortcode', ] def filter_by_range(self, queryset, name, value): listenTime_from = value.listenTime_from listenTime_to = value.listenTime_to return queryset.filter(transaction_time__gte=listenTime_from, transaction_time__lte=listenTime_to) def listeningReportView(request): Listening_filter = '' form = ListeningSearchForm(request.POST or None) if request.method == 'POST': listenTime_from = request.POST.get('listenTime_from') listenTime_to = request.POST.get('listenTime_to') serviceCode = request.POST.get('serviceCode') Listening_filter = Listeningfilter( request.GET, queryset = Listening.objects.filter(listentime__lte=listenTime_to, listentime__gte=listenTime_from, serviceshortcode=serviceCode).order_by('listeningid'), ) # pagination paginator = Paginator(Listening_filter , 2) page_number = request.GET.get('page') try: Listening_filter = paginator.get_page(page_number) except EmptyPage: Listening_filter = paginator.page(paginator.num_pages) if not Listening_filter: messages.error(request, "no data availabe") context = { 'form': form, 'Listening_filter': Listening_filter, } return render(request, 'charge/listening.html', context)