Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cache settings override does not work
This is my cache setting: ENABLE_CACHING = True if ENABLE_CACHING: CACHES = get_cache() else: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } I tried to override this setting in two ways: @override_settings(ENABLE_CACHING=False) @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}}) Both do not override the settings and I have to do it manually again. How can this be fixed? -
How to integrate django-rest-swagger 2.0 with existing DRF application(Beginner)
I am trying to integrate swagger 2.0 with existing DRF application but it gives following error in browser after runningpython manage.py runserver: TemplateDoesNotExist at /hellothere rest_framework_swagger/index.html Request Method: GET Request URL: http://127.0.0.1:8000/swagger Django Version: 1.10 Exception Type: TemplateDoesNotExist Exception Value: rest_framework_swagger/index.html Exception Location: C:\Users\MHAZIQ~1\Desktop\Tkxel\mmg-git\venv\lib\site-packages\django\template\loader.py in get_template, line 25 I have added following lines in views.py: from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Pastebin API') And I have added following lines in urls.py: url(r'^swagger', views.schema_view), I ve tried applying following solution: TemplateDoesNotExist at /docs/ rest_framework_swagger/index.html but it didnot solve my problem, Can anyone please help me in this regard? -
How to implement chart.js with each field in the model? Django
I'm creating an aircraft comparison website where the user can compare two aircraft. In my Aircraft model I have several fields like range, passengers, speed etc - all these fields are numerical allowing for comparison to be done. Models.py class Aircraft(AircraftModelBase): engines = models.PositiveSmallIntegerField(default=1) cost = models.DecimalField(max_digits=8, decimal_places=3) maximum_range = models.PositiveSmallIntegerField() passengers = models.PositiveSmallIntegerField() maximum_altitude = models.PositiveIntegerField() cruising_speed = models.PositiveIntegerField() fuel_capacity = models.DecimalField(max_digits=6, decimal_places=2) wing_span = models.PositiveSmallIntegerField(default=1) This is my view.py for the comparison: def aircraft_delta(request): ids = [id for id in request.GET.get('ids') if id != ','] aircraft_to_compare = Aircraft.objects.filter(id__in=ids) property_keys = ['image', 'name', 'maximum_range', 'passengers', 'cruising_speed', 'fuel_capacity'] column_descriptions = { 'image': '', 'name': 'Aircraft', 'maximum_range': 'Range (NM)', 'passengers': 'Passengers', 'cruising_speed': 'Max Speed (kts)', 'fuel_capacity': 'Fuel Capacity' } data = [] for key in property_keys: row = [column_descriptions[key]] first_value = getattr(aircraft_to_compare[0], key) second_value = getattr(aircraft_to_compare[1], key) if key not in ['image', 'name']: delta = first_value - second_value else: delta = '' row.append(first_value) row.append(delta) row.append(second_value) data.append(row) return render(request, 'aircraft/delta.html', { 'data': data }) The way I've done is that each aircrafts field is appended into a row and that row is displayed in the template. I would like to add a chart for EACH of the following fields, but I don't … -
Extend admin drag and drop functionality into dashboard
I want to extend the functionality of rearrange the categories with drag and drop, from django-admin to django-oscar dashboard. In django-admin you can arrange the order of Categories by just drag and drop. I want to do the same thing in django-oscar dashboard. Any ideas what to do ? Where to start and what to look ? -
django test sqlite in memory "nable to open database file"
I am trying to run my django (1.7) tests on an in memory sqlite database. However I keep getting django.db.utils.OperationalError: unable to open database file Some examples suggest that adding this to my settings.py should be enough if 'test' in sys.argv: DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'} while others suggest if 'test' in sys.argv: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' } but in either case, I get the error. I have seen several other similar looking stackoverflow questions and https://code.djangoproject.com/wiki/NewbieMistakes#DjangosaysUnabletoOpenDatabaseFilewhenusingSQLite3 but most of that isn't relevant here (I tried the things that were) -
Issues when settings existing Django App with Docker
I have a Django app which I want to run/deploy using Docker. So I followed Docker Docs for Django. But docker-compose command not reading manage.py file. Here is my directory structure (v-dj-sample is my django project.) Permissions for django project : Docker file code : FROM django ADD . /v-dj-sample WORKDIR /v-dj-sample RUN pip install -r ./v-dj-sample/requirements/base.txt docker-compose file code : version: '2' services: web: build: . command: python ./v-dj-sample/manage.py runserver 0.0.0.0:8000 volumes: - .:/v-dj-sample ports: - "8000:8000" Error i am getting when running docker-compose up python: can't open file './v-dj-sample/manage.py': [Errno 2] No such file or directory -
Mock test case to upload file to S3
How can we mock file upload to S3. I tried something like this. file_mock = mock.MagicMock(spec=File, name='FileMock') @mock.patch('storages.backends.s3boto.S3BotoStorage', FileSystemStorage) def test_post_file(self): response = self.client.post('/api/v1/file_upload/', { "status": "NEW", "amount": "250.00", "bill": file_mock }) But this is in inturn actually uploading to S3. I'm new to this. How can this be implemented without uploading files to S3? -
Coalesce results in a QuerySet
I have the following models: class Property(models.Model): name = models.CharField(max_length=100) def is_available(self, avail_date_from, avail_date_to): # Check against the owner's specified availability available_periods = self.propertyavailability_set \ .filter(date_from__lte=avail_date_from, \ date_to__gte=avail_date_to) \ .count() if available_periods == 0: return False class PropertyAvailability(models.Model): de_property = models.ForeignKey(Property, verbose_name='Property') date_from = models.DateField(verbose_name='From') date_to = models.DateField(verbose_name='To') rate_sun_to_thurs = models.IntegerField(verbose_name='Nightly rate: Sun to Thurs') rate_fri_to_sat = models.IntegerField(verbose_name='Nightly rate: Fri to Sat') rate_7_night_stay = models.IntegerField(blank=True, null=True, verbose_name='Weekly rate') minimum_stay_length = models.IntegerField(default=1, verbose_name='Min. length of stay') class Meta: unique_together = ('date_from', 'date_to') Essentially, each Property has its availability specified with instances of PropertyAvailability. From this, the Property.is_available() method checks to see if the Property is available for a given period by querying against PropertyAvailability. This code works fine except for the following scenario: Example data Using the current Property.is_available() method, if I were to search for availability between the 2nd of Jan, 2017 and the 5th of Jan, 2017 it'd work because it matches result 1. But if I were to search between the 4th of Jan, 2017 and the 8th of Jan, 2017, it wouldn't return anything because the date range is overlapping between multiple results - it matches neither result 1 or result 2. I read this earlier (which … -
XHR Unable to Load
I'm in traineeship in a company and I need to used the program of an otheranother trainee who programmed it in 2012. So I have done some update but I have a some problems : When I press a button, I have a JS who do a xhr.get to recover a JSON. But I have this message on my firefox console : Object { message: "Unable to load /query/?typeForm=com…", stack:".cache["dojo/errors/create"]/</</g@…", response: Object, status: 0,responseText: "", xhr: XMLHttpRequest } My JS : function queryDataGrid(map, stringForm) { var test = "pouet"; require(["dojox/grid/DataGrid", "dojo/store/Memory", "dojo/data/ObjectStore", "dojo/_base/xhr", "dojo/domReady!", "dojo/dom", "dojo/_base/array"], function(DataGrid, Memory, ObjectStore, xhr, arrayUtil, dom) { var nodeDomGrid = dom.byId("datagrid"); window.alert("hey"); xhr.get({ url: "/query/", form: dom.byId(stringForm), handleAs: "json", load: function(data) { var nodeDomGrid = dom.byId("datagrid"); var nodeGrid = dijit.byId("datagrid"); var gridLayout = []; var dataStore = new ObjectStore({ objectStore:new Memory({ data: data.fields }) }); console.log("store"); console.log(data.fields[0][1]); globalData = data; for(i in data.columns) { gridLayout.push({ name: data.columns[i], field: data.columns[i], width: "auto" }) } // dijit.byId récupère l'objet graphique Dojo (ici Datagrid) alors que dojo.byId récupère le node DOM nodeGrid.setStructure(gridLayout); nodeGrid.setStore(dataStore); var nodeMap = dom.byId("map"); // Remplissage des données du formulaire de style columns = data.columns; columnsToDisplay = [] // On parcourt les colonnes des … -
Django static file not found (404 1795) while using template tag trick in .js file
I would like to load image in java script using django static template system like this: base.html: {% load static %} <script> var static_base = "{% static "one-page/" %}"; </script> <script src="{% static "one_page/js/google-map.js" %}"></script> In google-map.js: function init() { var mapOptions = { //... }; var mapElement = document.getElementById('map'); map = new google.maps.Map(mapElement, mapOptions); // Custom Map Marker Icon // img-base is defined in base.html using template tag var image = static_base + 'img/map-marker.png'; var myLatLng = new google.maps.LatLng(40.221384, -73.007270); var marker = new google.maps.Marker({ position: myLatLng, map: map, icon: image }); } When loading site in localhost I get following codes (make note that intro-bg.jpg put in the same location, calling from hmtl file, is loaded properly. ... [18/Apr/2017 09:42:27] "GET /static/one_page/img/intro-bg.jpg HTTP/1.1" 200 88321 [18/Apr/2017 09:42:28] "GET /static/one-page/img/map-marker.png HTTP/1.1" 404 1795 However, for calling the image by hand: http://localhost:8000/static/one_page/img/map-marker.png, there IS what I want: [18/Apr/2017 09:49:06] "GET /static/one_page/img/map-marker.png HTTP/1.1" 200 1072 I don't understand what is going wrong here. How to do this properly? -
DokuWiki: Include content from Django Application
The "intranet knowledge base" of the company I work for is our DokuWiki. I want to add some data to dokuwiki of a django application. I found the dokuwiki plugin include, but this seems to be only able to include wiki pages, not external resources (via https://....). How can I add content from a web application to dokuwiki? Support for authentication (dokuwiki needs a password to access the web application) would be good. -
optimized way of passing a form in all view functions django
I have a form which is needed in all the view functions of my django project. I have a common template for printing the form but for this I have to pass the form from all my view functions. I have about 8 apps. To include the form in all my view functions. Plus the form can be bound or blank depending on a session value. If I write the lines for including the form I have to write 5 lines. So I have to write those 5 lines to all my view functions. Any way to do this in a better way? -
Django-polymorphic stackedpolymorphicinline doesn't fetch values for subclass fields
I'm trying to create admin interface to edit some polymorphic fields inline. But values of subclass models don't fetch into form. Here's minimal code: models.py from django.db import models from polymorphic.models import PolymorphicModel class BigModel(models.Model): name = models.CharField(max_length=150, null=False, blank=False) class SomeModel(PolymorphicModel): title = models.CharField(max_length=150, null=False, blank=False) big = models.ForeignKey( BigModel, null=False, blank=False, related_name="somes", on_delete=models.CASCADE) class Spec1(SomeModel): number = models.IntegerField(null=False, blank=False) admin.py from django.contrib import admin from polymorphic.admin import PolymorphicInlineSupportMixin, StackedPolymorphicInline from stacked.models import * class SomeInline(StackedPolymorphicInline): class Spec1Inline(StackedPolymorphicInline.Child): model = Spec1 model = SomeModel child_inlines = (Spec1Inline,) @admin.register(BigModel) class BigModelAdmin(PolymorphicInlineSupportMixin, admin.ModelAdmin): model = BigModel inlines = (SomeInline,) Now if you create BigModel in admin interface and add Spec1 to it with some input (e.g title = "TITLE", number = 5) then save it, Number form field becomes empty, but it's still set to 5. This field is also required but does not affect model in any way. Number field is not editable. Is this a supposed behavior or did I miss something? (versions are: Django 1.11, django-polymorphic 1.1) -
Django: ModelChoiceField as MultipleHiddenInput
I am trying to render a ModelChoiceFiel using the MultipleHiddenInput widget but the template does not generate any inputs at all. Here is what I am trying: class PresetSelectForm(forms.Form): presets = forms.ModelChoiceField(queryset=Preset.objects.none(), widget=forms.MultipleHiddenInput()) def __init__(self, presets, *args, **kwargs): super(PresetSelectForm, self).__init__(*args, **kwargs) self.fields['presets'].queryset = presets And in the template I am using the following: {% csrf_token %} {{ form }} The csrf token input is generated, but nothing is for {{ form }}. What am I missing? -
Not able to get farme in face-detection in django (using python-opencv) project
I made a program for detection of face, it is working properly with python but when i used this in django, the frame (webcam-screen) is not showing. Please help views.py from django.shortcuts import render import cv2 # Create your views here. def dateset(request): # import pdb;pdb.set_trace() cam = cv2.VideoCapture(0) detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') Id = 2 #raw_input('enter your id') sampleNum = 0 while (True): ret, img = cam.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = detector.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # incrementing sample number sampleNum = sampleNum + 1 # saving the captured face in the dataset folder cv2.imwrite("dataSet/User." + Id + '.' + str(sampleNum) + ".jpg", gray[y:y + h, x:x + w]) cv2.imshow('frame', img) # wait for 100 miliseconds if cv2.waitKey(100) & 0xFF == ord('q'): break # break if the sample number is morethan 20 elif sampleNum > 20: break cam.release() cv2.destroyAllWindows() -
sphinx search in python3 django
I'm trying to run sphinx search with my python code, Please look into this import sphinxapi client = sphinxapi.SphinxClient() client.SetServer('127.0.0.1',9306) client.Query('select job_title from table_name_index limit 6') File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.4/dist-packages/sphinxapi/__init__.py", line 579, in Query assert (len(self._reqs) == 0) AssertionError my sphinx search is working and searchd successfully and run queries mysql -h0 -P 9306 And i have create a index in sphinx.conf "table_name_index" -
Django and Angular 2
I recently going to learn django. I sent a http request with a JSON in angular2 with the following code : import { Component } from '@angular/core'; import { Headers,Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Human } from "./Human"; @Component({ selector: 'main-app', templateUrl:"./app.component.html", styleUrls: ['./app.component.css'] }) export class AppComponent { private headers = new Headers({'Content-Type': 'application/json'}); private http:Http; private human:Human; private webApiUrl="api/Data"; putModel():Promise<Human>{ return this.http.post(this.webApiUrl,JSON.stringify({HumanName : this.human.Name}),{headers: this.headers}) .toPromise() .then(res => res.json().data as Human); } } Now I want to use this json file in django. Please help me how can I use this json file in django??? Thanks a lot. -
How to prevent to reset or clearing the django form fields if any error occurs during submit?
I am using django registration-redux for user registration. When i enter a same userid it shows error and the clears all the input fields of the form. how to prevent that error should occurs but input fields shouldn't get cleared. <form method="POST" role="form" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label class="col-sm-2 lab" for="id_username">Username *</label> <div class="col-sm-10"> <input name="username" id='id_username' class='form-control' placeholder='Username' minlength="5" maxlength="15" type='text' required></div> </div> <div class="form-group"> <label class="col-sm-2 lab" for="id_email">E-Mail *</label> <div class="col-sm-10" > <input class='form-control' name="email" id='id_email' placeholder='user@mydomain.com' pattern="(^[a-zA-Z0-9_.+-]+@[a-zA-Z]+\.com$)|(^[a-zA-Z0-9_.+-]+@[a-zA-Z]+\.org$)|(^[a-zA-Z0-9_.+-]+@[a-zA-Z]+\.co\.in$)" maxlength="200" type='email' required> </div> </div> <div class="form-group"> <label class="col-sm-2 lab">Password *</label> <div class="col-sm-10"> <input class="form-control" name="password1" id="id_password1" placeholder="Password" minlength="8" maxlength="15" type="password" required> </div> </div> <div class="form-group"> <label class="col-sm-2 lab2">Password Confirmation *</label> <div class="col-sm-10"> <input class="form-control" name="password2" id="id_password2" placeholder="Confirm Password" minlength="8" maxlength="15" type="password" required> </div> </div> <button type="submit" value= "register">Register</button> </form> should i use java script or what should help me? -
django-rest swagger : The schema generator did not return a schema Document
I have an error The schema generator did not return a schema Document when i tried to display my API listing. I'm using django-rest-swagger==2.1.2, python 2.7 and django==1.10.5 Traceback: Exception Type: TypeError at /rest/ Exception Value: __init__() got an unexpected keyword argument 'request' Request information: USER: admin GET: No GET data POST: No POST data FILES: No FILES data -
Django form ajax submit concurrently
I have some field created by Django form and there are some other data I want to post to other form using jQuery(Ajax). Is there any way to post them to different tables with two different ways at the same time? -
Django: self referential foreign key with choice list
My model defines an employee, which has a name, ID, job, and manager. I'd like to be able to specify a list of choices of Employees that could be listed as another employees manager (similar to the jobs field). To do so I have included class Employee(models.Model): EXECUTIVE = 'EXC' SALESMAN = 'SAL' ENGINEER = 'ENG' CLERK = 'CLK' JOBS = ( (EXECUTIVE, 'Assistant Engineer'), (SALESMAN, 'Salesman'), (ENGINEER 'Engineer'), (CLERK, 'Clerk'), ) employee_id = models.CharField(max_length = 5, primary_key=True) name = models.CharField(max_length=25) job = models.CharField(max_length=3, choices=JOBS) is_manager = models.BooleanField(default=False) manager = models.ForeignKey('self', on_delete=models.PROTECT, null=True, choices=get_managers()) def __str__(self): return self.name Also in my models.py I have defined the following function: def get_managers(): managers = [] for manager in Employee.objects.filter(is_manager=True): managers.append((manager.employee_id, manager.name)) return managers My problem is that when the function is placed before the Employee class definition I get NameError: name 'Employees' is not defined and when placed after the Employee class definition the error NameError: name 'get_managers()' is not defined. I have tried placing the get_managers() within the class and get `NameError: name 'get_managers()' is not defined If there are better ways of accomplishing the same thing I would be open to suggestions. -
Import error when starting uwsgi with virtual enviroments
I am trying to setup my Django application to work with python 3.5 ( Python 2.7 is default) So I created a virtual environment in 3.5 and deployed my Django project. I now want to get it working with uwsgi /etc/uwsgi/emperor.ini [uwsgi] emperor = etc/uwsgi/sites logto = /var/log/uwsgi /etc/uwsgi/sites/ams.ini [uwsgi] project = AMS base = /home/user chdir = %(base)/%(project) #home = %(base)/.virtualenvs/%(project) module = %(project).wsgi:application master = true processes = 5 socket = %(base)/%(project)/ams.sock chmod-socket = 666 uid = user gid = www-data vacuum = true logto = /var/log/uwsgi/log.log /etc/systemd/system/uwsgi.service [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/usr/local/bin/uwsgi --http :8000 --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target If I start uwsgi from within the virtual environment I can start it successfully uwsgi --http :8080 --chdir /home/user/AMS -w AMS.wsgi [pid: 31757|app: 0|req: 2/2] 203.94.69.162 () {42 vars in 695 bytes} [Mon Apr 17 10:34:02 2017] GET /ams_tools/ => generated 146 bytes in 76 msecs (HTTP/1.1 200) 2 headers in 80 bytes (1 switches on core 0) However when I start uswgi as a service I get the following error *** Starting uWSGI 2.0.15 (64bit) on [Tue Apr 18 07:33:41 2017] *** compiled with version: 5.4.0 20160609 on 17 April 2017 … -
FileField not working in Django
I am trying to create FileField in my forms and without saving file locally, add the file(as an attachment) to email and send it. Email part of code works fine, but when i add FileField it shows me error "'str' object has no attribute 'get'" and i am struggling to figure out what is the problem. Here is my view: def print(request): if request.method == 'POST': form = PrintForm(data=request.POST, request = request) # print(request.FILES) if form.is_valid(): contact_name = request.POST.get('contact_name', '') contact_email = request.POST.get('contact_email', '') form_content = request.POST.get('content', '') supervisor = form.cleaned_data['supervisor'] template = get_template('threeD/email/contact_template_for_printing.txt') context = Context({ 'contact_name': contact_name, 'supervisor': supervisor, 'contact_email': contact_email, 'form_content': form_content, }) content = template.render(context) subject = "New message" try: email = EmailMessage( subject, content, contact_email, [supervisor], headers={'Reply-To': contact_email} ) if request.FILES: # uploaded_file = request.POST.get('file') uploaded_file = request.FILES['stl_file'] # file is the name value which you have provided in form for file field email.attach('uploaded_file.name, uploaded_file.read(), uploaded_file.content_type') email.send() except: return "Attachment error" messages.success(request, "Thank you for your message.") return redirect('/index/print/') else: form = PrintForm(request=request) context_dict = {} context_dict['printers'] = Printer.objects.all() context_dict['form'] = form return render(request, 'threeD/print.html', context_dict) form: class PrintForm(forms.Form): contact_name = forms.CharField(required=True) contact_email = forms.EmailField(required=True) supervisor = forms.ChoiceField( choices=[(str(sup.email), str(sup.name)) for sup in Supervisors.objects.all()] ) … -
How to exclude paths from hashing with ManifestStaticFilesStorage
I am involved in an application that uses whitenoise to serve static files. It is configured to use CompressedManifestStaticFilesStorage which in turn uses ManifestStaticFilesStorage. By static files, I mean static files we provide, and libraries such as leaflet from third parties. The ManifestStaticFilesStorage class, provided by Django, will rename filenames to include a hash. For cachebusting. It filters resources and changes unhashed references to files to include the hash. This in turn breaks a function in leaflet: _detectIconPath: function () { var el = DomUtil.create('div', 'leaflet-default-icon-path', document.body); var path = DomUtil.getStyle(el, 'background-image') || DomUtil.getStyle(el, 'backgroundImage'); // IE8 document.body.removeChild(el); return path.indexOf('url') === 0 ? path.replace(/^url\([\"\']?/, '').replace(/marker-icon\.png[\"\']?\)$/, '') : ''; } The problem being the value of path looks something like: url("https://example.org/static/path/leaflet/dist/images/marker-icon.2273e3d8ad92.png") As the filename does not match, the 2nd replace will not do anything. This in turn will return: https://example.org/static/path/leaflet/dist/images/marker-icon.2273e3d8ad92.png") When leaflet tries to append a filename to this "directory", we get: https://example.org/static/path/leaflet/dist/images/marker-icon.2273e3d8ad92.png")marker-icon.png Which it obviously wrong. So what is the solution? I have been advised that we shouldn't be trying to hash filenames of third party packages, there could be other breakages. However I don't see any options for ManifestStaticFilesStorage to exclude certain directories from being hashed. I created the … -
Django value, annotate issue?
This is very simple, but I don't know exactly.. This is Some tables (Two) Football_game Table : id, game_name, score_user_id(FK), score, date User Table :id, name, email I need a sum of score by user in spacific date include all information(Football_game) This is my code football_list = Football_game.objects.filter(date='2017-04-18') football_data = football_list.values(score_user_id).annotate(sumOfScore=Sum('score')) game_lists = [entry for entry in football_data] for game_list in game_lists blah blah.. There is some problems. I need more information for the football game (date, game_name, etc..) How can I get this from object?