Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Error "'DefaultConnectionProxy' object has no attribute '__getitem__'" when calling stored procedure
Hi i'm making a project using python/Django, on my first page (index) i'm calling a stored procedure to fetch the data. def index(request): listOPT = [] Data = [] fluxState = settings.FLUX_MANAGER_STATE if fluxState != True: listOPT.append('FLUX AXEREAL : OFF') cursor = connection['site'].cursor() """MS SQL CALL TO STORED PROCEDURE SP_webGET_RESUME_MVT_INIT_ACTIF """ cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") mouvements = cursor.fetchall() cursor.close() return render(request, 'index.html', locals()) but when executing i get this error "'DefaultConnectionProxy' object has no attribute 'getitem'" Traceback : Environment: Request Method: GET Request URL: http://10.1.20.14:8084/gestion_mouvement/index Django Version: 1.9.6 Python Version: 2.7.11 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Gestion_Mouvement'] Installed 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.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'easy_pjax.middleware.UnpjaxMiddleware'] Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\prog2\PJ1705-027_Automatisation_Silo1_Site_LADON\4-Developpement\Informatique\Web\Gestion_Mouvements\Gestion_Mouvements\Gestion_Mouvement\views.py" in index 26. cursor = connection['site'].cursor() Exception Type: TypeError at /gestion_mouvement/index Exception Value: 'DefaultConnectionProxy' object has no attribute '__getitem__' Any idea on how to fix this ? i saw some people had to add some def unicode to their models but it doesn't seem to work for me. -
Create a django superuser but never let it login
from django.contrib.auth.models import User from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Create default system user without login authorization' def handle(self, *args, **options): User.objects.create_superuser('codobot', 's@codium.co', None) I create the superuser with None password But when I look into the database it still has data in field password. Begin with ! Question: Is that user be able to login? -
WebInterface for a complex programmable logic controll device
My project is to develop a Web Interface for a complex machine. The web interface should be applied for maintaining and diagnostics. The webserver should run on a embedded device. On the embedded device a process which takes all the required data from the complex machine (Sensor data, etc..) and delivers the data to the webserver/webinterface is needed. Another requirement is, the webinterface should be available for a long product live cycle. The webinterface should show realtime data and allow to manipulate data from the complex machine. So I`m completely new at this topic. I found out the Webframework Django and for real-time data the module channels (Websocket) would be fit for this. What experience is available for Django/Channels or other Solutions to fulfill my requirements ? -
Change 'Change model class name' in Django Admin || Change the Change <h1>
I know about: class MFM(models.Model): class Meta: verbose_name = 'my fancy Model' verbose_name_plural = 'my fancy Models' but when I edit MFM in Django Admin, it says 'Change my fancy Model'. But I want it to say 'Settings on my fancy Models'. -
How can I prevent the same task executed one OVER another?
I have a task that pulled data from API and then do system automation (deleting, renaming, ...) with respect to a database (SQLite). I set the task to be executed every 5 minutes. However, sometimes the task takes more than 5 minutes to complete, hence two task run in parallel. This is not good because SQLite database is locked to the task in 0 minute. How can I have, either, the task will not be executed unless the previous task has already finished or the second task queued-up and executed directly after the 0 minute task finished? I have tried to use global boolean to prevent the task to be executed when it is running, like this. automate_is_running = False @periodic_task(run_every=timedelta(minutes=5)) def automate(): if not automate_is_running: automate_is_running = True automate_all() automate_is_running = False But that returns UnboundLocalError: local variable 'automate_is_running' referenced before assignment error. What should I do? -
Django 1.11.5 templates in nested folders
I have a problem with Django Templates in nested folders. 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 │ │ │ ├── 0002_auto_20170924_2140.py │ │ │ ├── __init__.py │ │ │ └── __pycache__ │ │ │ ├── 0001_initial.cpython-36.pyc │ │ … -
django form template designer friendly
I am doing the django project right now. I love the principle of DRY. I have a form which can be applied to all other pages which needs it. I mean a generic form based from django docs. But in the form, there can be select type, file upload, checkbox, radio etc which I dont like the design of native html. I want to leverage the design of material with some customization. How can I do it? Below is my form and my form has checkbox, file upload and multiple select which I need to customize. In a nutshell, my question is how do I make my generic form designer friendly? For now I am handling my form template as follow <form class="form" role="form" action="" method="post"> {% csrf_token %} <div class="form-group label-floating"> <label class="control-label" for="{{ form.company.id_for_label}}">Company</label> <select class="form-control" name="{{ form.company.name }}" id="{{ form.company.id_for_label}}"> <option value=""></option> {% for id, name in form.company.field.choices %} <option value="{{ id }}" class="option">{{ name }}</option> {% endfor %} </select> </div> <div class="form-group label-floating"> <label class="control-label" for="{{ form.name.id_for_label}}">Job Title</label> <input type="text" id="{{ form.name.id_for_label }}" name="{{ form.name.name }}" class="form-control"> </div> <div class="row"> <div class="col-md-6"> <div class="form-group label-floating"> <label class="control-label" for="{{ form.description.id_for_label}}">{{ form.description.label }}</label> <div class="markdownx"> {{ form.description|add_css:'form-control' }} … -
Django - Saving data across paginated formset
I'm using modelformsets to edit 100's of items at once and I'm using pagination according to the solution at http://missfilly.github.io/2013/02/17/how-to-paginate-django-formset/ This works in general, however the form data is not held when moving pages, therefore if I fill in 10 pages of forms, only the last one is saved. I thought sessions may be the way to solve this however there is no POST data when the 'next' button is pressed. Has anyone come across a need to solve this problem before or could advise me on how I may solve it? Edit: I guess Ajax may also be an avenue to go down to solve this but I'm not sure where I would start. -
Django Internal Server Error - RecursionError
I've tried a very basic load test on my django app, something among the lines: for _ in {1..50}; do for x in {1..50}; do curl http://example.com &> /dev/null; done & done After a while server started returning http 500, the reason for that was RecursionError: Serving on http://unix:/tmp/waitress/socket WARNING:django.template:Exception raised while rendering {% include %} for template 'django/forms/widgets/email.html'. Empty string rendered instead. Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/loader_tags.py", line 216, in render return template.render(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 209, in render return self._render(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/usr/local/lib/python3.6/site-packages/django/template/defaulttags.py", line 166, in render values = self.sequence.resolve(context, True) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 708, in resolve obj = self.var.resolve(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 849, in resolve value = self._resolve_lookup(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 882, in _resolve_lookup current = current[bit] File "/usr/local/lib/python3.6/site-packages/django/template/context.py", line 84, in __getitem__ for d in reversed(self.dicts): RecursionError: maximum recursion depth exceeded while calling a Python object WARNING:django.template:Exception raised while rendering {% include %} for template 'django/forms/widgets/text.html'. Empty string rendered instead. Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/loader_tags.py", line 216, in render return template.render(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 209, in render return … -
How to request get method for loading another HTML page
I want to load the another html page using ajax getmethod . Currently I am loading my HTML page simply like as follow- Views.py def about(request): context = {} template = 'about.html' return render(request,template,context) I want to load the same html page using ajax get method so I tried as- def about(request): if request.GET.get('id'): data = request.GET.get('id', '') template = loader.get_template('about.html') context = { 'data': data, } return HttpResponseRedirect(template.render(context, request)) But I am struggling doing this and about.html page content is not displaying, I am beginner in ajax and django, please help me.. this is my about.html page {% extends 'base.html' %} {% block content %} {{data}} <h1>hello about</h1> {% endblock %} Here is urls.py details- url(r'^data/', profiles_views.about, name='about'), I am getting this error- ValueError at /data/ The view profiles.views.about didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://127.0.0.1:8000/data/ Django Version: 1.11.5 Exception Type: ValueError Exception Value: The view profiles.views.about didn't return an HttpResponse object. It returned None instead. Exception Location: C:\Users\prash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py in _get_response, line 198 Python Executable: C:\Users\prash\AppData\Local\Programs\Python\Python36-32\python.exe Python Version: 3.6.2 Python Path: ['C:\\Users\\prash\\Desktop\\tryTen', 'C:\\Users\\prash\\AppData\\Local\\Programs\\Python\\Python36-32\\python36.zip', 'C:\\Users\\prash\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs', 'C:\\Users\\prash\\AppData\\Local\\Programs\\Python\\Python36-32\\lib', 'C:\\Users\\prash\\AppData\\Local\\Programs\\Python\\Python36-32', 'C:\\Users\\prash\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages'] Server time: Mon, 25 Sep 2017 10:39:51 +0000 -
how to use filter() function to fetch data between a range?
I have write down a model like this: from future import unicode_literals from django.db import models Create your models here. class SequenceDetails(models.Model): IDs = models.CharField(max_length=30) country = models.CharField(max_length=30) year = models.IntegerField(max_length=30) def __unicode__(self): return self.IDs To fetch data from the data base i have write down a query like this: SequenceDetails.objects.all().filter(country='india').filter(year='2002') which is returning expected results but further I want to filter out data on the basis of country and year range. I have write down a query set like this. SequenceDetails.objects.all().filter(country='india').filter(year__range =['2002','200']) but its now working and throwing error like given bellow: SyntaxError: invalid syntax How can i achieve this thanks -
Best performance web server to handle AJAX requests
I have a web application that should handle thousands of AJAX requests. I want to know which web server I have to use in order to handle these requests efficiently and with low latency. Back-end logic is written in python. I did try Apache-Mod_WSGI->Django and did not get the required efficiency. I thought of using Python-tornado so any any suggestion on which web server I should use? -
Django Pagination: Loads all Element from first page
I have a page blog.html, and pagination sequence loads just fine, But i query the paginator to show one element in a page to test if pagination works. I have 4 items in DB, the pagination reads 4 elements but shows all elements in all pages . Views.py def blog(request): blog_cat = Blog_Categorie.objects.all() all_blog = Blog.objects.all() page = request.GET.get('page') paginator = Paginator(all_blog, 1) try: blog = paginator.page(page) except PageNotAnInteger: blog = paginator.page(1) except EmptyPage: blog = paginator.page(paginator.num_pages) return render_to_response('blog.html',{'blog':all_blog,'blog_cat':blog_cat,'blog_p':blog}) blog.html <div class="col-lg-12 col-md-12 text-center"> {% if blog_p.has_other_pages %} <ul class="pagination"> {% if blog_p.has_previous %} <li><a href="?page={{ users.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in blog_p.paginator.page_range %} {% if blog_p.number == i %} <li class="active"><span>{{ i }}</span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if blog_p.has_next %} <li><a href="?page={{ users.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} -
Django sending back parameters to the view
I have trouble with one of the page of my project. I have a page, use to look up mouvements history : The Page url contain an ID to search for a specific location for the query Once on the page, the user must choose a begin and end date and then with those informations a sql query get the informations in my view and django fill a datatable with the result. My problem is how do i send back the dates informations to the view once the user picked them on the template ? -
Python: var set in __init__ not available [duplicate]
This question already has an answer here: Python method name with double-underscore is overridden? 2 answers I'm failing to understand the following behaviour inside my debugger: (Pdb++) ll 58 def __init__(self, content=None): 59 import pdb; pdb.set_trace() 60 self.__content = BytesIO() 61 self.__len = 0 62 -> self.read_started = False 63 if content is not None: 64 self.write(content) (Pdb++) !self.__len *** AttributeError: 'FakePayload' object has no attribute '__len' instead I can prove that the object has an attribute like that: (Pdb++) fpl = environ['wsgi.input'] (Pdb++) fpl._ -> <TAB-TAB> _FakePayload__len I have never seen anything like that before and I'd be glad for any hint to make me understand.