Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Passing JSON Dato to View with Loading Download Function
I am writing a Django (1.10) and want users to download report based on the their html selection to the database data. I tried to use Ajax to pass data from template to view, docx to construct the report, and HttpResponse for download. One problem I am facing is it seems like when I am using ajax with url to direct page, the HttpResponse does not work to download the report. However, when I used window.location.href, the download function works but cannot pass through the JSON data (error msg: the JSON object must be str, not 'NoneType'). So, could anyone advise what to do in order to achieve the purpose of both passing JSON data and trigger the downloading function? I list the codes as below for your reference. Many thanks. template js: <script> $(document).on('click', '.exWord', function(){ //get the checkbox list var checkboxes = document.getElementsByName('selection'); var in_news_list = []; // loop over them all for (var i=0; i<checkboxes.length; i++) { // And stick the checked ones onto an array... if (checkboxes[i].checked) { in_news_list.push(checkboxes[i].value); } }; //passing back to views.py for processing $.ajax({ type: "POST", url: '/exRpt/', //this can pass JSON data but cannot trigger download function data: { in_news: JSON.stringify(in_news_list), … -
Extra chars in django template
I've some code like this: <select id="form.category}}"> {% for category in form.category %} <option value="{{ category }}"></option> {% endfor %} </select> And result is: https://zapodaj.net/940329c1516df.png.html Why? -
Django DB Relations
I apologize for the novice question but my head is about to explode. I am trying to learn Django and wanted to create something practical and that I could use. I settled with a small inventory system. The problem I am having is figuring out the best way to have relationships between models for ideal db setup. I have models for the following: Depreciation Policy Manufacturer Customer/Owner Asset Category (Server, laptop etc) Asset Model (Macbook Pro, Proliant DL380 Gen 9 etc) Asset Status (Archived, Deployed, Lost etc) Asset Fields (Generic fields all assets would have, model(FK), status(FK), purchase date etc.) Cpu Server Network Card Right now I have both Server & Network Card inheriting Asset Fields. My goal was to have tables for each type of asset but still have one master table that can reference each asset type's table via a FK so that if I want to display all assets in the database I can just list one table and pull in the relevant information from their related tables instead of having to look through each asset's table. I want something like: Asset Table: id(pk), model(fk), status(fk), serial Number, purchase date, cost, location, server_id/network_card_id(fk) Server Table: id(pk), customer, … -
Leave Debug on in Django for internal application
I'm working on a Django project that I took over for someone else that is only used internally. It's not deployed to a website and can only be accessed on a local network. The previous developer had left DEBUG = True in settings.py. Django docs really emphasize that leaving DEBUG=True when the site is in production is bad. The site is inaccessible by anyone not on the local network, and is only even looked at by ~5 people regularly. Aside from security reasons, is there any other downside to operating permanently in DEBUG mode? -
I have issues finding a python book for intermediate/advance programming [on hold]
I have red half a dozen of Books to learn Python and Django. I enjoyed them very much and I learnt a lot but now, when I work in real scenarios certain things are missing. So I am looking for a book with some non standard topics like webservices, complex data mdoels, blobs, advanced web development, etc. Everything I look in online stores seems to be more of the same (django basics, python basics) I would apreciate any advice for a book in english or spanish, free or not -
Django - pass variable to template using mqtt
I'm using mqtt it's working well but I'm trying to print in template the message i'm getting in console. Can anyone help me? this is what I have: // main function def main(request,id): mensaje = 'mymsg' client = mqtt.Client() client.connect("iot.eclipse.org", 1883) client.publish("path", payload=mensaje, qos=x, retain=False) client.on_subscribe = on_subscribe client.on_message = on_message client.subscribe("path", qos=x) client.loop_forever() return render(request, 'test.html') // subscribe def on_subscribe(client, userdata, mid, granted_qos): print("Subscribed: "+str(mid)+" "+str(granted_qos)) // message received def on_message(client, userdata, msg): print (str(msg.payload)) # this is what I need in template or main function Basically by console I'm getting what's in def on_message() I need that in template. How can I pass what's in def on_message() to def main() or just send that to template from def on_message() ? NOTE: my code is working, i'm receiving a mssg from a .jar but all I need is to show in template what's in def on_message() Thanks in advance -
Django 1.10 - Maintaining context object information
My question is, is there a way to maintain the context object over multiple views? Say you are at the home page, you click a link to go to a specific part of the application but you want to maintain the context information as to not excessively query the DB for this information every time you change views. I know of mixins and such, but these do not seem to maintain the information, or am I wrong? Question is, can I access the context information and pass it to the next view? -
Django -> queryset[index] Index out of range
I don't know why it's happening this.I got a queryset that contains 2663 objects, and when i try to access the objects with index 2662 returns Index out of range. I'm looking for someone to explain me why's happening this. -
Django All-Auth Role Based Signup
Having read many stack overflow questions, tutorials etc on all-auth I keep getting the impression that it only supports the registration of one type of user per project. I have two usecases A business user authenticates and registers his business in one step. A developer user authenticates and just fills in the name of his employer (software company). I do not want the developer to see the business fields when he signs up. i.e his signup form is different. If, in fact signup should be common and the user specific details should be left to a redirect, how to accomplish this from social auth depending on user type? -
SSL Bad Handshake - AWS - Requests
I have a django app on AWS pushed with Elastic Beanstalk that is returning some SSL errors when a make a requests.POST The error I'm getting is SSLError: ("bad handshake: SysCallError(-1, 'Unexpected EOF')",) File "/opt/python/current/app/my_app/helpers.py", line 74, in revoke req = revoke_token(employee) File "/opt/python/current/app/my_app/helpers.py", line 96, in revoke_token req = requests.post(url, data=data, headers=headers) File "/opt/python/run/venv/lib/python2.7/site-packages/requests/api.py", line 107, in post return request('post', url, data=data, json=json, **kwargs) File "/opt/python/run/venv/lib/python2.7/site-packages/requests/api.py", line 53, in request return session.request(method=method, url=url, **kwargs) File "/opt/python/run/venv/lib/python2.7/site-packages/requests/sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "/opt/python/run/venv/lib/python2.7/site-packages/requests/sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "/opt/python/run/venv/lib/python2.7/site-packages/requests/adapters.py", line 447, in send raise SSLError(e, request=request) SSLError: ("bad handshake: SysCallError(-1, 'Unexpected EOF')",) $ openssl version OpenSSL 1.0.1k-fips 8 Jan 2015 Code causing Error def revoke_token(employee): if employee.customer.is_sandbox: url = revoke_token_url_sandbox else: url = revoke_token_url data = { 'token': employee.auth_token, } headers = { 'content-type': 'application/x-www-form-urlencoded' } print "url - {} - data - {} - headers - {}".format(url, data, headers) req = requests.post(url, data=data, headers=headers) return req output of printing url, data, headers [Thu Feb 02 15:22:39.530520 2017] [:error] [pid 16985] url - https://login.salesforce.com/services/oauth2/revoke - data - {'token': u'00ANONYMIZEDkAQIk40FdTB6nFAhqD.ON4UBJRl5uiDoIrLMDR4DxrXt7SHDTHVL_U2lDi67thYweyl55dSkcrUvXZLheNJ_5SgH9sgNoq'} - headers - {'content-type': 'application/x-www-form-urlencoded'} pip freeze awsebcli==3.8.4 beatbox==32.1 beautifulsoup4==4.5.1 blessed==1.9.5 boto==2.43.0 botocore==1.4.75 … -
django pagination returns all data after clicking any page in search result
I paginate search result. At first, query set gives me perfect result and initial page numbers indicate correctly, but when click to any page number, it accepts search key as null and get all data from db. here is the code def search(request): searchKey = request.POST.get("key", "") searchRequestsInitial = ScRequests.objects.filter(description__contains=searchKey) searchCount = searchRequestsInitial.count() page = request.GET.get('page', 1) paginator = Paginator(searchRequestsInitial, 10) try: searchRequests = paginator.page(page) except PageNotAnInteger: searchRequests = paginator.page(1) except EmptyPage: searchRequests = paginator.page(paginator.num_pages) context = {'searchRequests':searchRequests,'searchCount':searchCount,'searchKey':searchKey} template = "searchResult.html" return render(request,template,context) in template: <tbody> {% if searchRequests %} {% for searchRequest in searchRequests %} <tr> <td>{{searchRequest.description|convert_utf8|shortName}}</td> <td>{{searchRequest.title|convert_utf8|shortName}}</td> <td>{{searchRequest.sender}}</td> </tr> {% endfor %} {% endif %} </tbody> </table> {% if searchRequests.has_other_pages %} <ul class="pagination"> {% if searchRequests.has_previous %} <li><a href="?page={{ searchRequests.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in searchRequests.paginator.page_range %} {% if searchRequests.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if searchRequests.has_next %} <li><a href="?page={{ searchRequests.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} -
How Django processes a request when matched regular expression returned no named groups?
I'm the newbie in django development field. I read the documentation of django especially HTTP/URL. There is a information about 'How Django processes a request'. (https://docs.djangoproject.com/en/1.10/topics/http/urls/) They said "If the matched regular expression returned no named groups, then the matches from the regular expression are provided as positional arguments." I can't understand what happen when the regular expression return no named groups (like ""). If you can tell me with example codes, it will be the best :) -
SQL injection prone?
I'm building a website with Django where there will be a sql console for performing raw queries on the database (SQLite3). I know that this is a dangerous idea and that is why I'm wondering if my rather inelegant and brute solution will work. I want the user to be able to perform only SELECT statements and therefore before the query is executed on the database I am simply making an assert statement which checks that the words 'DROP', 'UPDATE' or 'CREATE' are not in the query string and another one to assert that the word 'SELECT' is. If this is not satisfied the query is not being processed. Is it good enough or am I missing something here? -
Synchronous XMLHttpRequest on a django view
went i run this code y get this error in the browser error browser chrome Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/ my view {% block beneficios %} <script type="text/javascript"> $('[data-toggle="tabajax"]').click(function(e) { var $this = $(this), loadurl = $this.attr('href'), targ = $this.attr('data-target'); $.get(loadurl, function(data) { $(targ).html(data); }); $this.tab('show'); return false; }); $(document).ready(function(){ $('[data-toggle="tabajax"]:first').click(); }); </script> <ul class="nav nav-tabs tabs-up" id="friends"> <li><a href="{% url 'detalle3' pk=1 %}" data-target="#contacts" class="media_node active span" id="contacts_tab" data-toggle="tabajax" rel="tooltip"> Contacts </a></li> <li><a href="{% url 'detalle3' pk=2 %}" data-target="#friends_list" class="media_node span" id="friends_list_tab" data-toggle="tabajax" rel="tooltip"> Friends list</a></li> <li><a href="{% url 'detalle3' pk=3 %}" data-target="#awaiting_request" class="media_node span" id="awaiting_request_tab" data-toggle="tabajax" rel="tooltip">Awaiting request</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="contacts"> </div> <div class="tab-pane" id="friends_list"> </div> <div class="tab-pane" id="awaiting_request"> </div> </div> {% endblock beneficios %} -
Django : no CSS on Admin page
After reading some tutorials and questions on SO (for example : css not loading in my login and admin page in django), I don't find a way to load css stylesheet. It comes from migration between my MacOSX localhost machine and my new Ubuntu distant server. My admin login page looks like : As you can see, I don't have CSS which is taken account from /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/ All my admin part looks like this : without CSS I have a settings.py file which looks like : # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', 'app2', 'app3', 'app4', 'app5', 'django_countries', 'app6', 'app7', ] MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/var/www/html/myproject/templates/', '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/', '/var/www/html/myproject/app1/templates/', '/var/www/html/myproject/app2/templates/', '/var/www/html/myproject/app3/templates/' ], 'APP_DIRS': True, 'OPTIONS': { 'debug' : DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "/var/www/html/myproject/static/"),) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # SESSION AGE 100 Minutes SESSION_COOKIE_AGE = 100*60 … -
Regex Pattern For Django URL That Accepts Digits and Chars
My url pattern is like dis example.com/pv/56EETLN0/ How I came about the 56EETLN0 is with the below code. def ref_url_tag(size=8, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) I have a field called refurl and by default it saves what function ref_url_tag prints out. In my Urls.py, I did this but none of them is working. url(r'^pv/(?P<refurl>.*)/$', m_views.single_page, name='single_page'), url(r'^pv/(?P<refurl>[\w\-]+)/$', m_views.single_page, name='single_page'), I'm getting the below error: Reverse for 'single_page' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['pv/(?P<refurl>[\\w\\-]+)/$'] What am I missing in order to match the pattern? -
Neo4j and Django testing
I'm using Django and Neo4j together with neomodel as the OGM (ORM for graphs). It's working nicely but when it comes to testing, Neomodel doesn't support the usual Django behavior with the relational databases. I mean that it doesn't create a temporal Neo4j instance that is created at the beginning of testing and destroyed once it ends. I've been doing some research and I've found two possible solutions: The first, is creating a custom discover runner where you stop the development database, then start a test database from another path, run your tests and finally, stop the test instance and start the development instance again. This solution is proposed in the thread Django testing of neo4j database. The following code has been adapted for 3.1.1 Neo4j version: from time import sleep from subprocess import call from django.test.runner import DiscoverRunner from py2neo import authenticate class DiscoverRunner(DiscoverRunner): def setup_databases(self, *args, **kwargs): # Stop your development instance call("sudo service neo4j stop", shell=True) # Sleep to ensure the service has completely stopped sleep(1) # Start your test instance (see section below for more details) success = call("neo4j_test/neo4j-community-3.1.1/bin/neo4j" " start", shell=True) # Need to sleep to wait for the test instance to completely come up … -
OperationalError table accounts_post has no column named image1
I got an error that OperationalError at /accounts/upload_save/ table accounts_post has no column named image1 . Traceback told photo_obj.save() was wrong. In views.py,I wrote @require_POST def regist_save(request): form = RegisterForm(request.POST) if form.is_valid(): user = form.save() login(request, user) context = { 'user': request.user, } return redirect('profile') context = { 'form': form, } return render(request, 'registration/accounts/regist.html', context) def photo(request): d = { 'photos': Post.objects.all(), } return render(request, 'registration/accounts/profile.html', d) def upload(request, p_id): d = { 'p_id': p_id, } return render(request, 'registration/accounts/photo.html', d) def upload_save(request): photo_id = request.POST.get("p_id", "") print(photo_id) print("hoge") if (photo_id): photo_obj = Post.objects.get(id=photo_id) else: photo_obj = Post() files = request.FILES.getlist("files[]") print(files) photo_obj.image1 = files[0] photo_obj.save() return redirect("registration/accounts/photo.html") My database has image colum,so I changed photo_obj.image1 = files[0] into photo_obj.image = files[0] . But I got a same error like table accounts_post has no column named image . So,I really cannot understand how to fix. I wrote in urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^regist/$', views.regist,name='regist' ), url(r'^regist_save/$', views.regist_save, name='regist_save'), url(r'^profile/$', views.profile, name='profile'), url(r'^photo/$', views.photo, name='photo'), url(r'^upload/(?P<p_id>\d+)/$', views.upload, name='upload'), url(r'^upload_save/$', views.upload_save, name='upload_save'), ] in photo.html {% extends "registration/accounts/base.html" %} {% block body %} <div class="container"> {% for photo in photos %} <h2 class="page-header">{{ photo.title }}</h2> … -
uWSGI process got segmentation fault by cx_Oracle from the backtrace
The environment is uWSGI+django+OracleDB, sometimes we found the uwsgi process is terminated when the program is reading data from Oracle db. From the uwsgi log, we can see the backstrace pointed to cx_Oracle. When uwsgi process is terminated, the program is running below scenario: tomcat->nginx->uwsgi->django->cx_Oracle->Oracle client->Oracle DB. Config: python2.7.8 cx-Oracle==5.2.1 uWSGI==2.0.12 Django==1.8.2 oracle-instantclient12.1-basic-12.1.0.2.0-1.x86_64.rpm oracle-instantclient12.1-devel-12.1.0.2.0-1.x86_64.rpm The frequency of such issue is very low, and we caught two kinds of backtrace in log: Backtrace#1: !!! uWSGI process 7551 got Segmentation Fault !!! *** backtrace of 7551 *** uwsgi(uwsgi_backtrace+0x29) [0x47de99] uwsgi(uwsgi_segfault+0x21) [0x47e021] /lib64/libpthread.so.0() [0x38bea0f7e0] /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(+0x1f9eada) [0x7f7503d60ada] ...... /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(kpedbg_dmp_stack+0x194) [0x7f7503e00484] /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(kpeDbgCrash+0xd2) [0x7f7503e006e2] /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(kpureq2+0x88d) [0x7f750231796d] /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(OCIStmtPrepare2+0x9c) [0x7f75022ef8cc] /home/shapp/virtual_env1/lib/python2.7/site-packages/cx_Oracle.so(+0x120ec) [0x7f7504d910ec] /home/shapp/virtual_env1/lib/python2.7/site-packages/cx_Oracle.so(+0x1aeaf) [0x7f7504d99eaf] uwsgi(PyEval_EvalFrameEx+0x5620) [0x5586e0] uwsgi(PyEval_EvalCodeEx+0x877) [0x55a1c7] ...... Backtrace#2: !!! uWSGI process 24920 got Segmentation Fault !!! *** backtrace of 24920 *** uwsgi(uwsgi_backtrace+0x29) [0x47de99] uwsgi(uwsgi_segfault+0x21) [0x47e021] /lib64/libpthread.so.0() [0x38bea0f7e0] /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(skgfqio+0x297) [0x7f8c172a89b7] /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(sdbgrfbibf_io_block_file+0x134) [0x7f8c15a1e374] /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(dbgrfrbf_read_block_file+0x244) [0x7f8c159dfb84] /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(dbgrmflrp_read_page+0x89) [0x7f8c15ab8dd9] ...... /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(kpedbg_dmp_stack+0x194) [0x7f8c16f4d484] /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(kpeDbgCrash+0xd2) [0x7f8c16f4d6e2] /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(kpureq2+0x8ee) [0x7f8c154649ce] /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1(OCIStmtPrepare2+0x9c) [0x7f8c1543c8cc] /home/shapp/neo4j_uwsgi/lib/python2.7/site-packages/cx_Oracle.so(+0x120ec) [0x7f8c17ede0ec] /home/shapp/neo4j_uwsgi/lib/python2.7/site-packages/cx_Oracle.so(+0x1aeaf) [0x7f8c17ee6eaf] uwsgi(PyEval_EvalFrameEx+0x5620) [0x5586e0] uwsgi(PyEval_EvalCodeEx+0x877) [0x55a1c7] ...... -
Django populate() isn't reentrant on multilanguage setup with different domains
I run a Django==1.10.4 website with 4 different languages. Each of them has there own domain. Only 2 or 3 of them are working at the same time. One or more is failing with this error: This is the error which appears after I kill my wsgi processes and access the page the first time: mod_wsgi (pid=8416): Target WSGI script '/var/www/user324/htdocs/ukmypagecom/app.wsgi' cannot be loaded as Python module. mod_wsgi (pid=8416): Exception occurred processing WSGI script '/var/www/user324/htdocs/ukmypagecom/app.wsgi'. Traceback (most recent call last): File "/var/www/user324/htdocs/ukmypagecom/app.wsgi", line 11, in <module> application = django.core.wsgi.get_wsgi_application() File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/db/models/base.py", line 119, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/db/models/base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/db/utils.py", line 211, in __getitem__ backend = load_backend(db['ENGINE']) File "/var/www/user324/priv/venv/myvenv/lib/python2.7/site-packages/django/db/utils.py", line 134, in load_backend raise ImproperlyConfigured(error_msg) ImproperlyConfigured: 'django.contrib.gis.db.backends.mysql' … -
Submit form on blur using Django
I am trying to create a page which contains a bunch of fields that can be updated by the user by clicking an Edit button (which will show the form for that field) and then changing the form. Changes to the form (selecting an item from a dropdown list, for example) should be submitted to the backend as soon as they are chosen. If you look at some of the settings pages on Facebook, you'll see roughly what I'm aiming for. The site is built using django and I can obviously do this using jquery etc. but I'm wondering if it would make sense to use something like angular for this? Or react maybe? Is it sensible to spend time trying to learn something like angular (I've never used it) for this or is jquery the way to go, seeing as I only need a single page on my site? -
Django: Validation at model (not forms) level?
I want this to fail: MyModelWithSlug.objects.create(name='Foo', slug='abc . ü') The string abc . ü is not a valid slug in django. How to make above line fail? -
Django autocomplete with multiplechoice give me invalid form
I'm using django-autocomplete-light and I'm trying to make form like this: from dal import autocomplete class ReportForm(forms.Form): week_number = forms.MultipleChoiceField( choices=generate_week_numbers(), label=_("Week number"), widget=forms.SelectMultiple(), required=False ) units = forms.MultipleChoiceField( widget=autocomplete.Select2Multiple(url='units-ac'), required=False ) And autocompletes's code: class UnitsAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return Unit.objects.none() Unit.objects.filter(#somefilters#) if self.q: qs = qs.filter(name__icontains=self.q) return qs And when I sumbit the form I get an error: <ul class="errorlist"><li>units<ul class="errorlist"><li>Select a valid choice. 24 is not one of the available choices.</li></ul></li></ul> How can I resolve this? -
Could Not Login Postgres 9.5 SQL Even with Correct Password
I am using Postgres 9.5 SQL for my Django project because of Heroku's requirement, however I come across a situation that cannot solve and would like to seek your advice. Specifically, after using the Postgres for a couple of days, the system could not let me login (the database postgres) even with my correct password. When I am trying to login, I was given the below message: 'The server doesn't accept connections: the connection library reports could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?' Honestly, I have not changed anything. I have looked up the Internet for resources and tried the following things but in vain: reset the pg_hba.conf to trust all the host. Done but not work. The following is my current settings: . # TYPE DATABASE USER ADDRESS METHOD # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a … -
Append to parent's filter_horizontal in Django admin
Similar to how ModelAdmin.get_fields() and other such helper functions allow you to append items on subclasses, is it possible to do this for filter_horizontal? At the moment I have to manually re-write the list on each Child admin class: BaseAdminClass(admin.ModelAdmin): ... fields = ['some_field', 'many_to_many_field'] filter_horizontal = ['many_to_many_field'] ChildAdminClassOne(admin.ModelAdmin): def get_fields(self, request, obj=None): fields = super(ChildAdminClass, self).get_fields(request, obj) return fields + ['another_field'] # Something like get_filter_horizontal()? filter_horizontal = ['many_to_many_field' + 'another_field'] ChildAdminClassTwo(admin.ModelAdmin): def get_fields(self, request, obj=None): fields = super(ChildAdminClass, self).get_fields(request, obj) return fields + ['other_field'] filter_horizontal = ['many_to_many_field' + 'other_field']