Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Profiling Django: what is {posix.write} function?
Profiling Django app to figure out slow functions. I just added some middleware to track function calls, following this blog: http://agiliq.com/blog/2015/07/profiling-django-middlewares/ and I see that the entry of cProfile stats for {posix.write} is one of the longest. Any idea what that is, and where that comes from? Other functions are referenced by their name and package path, so I'm not sure what {posix.write} means. the log looks like this: 204051 function calls (197141 primitive calls) in 0.997 seconds Ordered by: internal time List reduced from 1204 to 50 due to restriction <50> ncalls tottime percall cumtime percall filename:lineno(function) 35 0.305 0.009 0.305 0.009 {posix.write} 95 0.206 0.002 0.207 0.002 {method 'execute' of 'psycopg2.extensions.cursor' objects} 73 0.088 0.001 0.088 0.001 {select.select} 898 0.023 0.000 0.047 0.000 /.venv/lib/python2.7/site-packages/django/db/models/base.py:388(__init__) 1642 0.012 0.000 0.371 0.000 /.venv/lib/python2.7/site-packages/django/template/base.py:806(_resolve_lookup) 1 0.010 0.010 0.011 0.011 {_sass.compile_filename} 1 0.009 0.009 0.009 0.009 {psycopg2._psycopg._connect} 34 0.009 0.000 0.009 0.000 {method 'recv' of '_socket.socket' objects} 39 0.007 0.000 0.007 0.000 {posix.read} 9641/6353 0.006 0.000 0.321 0.000 {getattr} 173 0.006 0.000 0.026 0.000 /.venv/lib/python2.7/site-packages/django/core/urlresolvers.py:425(_reverse_with_prefix) 25769 0.006 0.000 0.007 0.000 {isinstance} Thanks -
Top navbar moves when clicking on a specific menu item
Here is the app that I have developed: http://azeribocorp.pythonanywhere.com/index/ When I click on Search in the menu, the navbar shifts down, I cannot find where the problem is. I want the menu to be always fix on the top of the page. Any help is appreciated. __base.html: {% load staticfiles %} <!DOCTYPE html> <html lang="en" class="no-js"> <head> {% block meta_tags %}{% endblock meta_tags%} <title> {% block title %}Azeribo Tracking{% endblock title %} </title> {% block stylesheets %} {% endblock %} {% block javascript %} {% endblock javascript %} {% block extra_head %} {% endblock %} </head> <body> <header class="topnavbar"> {% include 'aztracker/_topnavbar.html' %} </header> <div id="main" role="main"> <div class="container"> {% block content %} {% endblock content %} </div> </div> {# /#main #} <script type='text/javascript' src="{% static 'js/_topnavbar.js' %}"></script> </body> </html> _topnavbar.html {% load static %} {% load staticfiles %} <head> <link rel="stylesheet" type="text/css" href="{% static 'css/_topnavbar.css' %}"> <link rel="script" type="text/css" href="{% static 'css/_topnavbar.js' %}"> </head> <!--Top Navigation--> <nav role="navigation" class="nav"> <ul class="nav-items"> <li class="nav-item"> <a href="/index/" class="nav-link"><span>Home</span></a> </li> <li class="nav-item "> <a href="#" class="nav-link"><span>Track Container</span></a> <nav class="submenu"> <ul class="submenu-items"> <li class="submenu-item"><a href="#" class="submenu-link">Product #1</a></li> <li class="submenu-item"><a href="#" class="submenu-link">Product #2</a></li> <li class="submenu-item"><a href="#" class="submenu-link">Product #3</a></li> </ul> </nav> </li> <li class="nav-item"> <a … -
Django Urls - two views with same regular expression
I have two views with the same regular expression, as you can see below. It's a Category and an Article view, their entry slugs will never be the same so it should be no problem. But at the moment it doesn't work well, as you prolly know the category-view will get triggered. urls.py urlpatterns = [ url(r'^index', index.Index.as_view(), name='index'), url(r'^search', search.Index.as_view(), name='search'), url(r'^(?P<slug>.+)$', category.Index.as_view(), name='category'), url(r'^(?P<slug>.+)$', article.Index.as_view(), name='article'), ] I tried to reverse from views.category back to urls.py if there is no category to find like this: views.category.py class Index(View): def get(self, request, slug): category = CategoryModel.objects.get(slug=slug) if category is None: return HttpResponseRedirect(reverse('article', args=[slug])) context = { 'category': category } return render(request, 'category/index.html', context) The error (but there is a article with slug 'test123'): NoReverseMatch at /wiki/test123 Reverse for 'article' with arguments '('test123',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Using Python 3.6 -
Duplicate indexes appears in the Django-haystack with solr backend
Solr indexes the same model object with duplicate, but id is different. Place/search_indexes.py class PlaceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) p_key = indexes.IntegerField(model_attr='id',indexed=False) name = indexes.CharField(model_attr='name',null=True) location = indexes.LocationField(model_attr='get_location',indexed=False) avatar = indexes.CharField(null=True,indexed=False) address = indexes.CharField(model_attr='address',null=True,indexed=False) allow_membership = indexes.BooleanField(model_attr='allow_membership') location_x = indexes.DecimalField(model_attr='location_x',indexed=False) location_y = indexes.DecimalField(model_attr='location_y',indexed=False) status = indexes.IntegerField(model_attr='status') city = indexes.CharField(model_attr='city__id') def prepare_avatar(self, obj): if obj.avatar: return obj.avatar.url return None def get_model(self): return Place def index_queryset(self, using=None): return self.get_model().objects.filter(status=Place.Status.ACTIVE, city__status=City.Status.ONLINE).distinct() Solr shows the duplicates with the all equal to each other, except id field. One index's id field is valid the second not present in db. What it might be causing this? Or,at least, is there a way to skip the specific index or object when calling update_index? Not index_queryset() because it doesn't handle indexing per object level? -
Django:Modal popup not opening on click of button
I have a dynamically created table https://imgur.com/a/4yulC and on click of cross mark button the modal doesn't open..I tried a lot but not understanding where the problem is involved.I took help of https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html his code as reference.please help me... m_manage.html <div class="container-fluid"> <div class="row"> <div class="col-lg-8"> <div class="panel panel-black"> <div class="panel-heading"><i class="fa fa-thumb-tack" style="font-size: 20px" aria-hidden="true"></i> My tasks</div> <div class="panel-body"> <table class="table table-hover" id="leave-table"> <col width="80"> <col width="1200"> <col width="50"> <col width="50"> <col width="50"> <col width="50"> <tbody> {% include 'leaves/partial_m_manage.html' %} </tbody> </table> </div> </div> </div> </div> </div> <div class="modal fade" id="modal-leave"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> </div> partial_m_manage.html : It contains the the columns in table {% for pl in pending_leaves %} <tr> <td><img src='{{pl.employee.image.url}}' width="55" class="img-circle"></td> <td> <b>{{pl.employee.emp_name|title}}</b> {% if pl.start_date == pl.end_date %} <p>Applied leave on <i>{{pl.start_date |date:"D"}}, {{pl.start_date}} </i></p> {% else %} <p>Applied leave from <i>{{pl.start_date |date:"D"}}, {{pl.start_date}}</i> to <i>{{pl.end_date |date:"D"}}, {{pl.end_date}} </i></p> {% endif %} </td> <td >{{pl.employee.emp_loc|title}}</td> <td><button type="button" class="btn btn-warning btn-sm js-update-leave" data-url="{% url 'leaves:leave_update' pl.id %}"><i class="fa fa-check" aria-hidden="true" style="color:green"></i></button> </td> <td><button type="button" class="btn btn-warning btn-sm js-delete-leave" data-url="{% url 'leaves:leave_delete' pl.id %}"><i class="fa fa-times" aria-hidden="true" style="color:red"></i></button> </td> </tr> partial_leave_delete.html <form method="post" action="{% url 'leaves:leave_delete' leave.id %}" class="js-leave-delete-form"> {% csrf_token %} <div … -
Connect to docker container using IP
I'm running the next commands: $ docker-machine ls NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS default * virtualbox Running tcp://192.168.99.100:2376 v17.06.2-ce $ docker-machine ip default 192.168.99.100 And I have some docker containers. Once of the is running django, other one postgres and a third one elastic search. When I'm running my django container with: # python manage.py runserver 0:8000 And it is working when I use the site: localhost:8000/ But, is not available when I use: 192.168.99.100:8000 There, I have the browser message: This site can’t be reached 192.168.99.100 refused to connect. Try: Checking the connection The same happens for the postgres and elasticseach container. Why my docker container is not applying the default docker-machine ip ? -
How to setup URL.PY Code for Django 1.11 on Ubuntu 16.04
I am very new to coding and started 2 days back, and using the Ubuntu distro since yesterday. I have been following a youtube video on how to build a website using python, and in the video he is using a Mac. It has been similar for the most part, but I have been able to google the few differences and fix them on my own. I am having trouble with the code that you use for the url.py file. Images of the error have been attached. *The code edit I did in the text editor. *The error I get on my Ubuntu terminal. Any help on this matter is greatly appreciated. -
How set permission for specific app in Django Rest Framework
I have two REST application in my Django project: api - should be AllowAny and ReadOnly! apicrm - should be rest_framework.permissions.IsAuthenticated How to set this permission for whole app in Django Rest Framework? -
How to post html data to an API in django
I am trying to post data to an external API using django html in json format. Once I select the dropdown, and click submit on the html page, the data should be posted to an external API in json format. what would be the best procedure to do that. Also, I am getting that values from external API. Here are my views and html. When I submit the form, It is submitted successfully but i was not able to post the selected data into that external API. What would be best way to do this. Any help will be highly appreciated. Views.py import json, urlib def home(request): deviceroles = list() if request.method == 'GET' url = "http://netbox.com/deviceroles" response = urllib.urlopen(url) data = json.loads(response.read()) for i in range(0, len(data['results'])): devicerole = data['results'][i]['name'] deviceroles.append(devicerole) return render(request,"base.html", {'deviceroles': deviceroles}) base.html <select class="em-c-select em-c-select" id="file" placeholder="Placeholder">] {% for devicerole in deviceroles %} <optgroup> <option value="{{ devicerole }}" disabled="disabled" selected="selected">{{ devicerole }}</option> </optgroup> {% endfor %} </select> forms.py class NameForm(forms.Form) device_roles = forms.CharField(label='device_role', max_length=100) urls.py urlpatterns = [ url(r'^$', views.home, name='home') url(r'^submitted', views.submitted, name='submitted') views.py def submitted(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): payload = {'apikey' : apikey, 'device_role' : request.POST.get('device_role') response … -
python list of dictionaries only updating 1 attribute and skipping others
I have a list of lists containing company objects: companies_list = [companies1, companies2] I have the following function: def get_fund_amount_by_year(companies_list): companies_length = len(companies_list) for idx, companies in enumerate(companies_list): companies1 = companies.values_list('id', flat=True) funding_rounds = FundingRound.objects.filter(company_id__in=companies1).order_by('announced_on') amount_per_year_list = [] for fr in funding_rounds: fr_year = fr.announced_on.year fr_amount = fr.raised_amount_usd if not any(d['year'] == fr_year for d in amount_per_year_list): year_amount = {} year_amount['year'] = fr_year for companies_idx in range(companies_length): year_amount['amount'+str(companies_idx)] = 0 if companies_idx == idx: year_amount['amount'+str(companies_idx)] = fr_amount amount_per_year_list.append(year_amount) else: for year_amount in amount_per_year_list: if year_amount['year'] == fr_year: year_amount['amount'+str(idx)] += fr_amount return amount_per_year_list The problem is the resulting list of dictionaries has only one amount attribute updated. As you can see "amount0" contains all "0" amounts: [{'amount1': 12100000L, 'amount0': 0, 'year': 1999}, {'amount1': 8900000L, 'amount0': 0, 'year': 2000}] What am I doing wrong? -
How to get value of fields from given dictionary in Django python
[ { "model": "demo.industrycat1", "pk": 1, "fields": { "name": "Division A: Agriculture, Forestry, And Fishing" } }, { "model": "demo.industrycat1", "pk": 2, "fields": { "name": "Division B: Mining" } }, { "model": "demo.industrycat1", "pk": 3, "fields": { "name": "Division C: Construction" } }, { "model": "demo.industrycat1", "pk": 4, "fields": { "name": "Division D: Manufacturing" } } ] I am beginner and could not find any relevant answer on internet. -
How to decode a serialized or toArray object from JQuery to Django views?
I am using jQuery sortable() to sort a table in the frontend. I have a button that will send the new order into my backend in Django once the user hit save. When the new order is saved, I am unable to decode the request post. Please see my code below for JQuery: $("#sortable").sortable({ update: function (event, ui) { var order = $(this).sortable('toArray'); $(document).on("click", "button", function () { $.ajax({ data: {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, order}, type: 'POST', url: '/sample_route' }); }); } }) I find that I can either use var order = $(this).sortable(‘serialize’); // or var order = $(this).sortable(‘toArray’); To be able to send the data into the backend. Let’s say the order of the ids are the following: <table class="table table-striped table-hover "> <thead> <tr> <th>Priority</th> <th>Report Type</th> <th>Submitted By</th> </tr> </thead> <tbody id="sortable"> {% for idx in reports %} <tr id="id_{{idx.0}}"> <td>{{idx.0}}</td> <td>{{idx.1}}</td> <td>{{idx.2}}</td> </tr> {% endfor %} </tbody> </table><br> If I use serialize; I get this in my Http request body print request.POST['order'] >> id[]=7&id[]=1&id[]=5 If I use toArray; I get this the following Http request: print request.POST >> u'order[]': [u'id_5', u'id_1', u'id_7’] print request.POST['order[]'] >> id_7 ## only prints the last element How can I use either … -
How to promote user to select only the unselected many-to-many objects .?
I want django-admin user to choose only unselected many-to-many objects ('cyan' and 'black'). User should not be able to deselect the objects that is already selected ('red', 'blue', 'yellow'). Default Django admin templates are used for my model forms.Here products field is of type forms.ModelMultipleChoiceField. How can I implement this in django-admin.? -
Django template language - multiple variables in the same line?
This seems like such a basic concept, but as a Django beginner i couldn't find an answer to it anywhere. What is the meaning of: {% varname1 varname2 varname3 varname4 %} Would that line just "print" to the page the value of each of those variables? -
Access the choice via my django model
settings.py PERIODS = ( ('day', _('Per day')), ('week', _('Per week')), ('month', _('Per month')), ('year', _('Per year')), ) models.py class Statistics(TimeStampedModel): @property def per_period(self): return settings.PERIODS[self.] def nb_of_customers_per_period(self): pass views.py class StatisticsIndexView(StaffRestrictedMixin, TemplateView): model = Statistics() template_name = 'loanwolf/statistics/index.html' def get_context_data(self, **kwargs): context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ 'applications_by_state': ApplicationsByState(), 'applications_calendar': ApplicationsCalendar(), 'new_customers_calendar': NewCustomersCalendar(), 'statistics': Statistics(), 'form': StatisticsBaseForm(), }) return context forms.py class StatisticsBaseForm(forms.Form): type_choice = forms.ChoiceField(label=_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, initial=0, required=False) period = forms.ChoiceField(label="Period", choices=settings.PERIODS, initial='week', required=False) from_regular_product = forms.ModelChoiceField( queryset=ProductConfig.objects.filter(pk=-1), required=False, label=_('Product')) from_special_product = forms.ModelChoiceField( queryset=ProductConfig.objects.filter(pk=-1), required=False, label=_('Product')) product_type = forms.ChoiceField( choices=settings.LOANWOLF_PRODUCT_TYPE_CHOICES, required=False, initial='regular', label=_('Product type')) debit_frequency = forms.ChoiceField( choices=settings.LOANWOLF_PRODUCT_DEBIT_FREQUENCIES_CHOICES, required=False) def __init__(self, *args, **kwargs): super(StatisticsBaseForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'row' self.helper.layout = StatisticalToolsLayout company = get_current_company() regular_products = company.available_products.filter( is_active=True, product_type='regular') special_products = company.available_products.filter( is_active=True, product_type='special') self.fields['from_regular_product'].queryset = regular_products self.fields['from_special_product'].queryset = special_products if regular_products: self.fields['from_regular_product'].initial = \ settings.LOANWOLF_EXTERNAL_REQUEST_DEFAULT_PRODUCT_INDEX if special_products: self.fields['from_special_product'].initial = \ settings.LOANWOLF_EXTERNAL_REQUEST_DEFAULT_PRODUCT_INDEX class Meta: model = Statistics fields = '__all__' Ok, here is my problem. I have a form with a period drop-down menu which allows me to select different types of period (Per day, Per week, Per month or Per year). For instance, if I select Per week, I would like to have access to … -
creating ads system using django
This is an insight question and I would like to know if it is appropriate to build an ads system using django . For example I have a blog system which enables users to create account. I want users to be able to create ads by picking a specific post of choice. I would like to know if it is possible with django and how to go about it. Thanks. Demo codes would also be appreciated -
UserCreationForm extension not making fields in the model
I have extended the Usercreationform as follows: //forms.py class UserCreationForm(UserCreationForm): email = EmailField(label=_("Email address"), required=True, help_text=_("Required.")) city= forms.CharField(label= _("City"),max_length=20, required=True) state= forms.CharField(label= _("State"),max_length=20, required=True) class Meta: model = User fields = ("username", "email", "password1", "password2","city","state") def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.city = self.cleaned_data["city"] user.state = self.cleaned_data["state"] if commit: user.save() return user This works fine till the form part. the template shows all these fields but there is a problem here. the fields that i added like city,state,etc are showing on the form but when i query like User.city or anything except the inbuilt, it gives me that User has no attribute city...this means that the fields are not being created in the in-built User model...So how do i do it? -
elastic search with haystack in django not working although setting up all requirements
here I did all the instructions given in haystack official documentation but still not able to fetch result. I am using django version 1.8.1 and haystack 2.4.1 and elasticsearch 5.4.0 Here is my views.py from haystack.query import SearchQuerySet def search1(request): result=SearchQuerySet().autocomplete(content_auto=request.POST.get('search_text','')) return render_to_response('ajax_search.html',{"result":result}) model.py class vastu(models.Model): vastu_key = models.ForeignKey(product_type) fetchall_key = models.ForeignKey(d_auth) title = models.CharField(verbose_name='Title', max_length=25) brand = models.CharField(verbose_name='Brand:', max_length=25, blank=True, null=True) image = models.ImageField(upload_to=upload_location1, null=True, blank=True, height_field="height_field", width_field="width_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) price = models.IntegerField(verbose_name='Price:', max_length=20) desc = models.TextField(verbose_name='Description', blank=True, max_length=500) dprice = models.IntegerField(verbose_name='Discount Price:', null=True, blank=True, max_length=20) bookmark = models.IntegerField(null=True, blank=True, max_length=02) def __str__(self): return self.vastu_key class Meta: ordering = [ 'desc','brand','title'] search_indexes.py import datetime from haystack import indexes from dashboard.models import vastu class vastuIndex(indexes.SearchIndex,indexes.Indexable): text = indexes.CharField(document=True,use_template=True) content_auto = indexes.EdgeNgramField(model_attr='title') def get_model(self): return vastu def index_queryset(self, using=None): return self.get_model().objects.all() text file path /dashboard/templates/search/indexes/dashboard/vastu_text.txt vast_text.txt {{ object.title }} {{ object.brand }} search.html location /home/mayuresh/shopcon/dashboard/templates/search/search.html search.html {% extends 'base.html' %} {% block content %} <h2>Search</h2> <form method="get" action="/user/search/"> <table> {{ form.as_table }} <tr> <td>&nbsp;</td> <td> <input type="submit" value="Search"> </td> </tr> </table> {% if query %} <h3>Results</h3> {% for result in page.object_list %} <p> <a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a> </p> {% empty %} <p>No results found.</p> {% … -
Django - Template tags with model instance methods
Say I have a template that renders the tag {{ model.choicenumber }}, returning an integer of 3. Using the model instance method like {{ model.get_choicenumber_display }} will return a human-friendly 'Three' string in this scenario. I'm looking to mix the get_FOO_display method and the |add template filter so that {{ model.choicenumber|add:'1' }} will print 'Four'. Trying something like {{ model.get_choicenumber|add:'1'_display }} returns the error Could not parse the remainder: '_display' from 'model.get_choicenumber|add:'1'_display' Thanks! -
How to display all session variables in django?
How to display all session variables ? i know that a variable can be accessed using request.session['variable'] but i wanted to know if there other variables that are set by others or set automatically during user logins or similar other events.. -
Connect two docker containers
I have two containers, the first one with a django and the second one with postgresql. Well, in my first server I have running django and I'm trying to connect it with the second one. The second container has the port 32770 exposed but internally running in the port 5432. In my local machine, I have the connection: Server: 'Localhost' Port: 32770 User: 'myuser' Password: '' And it's connecting, but with my django container, I'm getting this error: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 32770? The same happens for the port 5432 How I can connect both servers? -
How to replace re "." in Django template url tag
I have Django url routes that looks like this: app_name = 'courses' urlpatterns = [ url(r'./(?P<courseid>[0-9]+)/$', views.viewcourse, name='view_course'), url(r'./(?P<courseid>[0-9]+)/review/$', views.reviewcourse, name='review_course') ] The "." in the regular expression will usually be replaced by a slug, e.g.: courses/computer-science/3/ Now I need a link in my 'view course' template to take the user to the review page, i.e: courses/computer-science/3/review/ I could do this by simply appending review to the current url: {{ request.path }}review However, I would rather do it the 'correct' way using a template url tag {% url 'courses:review_course' courseid=course.pk %} However, this produces: courses/30/review, which of course fails. Is it possible to generate the correct link using the {% url %} tag without having to change the "." into a name capture parameter? -
Django deployment on Heroku, upgrading to Cedar-14, Import Settings Error
ImportError: Could not import settings 'settings.prod' (Is it on sys.path? Is there an import error in the settings file?) I built this app back in 2013-2014, and it hasn't seen much maintenance since then. But there's a problem now, some AWS keys need to be changed, but I can't deploy the app. git push heroku master results in a failed build unless I do heroku config:set DISABLE_COLLECTSTATIC=0 So, I did that, knowing it would probably break the site, but it never even gets to that point, because then I find out I can't deploy until I upgrade to Cedar-14. Ok, so I do that, then push, and then I get ImportError on every dyno. app/web.1: ImportError: Could not import settings 'settings.prod' (Is it on sys.path? Is there an import error in the settings file?): cannot import name _uuid_generate_random app/celerybeat.1: ImportError: Could not import settings 'settings.prod' (Is it on sys.path? Is there an import error in the settings file?): cannot import name _uuid_generate_random app/celeryd.1: ImportError: Could not import settings 'settings.prod' (Is it on sys.path? Is there an import error in the settings file?): cannot import name _uuid_generate_random So I read here that I need to update Kombu. Ok, so I do … -
FormFields for (Admin)Inlines || Can't import InlineModelAdmin
I want to catch up some extra information within my Django Admin through some extra Fields. I want to use inlines for that purpose. I have: class YourModelForm(forms.ModelForm): slot_count_request = forms.IntegerField(label='#-slot-size', initial=4 ) class Card_Group_proxy_inline(admin.TabularInline): model = SomeRandomModel form = YourModelForm This works fine for if I want to use a model within. I thought I can get rid of it, if I inherit from admin.InlineModelAdmin, but then I get an error: AttributeError: module 'django.contrib.admin' has no attribute 'InlineModelAdmin' -
Number of customers per week
In my django project, it is possible to show every customer in the application with CustomerProfile.objects.all() and find the creation date of a specific customer with In [12]: cust = CustomerProfile.objects.get(pk=100) In [13]: cust.user.date_joined Out[13]: datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) In [14]: cust Out[14]: <CustomerProfile: Chantal Goyette's customer profile> According to the creation date, I would like to make a listing of how many customers has been created for each week. An example of the result could be ... week 28 : [ 09/07/2017 - 15/07/2017 ] - Count : 201 customers ... I probably need a range start_date and end_date where we will list that kind of information. start_date will be the date of the first customer created and the first week create would be the week of this first date. Obviously, the end_date is today and the last week est the week of this end_date. Sorry, I am a very new programmer in python/django. Could anyone have an idea how I could implement such information?