Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and postgres migration errors
I have created a new postgressql db in my django app within Heroku. Every time I run a migration, however, I get an error that I don't understand. Error: Applying argent.0043_auto_20170322_1629...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: cannot cast type date to integer LINE 1: ...LTER COLUMN "date_id" TYPE integer USING "date_id"::integer,... I have removed and added the only date field I have, to no avail. I still get the same error whether the date field in my models is there or not. Any insight would be much appreciated. models.py class Entry(models.Model): date = models.DateField(blank=True, null=True,) euros = models.CharField(max_length=500, blank=True, null=True) comments = models.CharField(max_length=900, blank=True, null=True) euros_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) xrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) dollars_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) daily_savings_dollars = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) daily_savings_display = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) def get_absolute_url(self): return reverse('argent:detail', kwargs={'pk': self.pk}) def item_date(self): row_title = self.date return row_title class Meta: ordering = ['date'] traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line … -
Django order by
I'm learning django, I am trying to order my objects by field last_name but I think I might be missing something, this is how my function looks: def list(self, *args, **kwargs): data = super().list(*args, **kwargs) data = data.data x = self.queryset.order_by('last_name') print(x) # I'm priting X but I still get list not ordered by last_name return Response(data) -
Why is my django url regex not working
I want my url to accept 0 or more digits(positive or negative integers), I mean it should match '/','/0',...,'/9' as well as '/-9','/-88' etc. This is the regex I am using ^([-]?[0-9]*)/$ . It works for all urls except '/', what is the problem with this regex? -
Django model validation, pass current value to function?
I'm trying to validate an expected IP value in my Django model as per the below: dmvpn_dsl = models.GenericIPAddressField(protocol='IPv4', verbose_name="DMVPN DSL IP", \ validators=[validate_dmvpn_ip('','172.16.100.')], blank=True, null=True) and in my functions i have def validate_dmvpn_ip(value,subnet): from django.core.exceptions import ValidationError if subnet not in value or value != '0.0.0.0': raise ValidationError(u'Invalid IP address, please check corrent octects have been assigned') i just need to pass the current value to the function to check it, but am not sure how to set this? Thanks -
Django: How to filter DB records by 0-3 criteria?
My goal is to have a search form (currently with 3 fields, but later possibly with more) which could be used for filtering products (In my case a product is training that can be filtered by sport, province and city). All those filter fields shall be optional, so I want to ignore when the POST value is either None (sport and province are FKs to related tables) or an empty string (city). I need to chain those three condition into the Training.objects.filter() call, but I need to omit conditions, that are not actually used. And I also need to check for None values as I am getting RelatedObjectDoesNotExist exception. This is what I have so far, but it is not good (only when all 3 conditions are properly filled): trainings = Training.objects.filter(sport = searchQuery.sport.sport_id).filter(province = searchQuery.province.province_id).filter(city = searchQuery.city) I tried to use conditional expression inside filter() to avoid exceptions, but either I am not able to elaborate the syntax correctly, or it is not possible - I was stopped by invalid syntax error... I was even thinking of dumb solution checking inputs in IF clauses and have different query for each case, but even with 3 params it has many … -
SSO Integration with Apache running Django with mod_wsgi
I am using Apache to host my web application running on Django using mod_wsgi. I am trying to integrate SSO with my application. Also, I need to pass on parameters like username to Django session. I am new to this and as far as I have discovered, there are two ways to do the same. Either let Django talk to SSO IdP server using Pysaml or second, use Apache to talk to the IdP server and let it pass on the response parameters to Django. I am not sure which method is better one to use. I need a little clarification on the same. Can someone please help? Thanks! -
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