Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateDoesNotExist in Django (1.9)
I have installed in a local development environment (vagrant box/ubuntu trusty) a Django project which uses several applications all loaded properly in the settings.py file. When I try to run the application (python manage.py runserver 0.0.0.0:8000) I get: TemplateDoesNotExist at / geodash/maps/base.yml Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/vagrant/sparc2.git/sparc2/templates/geodash/maps/base.yml (Source does not exist) django.template.loaders.app_directories.Loader: /home/vagrant/.venvs/sparc2/local/lib/python2.7/site-packages/django/contrib/admin/templates/geodash/maps/base.yml (Source does not exist) django.template.loaders.app_directories.Loader: /home/vagrant/.venvs/sparc2/local/lib/python2.7/site-packages/django/contrib/auth/templates/geodash/maps/base.yml (Source does not exist) django.template.loaders.app_directories.Loader: /home/vagrant/.venvs/sparc2/local/lib/python2.7/site-packages/django/contrib/gis/templates/geodash/maps/base.yml (Source does not exist) django.template.loaders.app_directories.Loader: /home/vagrant/.venvs/sparc2/local/lib/python2.7/site-packages/pinax_theme_bootstrap/templates/geodash/maps/base.yml (Source does not exist) django.template.loaders.app_directories.Loader: /home/vagrant/.venvs/sparc2/local/lib/python2.7/site-packages/django_forms_bootstrap/templates/geodash/maps/base.yml (Source does not exist) django.template.loaders.app_directories.Loader: /home/vagrant/.venvs/sparc2/local/lib/python2.7/site-packages/autocomplete_light/templates/geodash/maps/base.yml (Source does not exist) django.template.loaders.app_directories.Loader: /home/vagrant/.venvs/sparc2/local/lib/python2.7/site-packages/leaflet/templates/geodash/maps/base.yml (Source does not exist) django.template.loaders.app_directories.Loader: /home/vagrant/sparc2.git/sparc2/templates/geodash/maps/base.yml (Source does not exist) The expected indeed doesnt exist in any of these paths. But it does exist in another folder which have this path: /home/vagrant/geodash-framework-django.git/geodash/templates/geodash/maps How do I include this in my settings.py file? -
Django - migrate database from sqlite to mysql
I am trying to migrate my sqlite database to mysql. I used dumdata/loaddata commands: python manage.py dumpdata > datadump.json # next changed my settings.py to # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'testowa', 'USER': 'testowy', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '3306', } } and python manage.py loaddata datadump.json I get an error: django.db.utils.ProgrammingError: (1146, "Table 'testowa.constance_config' doesn't exist") Any ideas? -
Environment can only contain strings- wagtail CMS, Django
I am getting the following error while runserver command in Django. I am using wagtail CMS. Could someone help me with this, please ? C:\Users\MAFON\Desktop\mafonglobal>python manage.py runserver Traceback (most recent call last): File "manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 62, in execute super(Command, self).execute(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 101, in handle self.run(**options) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 110, in run autoreload.main(self.inner_run, None, options) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 332, in main reloader(wrapped_main_func, args, kwargs) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 303, in python_reloader exit_code = restart_with_reloader() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 289, in restart_with_reloader exit_code = subprocess.call(args, env=new_environ) File "C:\Python27\lib\subprocess.py", line 168, in call return Popen(*popenargs, **kwargs).wait() File "C:\Python27\lib\subprocess.py", line 390, in __init__ errread, errwrite) File "C:\Python27\lib\subprocess.py", line 640, in _execute_child startupinfo) TypeError: environment can only contain strings -
Python Unittest mocked method returns None
I run teh following code. If I run the the first time, the mocked methode returns the correct value ( fake_temp ), but when I use the mocked method in a second test, it returns None. I strongly belive that it is a side_effect configuartion, but I'm not sure whitch I to use. Does someone can give me a hint about this issue? import unittest ... def test_heating_state_from_off_to_on(self): fake_temp = 10 with mock.patch.object(HeatingStateOn, '_getCurrentTemperature', return_value=fake_temp) as mock_temp: state = HeatingStateOff() state.setZone(self.heatingMapping) state = state.validateTemperature() self.assertIsInstance(state, HeatingStateOn) class FakeHeatingStateOn(HeatingStateOn): def __new__(cls,*args, **kwargs): return 21 -
FilterSelectMultiple in Django form not saving
I'm trying to create a user permission field in my webpage using django form to work exactly like in admin page using FilterSelectMultiple. Currently it populating the data correctly and the select and deselect button is working, but I unable to save the form, whenever I hit save, the page refresh and all the user are deselect again. The user = forms.ModelMultipleChoiceField(queryset=Project.objects.all(), widget=FilteredSelectMultiple('User', is_stacked=False)) is not working. How can I fix this? Any help is much appreciated thank you Below is my code : HTML : <link rel="stylesheet" type="text/css" href="/static/admin/css/base.css" /> <link rel="stylesheet" type="text/css" href="/static/admin/css/forms.css" /> <form method="POST" enctype="multipart/form-data" id=setting_form" name="setting_form" onsubmit="updateDiv()">{% csrf_token %} <!--USER--> <div class="field"> <label>User permissions:</label> <div class="related-widget-wrapper"> <select name="user_permissions" id="id_user_permissions" multiple="multiple" class="selectfilter" data-field-name="user permissions" data-is-stacked="0"> <option value={{ form.user }}></option> </select> </div> <script src="/admin/jsi18n"></script> <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> View.py def project_setting(request): form = EditProjectForm(request.POST or None, request.FILES or None, instance=selected_project, prefix='settings') if form.is_valid(): inst = form.save(commit=False) inst.save() form.save_m2m() return HttpResponseRedirect('/dashboard/projects/{}/setting'.format(project_id)) context = { 'form': form, } return render(request, 'dashboard/projects/setting.html', context=context) Form.py : from django.contrib.admin.widgets import FilteredSelectMultiple class EditProjectForm(forms.ModelForm): class Meta: model = Project fields = '__all__' user = forms.ModelMultipleChoiceField(queryset=Project.objects.all(), widget=FilteredSelectMultiple('User', is_stacked=False)) Model.py : class Project(models.Model): user = models.ManyToManyField(Employee, blank=True) -
Supress Oracle Database Exceptions in Django
I have created a middleware to handle oracle database errors so that the default oracle exception/error pages should not be displayed to the users: Middleware code: class DatabaseErrorMiddleware(object): def process_exception(self, request, exception): print("This is exception") return get_json_response(403, "HTTP Error 500: Internal Server Error") The middleware class is added to the last in the middleware list so that the custom middleware should be executed first once the exception/error occurred: settings.py MIDDLEWARE_CLASSES = ( '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', 'simple_history.middleware.HistoryRequestMiddleware', 'AUCAReturn.middleware.DatabaseErrorMiddleware', ) To remove this exceptions page: django 1.7.7 version -
I am working on a Django project and need to host it on a Windows server using IIS how to add the fcgi server in my app?
Need help on how to connect my django app and windows IIS server I want to create a django app and host it on windows server but I am not able to put the fcgi file -
Fastest way to find first match index of lots of strings in large text
I have implemented a quick find algorithm in python 2.7.13. It does what I want but I have small performance issues. These are my algorithms specificities : I have a text that is an HTML article, it is generally between 5 000 to 50 000 characters but it can be as big as 300 000 characters. I have a list of "words" that can contain special characters (é,à,ø,/...) and spaces, generally hundreds to a few thousands words. Words are 2 to 256 characters long. I need to ignore found items contained in HTML tags I need indexes in text of matches I only need the first match for each words What I have is this implementation : def find_indexes(text, words): words_indexes = [] found_words = [] authorized_characters = [u' ', u'.', u':', u';', u'?', u'!', u'¿', u'¡', u'…', u'(', u')'] text_length = len(text) for j, word in enumerate(words): i = 0 # This loop serves to go to the next word find if the first one isn't valid (contained in another word or in HTML tag) while i != -1: i = text.find(word, i + 1) if i + 1 + len(word) < text_length: # We check the before and … -
Is it better to put queries in models.py or views.py
I wanted to make a query query = Rating.objects.filter(human=pk) friendliness = query.aggregate(Avg('friendliness')) punctuality = query.aggregate(Avg('punctuality')) knowledge = query.aggregate(Avg('knowledge')) and show this in my html. Is the best practice to put it in views.py or is it better to put it in models.py? -
Django complex filter and order
I have 4 model like this class Site(models.Model): name = models.CharField(max_length=200) def get_lowest_price(self, mm_date): '''This method returns lowest product price on a site at a particular date''' class Category(models.Model): name = models.CharField(max_length=200) site = models.ForeignKey(Site) class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey(Category) class Price(models.Model): date = models.DateField() price = models.IntegerField() product = models.ForeignKey(Product) Here every have many category, every category have many product. Now product price can change every day so price model will hold the product price and date. My problem is I want list of site filter by price range. This price range will depends on the get_lowest_price method and can be sort Min to Max and Max to Min. Already I've used lambda expression to do that but I think it's not appropriate sorted(Site.objects.all(), key=lambda x: x.get_lowest_price(the_date)) Also I can get all site within a price range by running a loop but this is also not a good idea. Please help my someone to do the query in right manner. -
Connection Not established error in django-tastypie
I was trying to create a REST API in django using tastypie framework. I created all the urls,models and resources for the API. But on posting data to the API it is showing the error: Connection Not established error. What may be the reason for this. I am using django 1.11 and tastypie 0.14.0. -
Table in crispy-forms (django)
I want to show a table containing a set of model objects. My model class: from django.dbfrom django.db import models from django.utils.translation import ugettext_lazy as _ class DamageKind(models.Model): name = models.CharField(_('damage kind'), max_length=64) regions = models.ManyToManyField(Region) def __str__(self): return self.name class Meta: verbose_name = _('damage kind') verbose_name_plural = _('damage kinds') my form class: from django import forms from crispy_forms.helper import FormHelper from .models import DamageKind class DamageKindList(forms.Form): def __init__(self, *args, **kwargs): self.damagekinds = kwargs.pop('damagekinds', []) self.helper = FormHelper() self.helper.form_method = 'post' super().__init__(*args, **kwargs) My base template base.html: <!DOCTYPE html> <html> <body> {% block list %} {% endblock %} </body> </html> my list_damagekinds.html: {% extends "./base.html" %} {% load crispy_forms_tags %} {% block list %} <form action="" method="post"> {% csrf_token %} {{ damagekind_form }} </form> {% endblock %} and my views.py: def list_damagekinds(request): damagekinds = DamageKind.objects.all() return render( request, 'damage/list_damagekinds.html', {'damagekind_form': DamageKindList(damagekinds=damagekinds), } ) so my question is how I can make a table containing all the names of the damagekinds by not beeing editable, so just showing these. Thanks in advance. -
ImportError: No module named apps Django
when I run django application,get this error: Traceback (most recent call last): File "new_console_app.py", line 2, in <module> File "/usr/lib/python2.7/site- packages/PyInstaller/loader/pyimod03_importers.py", line 389, in load_module File "new_web/wsgi.py", line 16, in <module> File "site-packages/django/core/wsgi.py", line 14, in get_wsgi_application File "site-packages/django/__init__.py", line 18, in setup File "site-packages/django/apps/registry.py", line 85, in populate File "site-packages/django/apps/config.py", line 112, in create File "importlib/__init__.py", line 37, in import_module ImportError: No module named apps Failed to execute script new_console_app How can I resolve this error? Django version 1.8 -
django runserver gets killed
When there are simultaneous ajax request sent to runserver its gets killed. I know earlier it was single threaded, but --nothreading option says it is now multithreaded by default. Still, my runserver gets killed. I am running on django==1.10 and python==2.7 How do I stop runsever from getting killed? Or This is because of python's multithreading limitations? -
Minify, obfuscate, and compress the project created in Django framework
I am developing product using Django framework. I don't want to share the actual source code with client. So I need to obfuscate source code. Please let me know how to achieve same for Django frameworks ? Thanks in advance !!! -
.sock file "Conection refused" when NGINX on docker container, uWSGI on macOS
I installed Django, uWSGI and Docker on my Mac, then i run a NGINX docker image for serving web with sharing my project directory. docker run -v ~/Projects:/Projects -v /Projects/My-Project/My-Project_nginx.conf:/etc/nginx/conf.d/My-Project_nginx.conf:ro -p 80:80 -d nginx After i start uWSGI and test, NGINX got error "111: Connection refused": 2017/08/09 05:38:00 [error] 18#18: *11 connect() to unix:///Projects/My-Project/My-Project.sock failed (111: Connection refused) while connecting to upstream, client: 172.17.0.1, server: 172.16.10.30, request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://unix:///Projects/My-Project/My-Project.sock:", host: "172.16.10.30", referrer: "http://172.16.10.30/" 172.17.0.1 - - [09/Aug/2017:05:38:00 +0000] "GET /favicon.ico HTTP/1.1" 502 575 "http://172.16.10.30/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" "-" The problem seems on my Mac, Because i tested them worked on Ubuntu. Sharing .sock file is fine. Someone said "Socket sharing is possible, but not supported on OSX", is that true? Why? Can i fix it some way? Or, some better way for my case? I know docker-compose is born for this, but i want more flexible way for assembling by my own and less rely on internet. NGINX_conf server { listen 80; server_name 172.16.10.30; charset utf-8; client_max_body_size 75M; location /media { alias /Projects/My-Project/media; } location /static { alias /Projects/My-Project/static; } location / { uwsgi_pass unix:///Projects/My-Project/My-Project.sock; include /etc/nginx/uwsgi_params; … -
Inside the Database Table, Username should appear along with the Selected Checkbox Value (Django)
Brief Introduction: I'm working on a Django platform which has a homepage consisting a table of certain checkboxes and their values (which are added to the homepage from database admin panel directly), and a submit button And after selecting the certain checkbox and submitting, the selected values get stored in a different database table. Question: I want to create a login form for Users, which redirects to the homepage and when they select the checkbox and click submit, the username should appear along with the selected checkbox values Inside the database table PS: I'm a beginner. -
How to check recaptcha in confirm_login_allowed?
I'm novice in the Django framework and I'm trying to add some extra defence to my log in page. I'm using built in Django's auth system and want to add the recaptcha validation. Is that possible to add reCAPTCHA validation in the confirm_login_allowed method? In my forms.py: class MyAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): recaptcha_response = request.POST.get('g-recaptcha-response') # Here is the stuck! url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) if not result['success']: raise forms.ValidationError('Captcha Validation Failed.', code='invalid_captcha') And sure I have an error in this line: recaptcha_response = request.POST.get('g-recaptcha-response') Is there a way to get request in this method or is threre a better way? Thanks for any advice! -
Copy and past image from Google to my app
I am a totaly new on javascript so I ask your help about this. In my app, I have a textarea to insert a text. Any scripts are not interpreted of course. But there is an exception for the URL links which are preserved. What I would like to do is, if I post the URL of an image like http://image.jpg or png in my textarea, so the image will be displayed. So I think the issue is to know how transforming automatically this : <a href="image.jpg">image.jpg</a> to this : <img src="image.jpg"> I have in backend a TinyMCE Editor to write some articles. So it works fine with it. I can copy and past images links and images are displayed instead of their URL. But in a basic textarea it doesn't work. I have a BONUS QUESTION ! :) In Google image or whatever website, on any images, I can right click on it and choose to copy the image. But I can't paste it where I want. In my TinyMCE Editor, it's working fine. But It paste nothing on a textarea. I should at least have the URL link, doesn't it ? Thank you -
django one login system multiple apps using postgresql
I want to have multiple django projects but using just one user database to login and have that instance (request.user) ? am using postgresql i mean when i access to one app of django still have the same cookie for login or user another app -
Auto save into database django
I have a simple DB schema: class testModel(models.Model): modified_by = models.CharField(max_length=50, verbose_name="Modified by") modify_date = models.DateTimeField(auto_now_add=True, auto_now=False) week = models.DateField( verbose_name="Week date" ) type = models.CharField(max_length=10, verbose_name="Type") value = models.CharField(max_length=4, verbose_name="value") def __unicode__(self): return str(self.type) what i want to do is save each action into second table , e.g. testModel_history. I know I can create such table and import record during each change in first table, but I would like to ask you whether is there the better way to do this ? Thanks in advance, -
Use image in angular
I am developing web server with Django, but I have a problem reading image files from Angular 4. I can see my files with MEDIA_ROOT and MEDIA_URL before configured, when I access to http://localhost:8000/media/images/2017-08-07-10-31-52st1folio2.png (from Django, only put all path in url, no exists a menu of photos) I can see a good picture, but I when try access to image path from tag img in my component in Angular, when I put "media/images/2017-08-07-10-31-52st1folio2.png" I am not able to access it, and obtain an error localhost:9001/detail (here I call an image) when I try access this in my web terminal. Failed to load resource: the server responded with a status of 404 (Not Found). MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Bootstrap modal: Send modal data to the parent page in the form of list django
I am working with django templates, there is a part where I have a modal which has various textboxes in the form of a table. I need to send the data from parent web page to next web page in the form of a python list and display the data on parent page in a systematic form like table. Presently i get data to parent page using: $('#save-button').text() using text(), the data I get is: Capacity 23 extra Capacity 34 threshold 44 The modal is as: <div class="modal fade" id="Firstmodal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Add values</h4> </div> <div class="modal-body"> <p> <div id="table" class="table-editable"> <table class="table table-striped" id="tblone"> <thead id="tblHead"> <tr> <th>Parameters</th> <th>Add values</th> </tr> </thead> <tbody id="onetbl"> <tr><td>Capacity</td> <td contenteditable="true"></td></tr> <tr><td>extra Capacity</td> <td contenteditable="true"></td></tr> <tr><td>threshold</td> <td contenteditable="true"></td> </tr> </tr> </tbody> </table> <button id="btnSave-one" onClick="reply_click(this)" class="btn btn-primary">Save Changes</button> <p id="export"></p> </div> </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button> </div> </div> </div> How can i convert the data from modal to list, so that i can pass to next web page and display on parent page as a table as well? Thanks. -
Read configuration file in Django views.py
My question is simple: how to read any .txt or .ini file from views.py in Django project? I need to get a simple parameter (ex. 4) from settings. I dropped my setting.ini in one dir with views.py (in app folder). And nothing from the previous answers seem to work: In views.py: filename = os.path.join(os.path.dirname(file), 'setting.ini') returns FileNotFoundError, stating the exact right location, but being unable to read it: [Errno 2] No such file or directory: 'C:\\Users\\user\\Desktop\\XXXX\\XX\\XXXX\\XXXX\\setting.ini' Setting PROJECT_ROOT in settings.py also doesn't help. When I drop setting.ini in one folder with settings.py and try import os from django.conf.settings import PROJECT_ROOT file_ = open(os.path.join(PROJECT_ROOT, 'filename')) FileNotFoundError as well. -
How to block user login with certain status in Django
I'm using Django 1.11 and views based on classes. My user model is customized and it has a "status" field where it has "enabled, blocked and disabled". I'd like to know how I can only allow users to log in and the others are barred. Thanks!