Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to change pywebview and cherrypy base core from mozilla to chrome
I am working on a semi-standalone app (Django app as native desktop app ) using cherrypy as a server, django for the development and Py2exe and pywebview to create the semi standalone app. When I test it on browsers, chrome works fine, but Mozilla is not because of Mozilla's standards, and it's the same for Pywebview's browser. I noticed that it's using Mozilla core: INFO:cherrypy.access.4371749296:127.0.0.1 - - [25/Sep/2017:15:50:39] "GET /static/test/js/ned.js HTTP/1.1" 404 658 "http://localhost:9090/Departments/test/" "Mozilla/5.0 PS:-when I inspect elements on Firefox, I notice that it detect the css file. But the Pywebview does not. -I am following this tutorial: https://moosystems.com/articles/14-distribute-django-app-as-native-desktop-app-01.html Thank you!! -
Django pagination error: That page contains no results
I have results object which has 2 objects inside of it: Teacher 1 and Teacher 2. I wanted to build a pagination, so that only a single teacher is displayed per page. I have a teacher_list function view: def teacher_list(request, **kwargs): #get results variable #get number of teachers count = "{} Results Found".format(results.count()) page = request.GET.get('page', 1) paginator = Paginator(results, 1) try: results = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. results = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. results = paginator.page(paginator.num_pages) return render(request, "users/teacher_list.html", context={"teacher_list": results,"count": count,}) Template.html {% if is_paginated %} {% load users_tags %} {% if teacher_list.has_previous %} <li><a href="?{% url_replace page=teacher_list.next_page_number %}">{{ teacher_list.previous_page_number }}</a></li> {% endif %} <li><a href="#" class="current-page">{{ teacher_list.number }}</a></li> {% if teacher_list.has_next %} <li><a href="?{% url_replace page=teacher_list.next_page_number %}"><i class="sl sl-icon-arrow-right"></i></a></li> {% endif %} {% endif %} The if_paginated logic in the template doesn't work, since I don't get anything displayed. When I manually change the parameter in the URL to page=2, I get the second teacher. So I decided to remove if_paginated and run my pagination without it. The {% if teacher_list.has_next %} part works fine … -
Django Integrity Error:Cannot add or update a child row: a foreign key constraint fails using factory_boy in django unit test
I started writing unit tests for my django app, and I used factory boy to create objects with data. but I'm having this error IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails This my code : models class Group(models.Model): created_by = models.ForeignKey(User) name = models.CharField(_('Name'), max_length=100) description = models.TextField(_('Description'), max_length=1000) members = models.ManyToManyField(User, verbose_name='Members', related_name='member', blank=True) class User(models.Model): username = models.CharField(_('username'),max_length=30,unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), blank=True) password = models.CharField(_('password'), max_length=128) factories class UserFactory(factory.django.DjangoModelFactory): class Meta: model = models.User # to have unique user names username = factory.Sequence(lambda n: 'name%d' % n) first_name = factory.Faker('first_name') last_name = factory.Faker('last_name') # email based on the username email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) password = 'admin' class GroupFactory(factory.django.DjangoModelFactory): class Meta: model = models.Group created_by = factory.SubFactory(UserFactory) @factory.post_generation def members(self, create, extracted, **kwargs): if not create: # GroupFactory.build() return if extracted: # A list of users were passed in, use them for member in extracted: self.members.add(member) and in tests.py I wanted to test the Group model, here how I'm creating Group instance: class GroupTest(BaseModelTest): model = Group group = GroupFactory.build() BaseModelTest contains some abstract methods to … -
Redirecting after autocomplete selection in Django
I have done an autocomplete search bar using Django and JQuery. I managed to get the selection written into the textbox but what I want to do is to redirect the user to an url which uses the data in the textbox. Here are my HTML and JS files: <script> $(function() { $("#places").autocomplete({ source: "{% url "get_places" %}", select: function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } </script> <h1>Bienvenue sur le site de la Kfet !</h1> <h2>Rechercher un Klient dans la barre de recherche ci-dessous :</h2> <!-- jQuery !--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script> <!-- jQuery UI !--> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <div class="ui-widget"> <label for="places">Rechercher un klient : </label> <input id="places"> </div> I guess I have to put a kind of "link" in the JS file, but I don't know how to do it and to pass it the argument I want (the input text selected) Thanks in advance. -
How can I specify expiry time on session in django>=1.6?
Here is my code. Bu it works only if I set 'SESSION_SERIALIZER = "django.contrib.sessions.serializers.PickleSerializer"' in the settings file. ... tz = timezone.utc expire_time = timezone.datetime.utcfromtimestamp(oa_token_expire_time).replace(tzinfo=tz) request.session.set_expiry(expire_time) ... -
Adding new field to existing database table in django python
I have a Postgresql database connected with my django application, Now I have a existing table in the database and want to add a new field to this table using the migrate command. But when I try to add this new field to my models.py and run makemigration and migrate commands, django says there are no new migrations to apply. Can you help me with how to add a new field to existing table. -
Django Filter Backend filter by latitude and longitude
I'm using django-google-maps to get the the location of a place. In models i have this field: models.py class PlaceLocation(models.Model): name = models.CharField(max_length=200) address = map_fields.AddressField(max_length=200) geolocation = map_fields.GeoLocationField(max_length=100) When i add an address it automatically finds the latitude and longitude in this format: 44.4385334,26.005750199999966 I want to use django filter backend to filter by latitude and longitude, but i can't get the values separated. filters.py class LocationFilter(django_filters.FilterSet): ids = NumberInFilter(name='id', lookup_expr='in') geolocation = django_filters.NumberFilter(name='geolocation', lookup_expr='iexact') If i access: 'http://127.0.0.1:8000/locations/places/' it will show me all the places. 'http://127.0.0.1:8000/locations/places/?geolocation=44.4385334,26.005750199999966' it's giving me an empty list. How can i get the values separated so i can filter like this: 'http://127.0.0.1:8000/locations/places/?lat=44.4385334&long=26.005750199999966' -
NoReverseMatch at / with templates in different folders
I have a problem with Django Templates in nested folders. I read the other questions with this problem, but I didn't find the correct solution for my problem. Could you help me? My project has the next schema: . ├── eventus │ ├── eventus │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── wsgi.cpython-36.pyc │ │ ├── db.sqlite3 │ │ ├── settings │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── __init__.cpython-36.pyc │ │ │ │ ├── base.cpython-36.pyc │ │ │ │ └── local.cpython-36.pyc │ │ │ ├── base.py │ │ │ ├── local.py │ │ │ ├── prod.py │ │ │ └── staging.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── myapps │ ├── __init__.py │ ├── __pycache__ │ │ └── __init__.cpython-36.pyc │ ├── events │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── admin.cpython-36.pyc │ │ │ ├── models.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── views.cpython-36.pyc │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ ├── 0001_initial.py … -
django db_table not changing
Hi i have created a dynamic table model and it is not changing whenever i select another table from the list i ve created in the template... if i select the first table to see the data of it and then go back to the list and select the second table i get this error InternalError: (1054, u"Unknown column 'table_name1.id' in 'field list'") So basically when i change from http://127.0.0.1:8000/tables/id=1/ to http://127.0.0.1:8000/tables/id=2/ it gives me error. But if i restart the server and go straight to http://127.0.0.1:8000/tables/id=2/ it works. But now http://127.0.0.1:8000/tables/id=1/ it doesn't work. this is the party of views.py def addview(request, pk): table_name = Crawledtables.objects.get(id=pk) print table_name AllTables._meta.db_table = table_name.name print AllTables._meta.db_table tbl_detail = AllTables.objects.all() print tbl_detail return render(request, 'tables/table_list.html', {'details': tbl_detail}) The prints are just for testing and they work. It prints out the correct table i select. But the tbl_detail it doesn't print when i go to the 2nd table that i selected. only when i restart the server. CrawledTables holds all the table names inside that DB with the date of creation of each table. I get the table name of the CrawledTables and put it in the AllTables._meta.db_table. AllTables access all the tables in … -
`error: unpack requires a string argument of length 4` error when using syncdb to migrate
Never seen anything like it. When I do python manage.py syncdb in a Django app on the Ubuntu terminal, I'm seeing: error: unpack requires a string argument of length 4 I'm not sure what that means or how to fix it. p.s. I know syncdb is deprecated from 1.9 onwards. Put that on the back-burner for the purposes of this question. -
Django, define intermediate model AFTER m2m
I have a m2m field; class MyModel(BaseModel): initiatives = models.ManyToManyField('app.OtherModel',) But now, I need to define my own intermediate model for this m2m, after the fact; class MyModel(BaseModel): initiatives = models.ManyToManyField( 'app.OtherModel', through='app.Intermediate' ) Is there a way for me to seamlessly define one, without Django or my migrations getting really mad at me? Thanks in advance! -
Django RestFrame Work Not Registering Router Urls
I am trying to use Django's rest_framework but am having trouble with the routing. base.urls.py url(r'^api/', include('api.urls', namespace='api'), name='api'), api.urls.py from django.conf.urls import url, include from rest_framework import routers from api import views router = routers.DefaultRouter() router.register(r'test', views.UserViewSet, base_name='NAV') urlpatterns = [ url(r'^', include(router.urls)), ] api.views.py class UserViewSet(APIView): renderer_classes = (JSONRenderer, ) def get(self, request, format=None): querysets = NAV.objects.filter(fund__account_class=0, transmission=3).values( 'valuation_period_end_date').annotate( total_nav=Sum(F('outstanding_shares_par') * F('nav'))).order_by('valuation_period_end_date') content = {'qs': querysets} return Response(content) But when I try http://localhost:8000/api/test, I get a 404 Page not Found error. Any ideas? -
Using TextInput as widget for ManyToManyField
I have two models: class Post(models.Model): title = models.CharField() body = models.TextField() author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) tags = models.ManyToManyField( Tag, related_name='posts', blank=True, ) class Tag(models.Model): name = models.CharField(max_length=30, unique=True, null=False, blank=False) And ModelForm for Post: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'body', 'tags'] widgets = { 'tags': forms.TextInput, } Default widget for tags field in PostForm is MultipleSelect, but I want to use TextInput and force users to type tags and separate them with commas and if there are new tags then add its into database. The question is what field (and how) should I overwrite in PostForm in order to specify logic for setting (before rendered) and getting (after post request) value from TextInput widget? -
Django context error in extended template called by view
I'm working in Django 1.11 with Django-Jet template. Now I need to extend template in order to showing some data retrived from a view. So, I defined my template and my view. Here is the code: views.py from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import View from django.template.context import RequestContext from django.template import Context, Template class MyView(View): def get(self, request, *args, **kwargs): op = str(self.kwargs['op']).strip().lower() pk = self.kwargs['pk'] if op =='get': template='frontend/templates/show_my_data.html' return render_to_response(template,{'foo':'bar'}) else: return HttpResponse("Not found") My simple template: {% extends "admin/base.html" %} {% load i18n admin_urls static admin_modify %} {% block content %} {{ foo }} {% endblock %} settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'static/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] .... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] But when I run a test I get a key error: Request Method: GET Request URL: http://127.0.0.1:8000/admin/data_from_db/get/24/ Django Version: 1.11.2 Exception Type: KeyError Exception Value: 'user' Exception Location: /home/marco/sviluppo/myapp/myvenv/lib/python3.4/site-packages/django/template/context.py in __getitem__, line 87 Python Executable: /home/marco/sviluppo/myapp/myvenv/bin/python So, I make some test, and I found that the problem is (maybe) in context variables. This is my base template that I need … -
Django Pagination with other variables in the GET request in a Function Based View
I've tried to implement the following solution from here: How to paginate Django with other get variables? I added this to my views.py from urllib.parse import urlencode from django import template register = template.Library() @register.simple_tag def url_replace(request, field, value): dict_ = request.GET.copy() dict_[field] = value return dict_.urlencode() def teacher_list(request, **kwargs): paginator = Paginator(results, 1) page = request.GET.get('page') try: results = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. results = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. results = paginator.page(paginator.num_pages) template.html {% if teacher_list.has_next %} <li><a href="?{% url_replace request 'page' teacher_list.next_page_number %}">Next</a></li> {% endif %} However, this gives me: Invalid block tag on line 155: 'url_replace', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? I also tried loading: @register.simple_tag(takes_context=True) def url_replace(context, **kwargs): query = context['request'].GET.dict() query.update(kwargs) return urlencode(query) without success. I also tried: @register.simple_tag(takes_context=True) def url_replace(request, **kwargs): query = request.GET.dict() query.update(kwargs) return urlencode(query) None of these seem to work. -
Django add new option for ForeignKey in a ModelForm using django-autocomplete-light
I am a newbie 'asker' on this community and a newbie developer. Currently, I am developing a project in django and have got stuck while using the django-autcomplete-light to add a new 'option' when the search results return no results. I have read the DAL documentation quite a few times and tried to make it work but I can't seem to find a way. So, here is the issue : I have a ModelForm to add a new object with about 10 fields. On a few fields I have implemented DAL so they can search and add in realtime. The field I have DAL implemented on is a foreign key to another model which in turn has a foreign key field which is needed to be added when a new option is created** The search and the create part is working fine out of the box. But, I have no idea how to update the user foriegnkey field for the option being created. It needs to have current logged in user updated in the field. urls.py urlpatterns = [ url(r'^pilotname-autocomplete/$', views.PilotNameAutoComplete.as_view(create_field = 'name'), name = 'pilotname-autocomplete') ] The dropdown does show 'create "abc"'. see image create option and clicking on … -
can we create unit tests for custom widgets in a django app?
I'm new with unit testing in django, I have referred to the django documentation to write unit tests for views, forms and models. But a question came to my mind about widgets if they could be also tested, since unit tests are made to test every single unit in the project. For example I have a widget that let me write multiple emails in one inputText using a plugin and the widget as follow is made to change ' to " so that the plugin can work. class MultiEmailWidget(Input): def value_from_datadict(self, data, files, name): if name in data: if data[name]: return data[name].replace(']' ,'').replace('[','').replace('"' ,'').replace(',' , '\n') return None def render_value(self , value): """ change ' to " because multiple_email.js do split with " """ if value: return str(value).replace("'",'"') return value def render(self, name, value, attrs=None): value = self.render_value(value) return super(MultiEmailWidget, self).render(name, value, attrs) Is this widget testable ? Or do somebody have some useful links about testing widgets in django ? (if this is testable ofcourse) Thank you in advance :) -
Django: http_permissions interfering with tests
I have a view that list records. If I'm already login, I can access it with no problems. If have not login yet and try to access the page, I get redirected to the login page. So far so good! But during my tests I have the following issue: I am able to successfully login, but when I try to execute a get to list the records, I get a 403 (Permission denied) and a 302 (redirect, likely to login page). I don't understand what is going on. I know http_permissions is interfering with the tests, as I have commented the http_permissions and the test passed. Do I have to grant this http_permissions to the test user? Anyone can cast some light on this? Here is my code: teleconsultoria/models.py ... class Bibliografia(BaseModel): ativa = models.BooleanField(u'Ativa', default=True) link = models.CharField(u'Link', blank=True, max_length=2000,) nome = models.CharField(u'Nome', blank=False, max_length=255,) arquivo = SizeRestrictedFileField( u'PDF da Bibliografia', upload_to='bibliografia', blank=True, null=True, ) class Meta: verbose_name = u'Bibliografia' verbose_name_plural = u'Bibliografias' permissions = ( ('ver_bibliografia', u'Pode ver bibliografia'), ('criar_bibliografia', u'Pode criar bibliografia'), ('alterar_bibliografia', u'Pode alterar bibliografia'), ('excluir_bibliografia', u'Pode excluir bibliografia'), ) ... teleconsultoria/views.py ... class BibliografiaListView(ModelListView): model = Bibliografia app_name = 'teleconsultoria' table = BibliografiaTable search_fields = … -
Url key word argument within CreateView
How to get url keyword argument within get() or other method of CreateView? I tried to use self.kwargs['arg_name'], but without result. Thank you in advance. -
Error during the running django project
I'm running django project but i got this error. Can you help me with this problem? "C:\Program Files\JetBrains\PyCharm 2017.2.2\bin\runnerw.exe" C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\python.exe E:/download/manage.py runserver 8000 Unhandled exception in thread started by .wrapper at 0x0368ED68> Traceback (most recent call last): File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\apps\config.py", line 120, in create mod = import_module(mod_path) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 978, in _gcd_import File "", line 961, in _find_and_load File "", line 936, in _find_and_load_unlocked File "", line 205, in _call_with_frames_removed File "", line 978, in _gcd_import File "", line 961, in _find_and_load File "", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blog' -
Diplay object list, not working
I guess that I will ask a very simple question, but it is a sign that I still do not get something. I have a team model and I would like to display a list of all the team that the logged in user created. I tried with {% extends 'base.html' %} {% block body %} <div class="container"> <div class="jumbotron"> <h2>Select one of your team and link it to your project</h2> </div> <div class="col-md-8 col-md-offset-2"> {% for i in team_set.all %} <p>{{ i.team_name }}</p> {% endfor %} </div> </div> {% endblock %} But first it does not display anything and it is suppose to show all the team and not only the teams that the current logged in user created. COuld you please give me a hand ? model.py : class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") def __str__(self): return self.team_name -
Customized admin drop down menu in Django python
I am just a beginner in python. I have created two admin services called child and parent. Parent - Table id name type Child - Table pid type cname In both services column "type" will be displayed in the drop down list. When creating an entry for parent, if the "type" was not chosen in the parent service. That unchosen Parent id's should shown the in the child service in dropdown Sorry for my bad english # models.py class Parent(models.Model): id = models.IntegerField(blank=False) type = models.ForeignKey( 'self', on_delete=models.CASCADE, blank=True, null=True, related_name='parent_set') name = models.CharField(max_length=20) class Child(models.Model): pid = models.IntegerField(max_length=30, blank=False) Type = models.ForeignKey( Parent, null=True, on_delete=models.CASCADE, related_name='child_set' ) pname = models.CharField(max_length=20) Any help would be appreciated -
How to pass parametres of javascript function when call div with innerhtml
I have a problem, when I pass parameters to a function in javascript, innerHTML doesn't know it. This is my code: function get_similarity(reference) { console.log("reference",reference); var div1= document.getElementById("mylocation"); var div2= document.getElementById("mylocation2"); div2.innerHTML=div1.innerHTML; } When I click on an image, the function GET_similarity(Reference) gets called. This function must make changes to the div below: <div id ="mylocation"> {% for sim in similars %} {% ifequal reference forloop.counter %} {% for sim1 in sim %} <div class="item"> <div class="ct-itemProducts ct-u-marginBottom30 ct-hover"> <label class="control-label sale"> Sale </label> <a href="{% url 'single_product' pk=sim1.id %}"> <div class="ct-main-content"> <div class="ct-imageBox"> <img src="{{ sim1.image }}" width="265" height="194" alt=""><i class="fa fa-eye"></i> </div> <div class="ct-main-text"> <div class="ct-product--tilte"> {{ sim1.zip_code }} {{ sim1.location }} </div> <div class="ct-product--price"> {# <span class="ct-price--Old">$ 450,000</span> #} <span> € {{ sim1.price }}</span> </div> <div class="ct-product--description"> {{ sim1.description }} </div> </div> </div> <div class="ct-product--meta"> <div class="ct-icons"> <span> <i class="fa fa-bed"></i> {{ sim1.bed }} </span> <span> <i class="fa fa-cutlery"></i> 1 </span> </div> <div class="ct-text"> <span> Area: <span>{{ sim1.area }} m2</span></span> </div> </div> </a> </div> </div> {% endfor %} {% endifequal %} {% endfor %} </div> -
The order of dictionary is varied each time
The order of dictionary is varied each time although using OrderedDict. I wrote in views.py from collections import OrderedDict from django.shortcuts import render import json def index(request): with open('./data/data.json', 'r') as f: json_dict = json.loads(f.read()) json_data = OrderedDict() json_data = json_dict return render(request, 'index.html', {'json_data': json_data}) and I wrote in index.html <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css"> </head> <body> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option>{{ i }}</option> {% endfor %} </select> <select name="type" id="type1"> {% for j in json_data.type1.values %} <option>{{ j }}</option> {% endfor %} </select> <select name="type" id="type2"> {% for k in json_data.type2.values %} <option>{{ k }}</option> {% endfor %} </select> <select name="type" id="type3"> {% for l in json_data.type3.values %} <option>{{ l }}</option> {% endfor %} </select> <select name="type" id="type4"> {% for m in json_data.type4.values %} <option>{{ m }}</option> {% endfor %} </select> </script> </body> </html> Variable of i&j&k&l&m has result of json_data,but this dictionary of json_data is not the order.For example i has {'items': [{'---': '---', ‘A’: ‘a’, ‘B’: ‘b’, ‘C: ‘c’, ‘D’: ‘d’}]} but the order of drill down is b=>c=>d=>a.I want to show a =>b=>c=>d .I think this can be done by … -
Variables are not instantiated
def count_customers_per_period(self): if not self.request.GET.get('period'): period = self.request.GET['period'] entry_date_production = datetime.datetime(2017, 6, 1) start_date = CustomerProfile.objects.filter(user__date_joined__gte=entry_date_production).\ first().user.date_joined end_date = CustomerProfile.objects.last().user.date_joined def start_end_period(period): start = start_date - datetime.timedelta(period) end = start + datetime.timedelta(period) if period == 'day': while start < end: array = np.array([]) count = CustomerProfile.objects.filter(user__date_joined__date=start_date).count() array = np.append(array, count) start_date += datetime.timedelta(1) elif period == 'week': start_end_period(7) while start < week: array = np.array([]) count = CustomerProfile.objects.filter(user__date_joined__range=[start, end]) array = np.append(array, count) start = end + datetime.timedelta(1) end = start + datetime.timedelta(7) elif period == 'month': start_end_period(months=1) while start < end: array = np.array([]) count = CustomerProfile.objects.filter(user__date_joined__range=[start, end]) array = np.append(array, count) start = end + datetime.timedelta(1) end = start + datetime.timedelta(months=1) elif period == 'year': start_end_period(years=1) while start < end: array = np.array([]) count = CustomerProfile.objects.filter(user__date_joined__range=[start, end]) array = np.append(array, count) start = end + datetime.timedelta(1) end = start + datetime.timedelta(years=1) return array In this method, I define start_end_period() function, because I need you use it multiple time. Questions : Is it normal that start and end are not instantiated whenever I call start_end_period() function? Is it a good practice to put a function in a method as this way?