Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I perform save on all records in Django?
In one of my models I want to add a field that depends on other fields of the same model and will be calculated when the record is saved. In my database there are already records, so I thought that I could accomplish this by performing save. I have tried save on a single record and it seems to work. For more records can I use a loop like this: for each_product_record in Product.objects.all(): each_product_record.save() Is there a better way or are there any caveats I should know before hand ? -
Django admin change_view not called
I'm trying to redefine a ModelAdmin for a model in this way: class MakeModelAdmin(admin.ModelAdmin): ... # def changeform_view(self, request, object_id, form_url='', extra_context=None): # if not request.user.is_superuser: # self.exclude = ('company',) # extra_context = extra_context or {} # return super().changeform_view(request, object_id, form_url, extra_context=extra_context,) def change_view(self, request, object_id, form_url='', extra_context=None): if not request.user.is_superuser: self.exclude = ('company',) extra_context = extra_context or {} return super().change_view(request, object_id, form_url, extra_context=extra_context,) admin.site.register(Make, MakeModelAdmin) But method change_view is not called. At the same time, the commented code changeform_view is called. I checked and ModelAdmin contains both of methods. I can't figure out why "change_view" is not called where "changeform_view" is called (obviously when uncommented). Documentation suggests change_view: https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.change_view I'm using Django 2.0.2 -
How to raise multiple ValidationError on Django?
from rest_framework.exceptions import ValidationError def to_representation(self, request_data): raise ValidationError({ 'field_name': ["Field not allowed to change"] }) In the example above how can I throw multiple validation errors? I want to throw them as dicts to show at the respective fields. -
KeyError when trying to compress image using PIL
I'm trying to compress uploaded images using PIL for quicker uploads. Here's my views: print(instance.image) #prints "imagename.jpg" instance.image = Image.open(instance.image) print(instance.image) #prints "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3190x2159 at 0x10EE73A20>" instance.image.thumbnail((220, 130), Image.ANTIALIAS) print(instance.image) #prints "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=193x130 at 0x10EE73A20>" instance.image.save(instance.image, quality=60) that last line sparks the error. Traceback: File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/zorgan/Desktop/project/site/post/views.py" in post 55. instance.image.save(instance.image, quality=60) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/PIL/Image.py" in save 1713. format = EXTENSION[ext] Exception Type: KeyError at /post/ Exception Value: '' Any idea what the problem is? -
Django Suit - Django CMS 3.5 compatibility
I have a project built on Django 1.11 with Django CMS 3.5 for content management, but I would like to have Django Suit as the front end part of my admin. The problem is that Suit doesn't support Django CMS since version 2.4 and a lot of the functionalities that it adds to the admin don't work anymore. More specifically, the pages and content management view. I've been trying to fix the issues but haven't been able to find a way to make it work properly. Does anyone know how to get this done or if there's any other alternative that can give me the ui and features like Django Suit and that is compatible with Django CMS 3.5? -
Slugified subpages lead to NoReverseMatch
Still very new to Django. I am trying to create a website, where users can have profiles, and then profiles can have trip titles, e.g. site.com/user1/short-trip-to-canada I managed to display site.com/user1, and (after adding some additional code) I managed to display site.com/user/short-trip-to-canada separately. But in the latter case, if I go to site.com/user1, then i get the following error: NoReverseMatch at /app/hellothere/ Reverse for 'view_trip' with arguments '('chad-and-a-cheerful-anthem',)' not found. 1 pattern(s) tried: ['app/(?P<username>[\\w\\-]+)/(?P<trip_name_slug>[\\w\\-]+)/$'] I have been trying to figure out why, for a while. My views.py: @login_required def view_profile(request,username): user = get_object_or_404(User, username__exact=username) profile = get_object_or_404(UserProfile, user__exact=user) trips = Trip.objects.filter(owner=user).order_by('startDate').reverse() context_dict = {'user':user, 'trips':trips, 'profile':profile } return render(request,'view_profile.html',context_dict) def view_trip(request, username, trip_name_slug): context_dict = {} try: trip = Trip.objects.get(slug=trip_name_slug) context_dict['trip'] = trip except Trip.DoesNotExist: context_dict['trip'] = None return render(request, 'trip.html', context_dict) app/urls.py urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^contact/$', views.contact, name='contact'), url(r'^pop_trips/$', views.pop_trips, name='pop_trips'), url(r'^recent_trips/$', views.recent_trips, name='recent_trips'), url(r'^best_travelled/$', views.best_travelled, name='best_travelled'), url(r'^most_active_travellers/$', views.contact, name='most_active_travellers'), url(r'^passport/$', views.passport, name='passport'), url(r'^add_trip/$', views.add_trip, name='add_trip'), url(r'^settings/$', views.settings, name='settings'), url(r'^my_trips/$', views.my_trips, name='my_trips'), url(r'^(?P<username>[\w\-]+)/$', views.view_profile, name='view_profile'), url(r'^(?P<username>[\w\-]+)/(?P<trip_name_slug>[\w\-]+)/$', views.view_trip, name='view_trip'), ] Templates: view_profile.html {% extends 'base.html' %} {% load staticfiles %} {% block title_block %} {{user.username}} {% endblock %} {% block body_block %} <h1>{{ user.username … -
Django filter with a lot of values ok PK
I do: qs = qs.filter(pk__in=qs_searches) with qs a (15000) QuerySet and sq_searches a big (+1000) haystack.query.ValuesListSearchQuerySet It takes a lot of time. More info: Indexation backend is Whoosh DB is currently sqlite pk has db_index=True (maybe useless) Is it possible to optimize it? -
Django: Programmatically save HTML page to PDF without using HTTP
views.py class PdfView(DetailView): model = TheModel template_name = 'pdf.html' urls.py urlpatterns = [ url( r'^(?P<pk>[0-9]+)/$', PdfDataView.as_view(), name='pdf-data', ), ] Visiting the relevant url, an html page is rendered. I need to programmatically save this html page to a pdf file on the server and avoid using an HTTP request or response to accomplish this. -
Django errors get overlapped, can't style them
I have a form and I decided to handle it manually. My form is actually from 2 forms, but that's not important. Thing is, that when I want to display the errors at the bottom of my form, they get overlapped on top of each other. I wanted to show one at a time, so I tried to use padding with overflow hidden for the form, but doesn't seem to work. Any style I apply won't work, except for margins. .alert { margin-top: 45% !important; } #errors { padding: 20px !important; } {% if form1.errors %} {% for field in form1 %} {% for error in field.errors %} <div class="alert alert-danger"> <strong id="errors">{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form1.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} {% if form2.errors %} {% for field in form2 %} {% for error in field.errors %} <div class="alert alert-danger"> <strong id="errors">{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form2.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} -
Django breadcrumbs with different kwargs in template
I am trying to implement breadcrumbs in my app. The question I have, is how can I successfully pass the island kwargs to sites_detail.html without causing a NoReseverseMatch error? Obviously, wth the current implementation I get: Reverse for 'sites' with keyword arguments '{'island': ''}' not found. base.html <li><a href="{% url 'sites' island='ni'%}">North Island</a></li> <li><a href="{% url 'sites' island='si'%}">South Island</a></li> site_list.hml {% block breadcrumbs %} {{ block.super }} » <a href="{% url 'sites' island=view.kwargs.island %}">{{ view.kwargs.island }}</a> {% endblock %} sites_detail.html {% extends "palaeo_app/sites_list.html" %} {% block breadcrumbs %} {{ block.super }} » {{ sites.location }} {% endblock %} Thankyou! -
Django telegram bot reply keyboard not working
i have a problem. I've just installed Django with django-telegram-bot package and I use a function from examples and it basically return a message to user. What I want is to send a reply_keyboard to him. It's strange, but its not working. Here is my code: from telegram.ext import CommandHandler, MessageHandler, Filters from telegram import ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton from django_telegrambot.apps import DjangoTelegramBot def me(bot, update): keyboard = [ [ InlineKeyboardButton("Option 1", callback_data='1'), InlineKeyboardButton("Option 2", callback_data='2') ], [ InlineKeyboardButton("Option 3", callback_data='3') ] ] reply_markup = InlineKeyboardMarkup(keyboard) # THIS IS PRINTING TEXT BUT Not keyboard! update.message.reply_text('Please choose:', reply_markup=reply_markup) # Again sent text bot.sendMessage(update.message.chat_id, text='text works' ,reply_markup=markup) I stuck already for 3 days with this problem. -
Django - Form in a dynamic HTML table
I am trying to create a HTML table, with a 2 fields on each row for the user to fill in (sports matches predictions). Right now I have a cycle which loops through the matches and based on that creates the HTML table. input.html {% block body %} <form method="post"> {% csrf_token %} <table class="table"> <tr> <th>Round</th> <th>Date</th> <th>Time</th> <th>Home</th> <th class="col-md-1"></th> <th class="col-md-1"></th> <th class="col-md-1"></th> <th>Away</th> </tr> {% for item in query_results %} <tr> <td>{{ item.match_round }}</td> <td>{{ item.match_date }}</td> <td>{{ item.match_time }}</td> <td>{{ item.home_team_name }}</td> <td>{{ form.home_goals_predictions|add_class:"form-control"}}</td> <td class="text-center">:</td> <td>{{ form.away_goals_predictions|add_class:"form-control"}}</td> <td>{{ item.away_team_name }}</td> </tr> {% endfor %} </table> <button type="submit" class="btn btn-success">Submit</button> </form> {% endblock %} This is works and display the table excatly as I want. However I am not able to extract the data as I want from it - to be more exact, when submiting the form, the data from the last row gets assigned to all the rows. views.py if request.method == 'POST': form = PredictionsForm(request.POST) if form.is_valid(): user_prediction = form.save(commit = False) for result in query_results.all(): for home_goals_predictions, away_goals_predictions in form.cleaned_data.items(): user_prediction.id = result.id user_prediction.match_round = result.match_round user_prediction.home_team_name = result.home_team_name user_prediction.away_team_name = result.away_team_name user_prediction.user_id = request.user.id user_prediction.home_goals_predictions = form.cleaned_data['home_goals_predictions'] user_prediction.away_goals_predictions = form.cleaned_data['away_goals_predictions'] … -
Python 3.6.x / Django 2.0.x uuids in paths failig
Python: 3.6.3 // Django: 2.0.2 I am trying two new things at one time. Class Based Views and using UUIDs as "account numbers". urls.py is: from django.urls import path, re_path from .views.index import * from .views import profile urlpatterns = [ re_path(r'^$', index.IndexDetailView.as_view(), name='index'), path('Members', index.IndexDetailView.as_view(), name='index'), path('Members/Profile/<uuid:account_number>/', profile.ProfileDetailView.as_view(), name='profile-detail'), path('Members/Profile/<uuid:account_number>/edit', profile.edit), path('Members/Profile/create', profile.create), ] "Profile" is an extension of the "User" model. The Profile includes an account_number field: account_number = models.UUIDField( max_length=32, default=uuid.uuid4, editable=False, unique=True, blank=False, null=False, ) The ``DetailView` I am trying out is: class ProfileDetailView(DetailView): model = Profile pk_url_kwarg = "account_number" template_name = 'Members/profile2.html' @verified_email_required def get_object(self, queryset=None): queryset = self.get_queryset() if queryset is None else queryset profile = get_object_or_404(queryset, account_number=self.kwargs['account_number']) # profile = super().get_object() return profile @verified_email_required def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form_readonly'] = True return context There is a "partial" view/template that displayes the Profile info. It contains an "Edit" button that looks like: <div id="profileDetails" class="profileDetails"> <h4>Account Holder Details:</h4> <table class="profileDetails text-left"> <tbody> <tr> <th>Name</th> <td>{{ profile.last_name }}, {{ profile.first_name }}{% if profile.middle_name %} {{ profile.middle_name }}{% endif %}</td> </tr> <tr> <th>Address</th> <td>{% if profile.address1 %} {{ profile.address1 }}<br> {% endif %} {{ profile.address2 }}<br> {{ profile.city }}, {{ profile.state }} {{ profile.zip … -
Django staticfiles_dirs not working correctly
I'm working with this website http://fotokluczniok.pl/ now. If You press F12 You will see the staticfiles do not work correctly. Here is my seetings.py code: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), '/home/fotoklu/fotokluczniok/static/', ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') Here is urls.py code: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Project structure: CLICK HERE How to solve this problem ? -
Django-Rest: Poping validated data
My goal is to add tags to a post. I'm using latest taggit and DRF. Goal: To pop tags only from posted request. For each tag in the post request to call post.tags.add("tag1","tag2") to add these tags to the model. Currently, my post serialiser is: class PostSerializer(serializers.ModelSerializer): tags = serializers.ListField( child=serializers.CharField(min_value=0, max_value=3) ) ... def create(self, validated_data): tags_data = validated_data.pop('tags') # Need to pop tags only to_be_tagged, validated_data = self._pop_tags(validated_data) images_data = self.context.get('view').request.FILES post = Post.objects.create(**validated_data) post.tags.add(tags_data) for image_data in images_data.values(): PostImage.objects.create(post=post, image=image_data) return post When I send a post request with the following data: data = { 'title': 'First Post', ... 'tags':'["tag1"]'} I get an error: File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/serializers.py" in save 214. self.instance = self.create(validated_data) File "/app/app/serializers.py" in create 111. post.tags.add(**validated_data) File "/app/.heroku/python/lib/python3.6/site-packages/taggit/utils.py" in inner 145. return func(self, *args, **kwargs) Exception Type: TypeError at /app/posts/ Exception Value: add() got an unexpected keyword argument 'title' -
Django + Angular 5 development setup CSRF handling
I am having a bit of an issue with my current development setup when it comes to CSRF verification. Since I am running an angular development server and a django development server side by side and (naturally) need to send requests to the backend, CSRF becomes an issue. Django usually hands the token out when a user connects, but now that the front- and backend are so disconnected I do not get the CSRF token in the natural way. What I now tried was to add a @csrf_exempt decorated function to be able to get the cookie, also by decorating the function with @ensure_csrf_cookie. The problem I am having is that still when setting the appropriate header for the request to include the CSRF token, the server still returns me a message saying that the CSRF cookie was not included (bullshit!). So, my question is firstly how to properly set the header for the CSRF token, this is how I currently do it (typescript below): constructor(private httpClient: HttpClient) { const cookies = document.cookie.split(';'); for (let cookie of cookies) { cookie = cookie.trim(); const re = new RegExp('^csrftoken'); if (re.test(cookie)) { this.csrfToken = cookie; // this.csrfToken = cookie.substr(10, cookie.length); break; } … -
Django ModelForm : How to use update_or_create on form.save()?
I have a Questions model with question_no being unique. I would like to update the question or create a new one if not exists. models.py class Questions(models.Model): question_no = models.CharField(max_length=255,blank=False,unique=True) question_img = models.ImageField(upload_to='avirbhav/2/images/ques/',blank=False) question_desc = models.CharField(max_length=255,blank=True) question_ans = models.CharField(max_length=255,blank=False) date_created = models.DateTimeField(auto_now_add=True) forms.py class UploadForm(forms.ModelForm): class Meta: model = Questions fields = ('question_no','question_img','question_desc','question_ans') views.py def upload_admin(request): if request.method=='POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): form.save() return JsonResponse({'created':'True'}) Now, the above code throws an error: Questions with this Question no already exists. I would have done it the other way with: question_no = form.cleaned_data['question_no'] question_img = form.cleaned_data['question_img'] question_desc = form.cleaned_data['question_desc'] question_ans = form.cleaned_data['question_ans'] question, created = Questions.objects.update_or_create(question_no=question_no,defaults={"question_img":question_img,"question_desc":question_desc,"question_ans":question_ans}) But I would like to update the database with form.save(). I need to save the image to a folder, and also update the database. I there any other way to do it? like overriding the save() to create_or_update database???? -
No module named 'django.contrib.postgres.search' Error
Trying to build a full text search view in Django, but getting this error message when I try to run the server: No module named 'django.contrib.postgres.search I did just switch my db from sqlite to postgres, so not sure if there is some sort of error that happened in that move here is my full stack trace Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x06B2D1E0> Traceback (most recent call last): File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate app_config.ready() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\debug_toolbar\apps.py", line 15, in ready dt_settings.patch_all() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\debug_toolbar\settings.py", line 243, in patch_all patch_root_urlconf() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\debug_toolbar\settings.py", line 231, in patch_root_urlconf reverse('djdt:render_panel') File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py", line 568, in reverse app_list = resolver.app_dict[ns] File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py", line 360, in app_dict self._populate() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py", line 293, in _populate for pattern in reversed(self.url_patterns): File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 33, in __get__ res … -
How do I make a django model form whose authorization can only be done by admin for positng?
So I have the following models.py class Incubators(models.Model): # These are our database files for the Incubator Portal incubator_name = models.CharField(max_length=30) owner = models.CharField(max_length=30) city_location = models.CharField(max_length=30) description = models.TextField(max_length=2500) rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(10)]) logo = models.CharField(max_length=30) picture = models.CharField(max_length=30) def __str__(self): # Displays the following stuff when a query is made return self.incubator_name + '-' + self.owner Now what I am trying to do is create a form for user who has to fill the above field for advertising there incubator on the wall. Before posting, I want to make sure that these details get verified by the admin (django admin), and after verification from admin it gets posted on the wall ? Is there any model field for the same specially meant for admin ? -
How to save data to database at 1 minute intervals on Django?
I'm writing a django survey application and it's required to save votes on a queue structure and at 1 minute intervals save the elements of the queue on database. Thats for save I/O overhead. Currently I'm saving the votes directly from my votes view: def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) selected_choice = question.choice_set.get(pk=request.POST['choice']) selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('enqueteapp:results', args=(question.id,))) My problem is that I don't know where I can start the queue and the thread to do what I need to do. PS: I don't wanna know if there is a better way to do it. I'm required to use the queue stuff. -
Host Django site on windows on lan
I have a site that I want to expose to a bunch of colleagues that serves as an interface for some Machine learning tools. I’ve made the site in Django 2.0 and would like to serve it from a small windows PC under my desk, and then from a more dedicated server once it’s operational. I’ve had a look around and it looks like my options are using uWSGI or Django it self to serve the site. Obviously Django is mich slower, but on a PC with an i5 i recon it should be able to handle a couple of requests a minute, which is the peak traffic I’m expecting. FastCGI appears to be depreciated, so what other options, prioritizing ease of confit on my part are there? -
ImportError: No module named googleads
I have a django project and want to deploy it on Google App Engine(GAE). I followed all this link for the tutorial: https://cloud.google.com/python/django/appengine When I finished deploying, and go to my project URL, I got an error and when I look on the Error Reporting in Google Cloud Platform It says "ImportError: No module named googleads", but I already installed it on my local before I uploaded it. Please help! Thanks! -
how to install packages inside virtualenv
I have a virtualenv created for a Django project. Inside this project I have app folder with 'views.py'. I have installed beautiful soup and requests inside this virtualenv and they import correctly into the 'views.py'. However, for testing puroposes I have another script created inside the same folder as 'views.py' but when I try to import same modules there I get 'no module named...' error. Is that possible? -
How to update database in django without taking id of the object
When i am doing a post request without id of the object it is showing "subject": [ "This field is required." ] subject has a field called title , so can i update the database using the title. -
Why is Postgres query faster than Redis query?
I am learning about Redis, and how its blazing fast since its an in-memory database. In my Django application, I have a Postgres table with about 1500 rows in it. The model only has two fields 'name' and 'occurrence'. To test out how much faster it would be to query for objects out of memory, compared to from my local database, which I believe is stored on disc, I created two queries 1) Simple order by query using Django objects manager 2) ZRANGE command on Redis server, getting same items back from a Redis sorted set. After making both queries, I found that getting the same number of items from a Redis sorted set took 250 times longer than it took to make the Postgres Query. Why is this ? Script def get_word_results(request): now = datetime.datetime.now() words = Word.objects.all().order_by('-occurrence') after = datetime.datetime.now() diff = (after - now).total_seconds() * 1000 print(diff) rnow = datetime.datetime.now() words_redis = redis_server.zrange(name='myzset', start=0, end=-1, withscores=True) rafter = datetime.datetime.now() diff2 = (rafter - rnow).total_seconds() * 1000 print(diff2) Results 0.199 48.048