Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Avoiding repetition in Django class-based view
I am writing a web application in Django, which is used in a particular way. Instead of using models stored in a database, it builds forms dynamically from JSON data gathered from another application and platform using REST API. The web page renders a form, which displays a list of mathematical parameters and their values. The user can then change (or not) those values and press a "Run" button to display some calculation results. The forms are built from data obtained by querying JSON data via a URL (which gives me the list of parameters and their initial values). By specification, I have to use Django and do not use the database to store any parameter value data (the only data which are stored are the URL addresses of the JSON data). I ended up with some working solution, using CBV. I have a DetailedView, of that structure: class SimulationView(DetailView): template_name='template.html' model=SimModel # provides URLs for REST API (URLs for querying parameter list and simulation function) # this is used to display the page with GET def get_context_data(self, **kwargs): # conn.request function that returns param_JSON in JSON/REST # for a SUBSET of parameters in param_JSON build a list of entries … -
Number formatting in Django template
I have an dictionary as follows: {'warranty': '1 jaar', 'delivery': u'2017-06-13', 'to_pay': 9000.0, 'deposit': 1000.0} I send it to Django template and I want to show to_pay as 9.000,00. But I can't. I have {% load humanize %} {% load i18n %} {% load l10n %} at the top of the template and I have USE_I18N = True USE_L10N = True in settings.py What have I tried: {{ car.sale.to_pay|floatformat:2|intcomma }} // 9,000,00 {{ car.sale.to_pay|intcomma }} // 9.000,0 almost good, but I need two zeroes after comma {{ car.sale.to_pay|localize }} // 9000,0 Any idea? -
Intermittent 403 response from django.contrib.auth.views.login()
Using django.contrib.auth.views.login() to process user logins I'm seeing 403 responses in a production environment. A second attempt to login succeeds after an initial 403 (when that response occurs). I've begun to log all 403 login failures, capturing the POST payload and cookie values which shows that csrfmiddlewaretoken (the hidden form field value) and csrftoken (cookie value) don't match. It's intermittent and happens to many users. The following decorators are all applied to the login function being used to proxy the django.contrib.auth.views.login() function: @ensure_csrf_cookie, @sensitive_post_parameters, @csrf_protect, @never_cache What might be the causes of this problem? -
Django Model Choices difference
In Django, when creating choices, is there any difference between... prod = 'Production' purch = 'Purchasing' support = 'Support' DEPT = ( (prod, 'Production'), (purch, 'Purchasing'), (support, 'Support') ) and DEPT = ( ('Production', 'Production'), ('Purchasing', 'Purchasing'), ('Support', 'Support') ) Either on a DB level or from a models perspective? Are there any advantages from writing it one way over another? -
Mocking imported class in django unittest
I'm having issue's with setting up mocking for some django views. backend.py class Connector(object): def get_this(): ... def get_that(): ... view_a.py from backend import Connector class AView(View): def get_context_data(self, **kwargs): connector = Connector() things = connector.get_this(...) view_b.py class BView(View): def get_context_data(self, **kwargs): connector = Connector() things = connector.get_that(...) text_view_a.py class ATest(TestCase): @mock.patch('backend.Connector') def test_simple(self, connector_mock): mi = mock.return_value # The constructor mi.get_this.return_value = ... mi.get_that.return_value = ... response = self.client.get( reverse('...view_a'), ) self.assertTrue(mi.get_this.called) text_view_b.py class BTest(TestCase): @mock.patch('backend.Connector') def test_simple(self, connector_mock): mi = mock.return_value # The constructor mi.get_this.return_value = ... mi.get_that.return_value = ... response = self.client.get( reverse('...view_b'), ) self.assertTrue(mi.get_that.called) The behavior i'm seeing is that they all work fine individually but when running combined only the first succeeds and the rest fails. Basically it looks like only the first mock is setup/used. I guess this has something to do with the views taking their own copy of the imported class? When is the best practice for mocking such backend classes? Paul -
Three apps one namespace
What I am trying to do is to have common namespace for two or more apps. Lets say I have an apps folder with 3 apps in it: dashboard (admin panel to display other apps), clients (displays fancy tables), and orders (same as clients). Looks like this: -- apps |-- dashboard | |-- views.py | |-- models.py | |-- urls.py |-- clients | |-- views.py | |-- models.py | |-- urls.py |-- orders | |-- views.py | |-- models.py | |-- urls.py In my main urls.py I have: url(r'^dashboard/', include('apps.dashboard.urls', namespace='dashboard', app_name='dashboard')), In dashboard/urls.py: url(r'^clients/', include('apps.clients.urls')), url(r'^orders/', include('apps.orders.urls')), And in clients: url(r'^$', views.AllClientsList.as_view(), name='clients-all'), So, I'd like to have the same namespace for urls in clients and orders app, to use them as {% url "dashboard:clients-all" %}. But it simply doesn't work - NoReverseMatch: Reverse for 'customers_detailed' not found. 'customers_detailed' is not a valid view function or pattern name. Is there any way to do it? -
Uploading image to a server cannot be done [duplicate]
This question already has an answer here: Transport security has blocked a cleartext HTTP 23 answers Uploading image to a server cannot be done. I am making Swift app and I wanna make a system in my app which uploading a image to my Django server. Now,PhotoController(it is for the system)is import Foundation import MobileCoreServices import UIKit class PhotoController:UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate{ @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var label: UILabel! @IBOutlet weak var myImageView: UIImageView! private var imagePicker:UIImagePickerController! @IBAction func uploadButtonTapped(_ sender: Any) { myImageUploadRequest() } override func viewDidLoad() { super.viewDidLoad() label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.5 label.text = "Tap the PhotoSelect or Camera to upload a picture" } @IBAction func PhotoSelect(_ sender: Any) { let myPickerController = UIImagePickerController() myPickerController.delegate = self; myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary self.present(myPickerController, animated: true, completion: nil) } @IBAction func Camera(_ sender: Any) { let sourceType:UIImagePickerControllerSourceType = UIImagePickerControllerSourceType.camera // カメラが利用可能かチェック if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){ // インスタンスの作成 let cameraPicker = UIImagePickerController() cameraPicker.sourceType = sourceType cameraPicker.delegate = self self.present(cameraPicker, animated: true, completion: nil) } else{ label.text = "error" } } // 撮影が完了時した時に呼ばれる func imagePickerController(_ imagePicker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { myImageView.contentMode = .scaleAspectFit myImageView.image = pickedImage } //閉じる処理 imagePicker.dismiss(animated: true, completion: nil) … -
How connect django to a RDS Postgresql encrypted database
I created a RDS encrypted database (Postgresql). I'm searching how I can connect my Django app to this database. After few searches I find how connect to a postgresql database over ssl in Django. You have to add this in your database settings : 'OPTIONS': { 'sslmode': 'verify-full', 'sslrootcert': '/path/to/ca-cert.pem' } but I can't find in KMS how to download the .pem with the keys automatically generated by AWS. Any help is appreciated. Thanks -
Django push notifications not working on ios
I am working on django push notifications. https://pypi.python.org/pypi/django-push-notifications/1.4.1 so we configured the pem files in server. Now i want to track the status of below code device = APNSDevice.objects.get(registration_id=apns_token) device.send_message("You've got mail") # Alert message may only be sent as text. device.send_message(None, badge=5) # No alerts but with badge. device.send_message(None, badge=1, extra={"foo": "bar"}) # Silent message with badge and added custom data. print device.send_message # its giving none from ios side, i can see the message that is coming to mobile from apns but the notification is not appearing on mobile. -
Getting ValueError while validating the form fields using Django and Javascript
I am getting the below error while validating the field using Javascript and Django. Error: ValueError at /insert/ invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/insert/ Django Version: 1.11.2 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py in get_prep_value, line 1853 Python Executable: /usr/bin/python Python Version: 2.7.6 I am explaining my code below. insert.html: <script type="text/javascript"> function validateForm(){ var s=document.frmfeed; if(s.name==''){ alert('Please enter the name'); return; }else if(s.phone==''){ alert('Please enter the phone no'); return; }else if(s.age==''){ alert('Please enter the age'); return; }else{ } } </script> <form method="post" action=" " onSubmit="return validateForm();" name="frmfeed"> {% csrf_token %} <label>Name: </label> <input name="name" value="{{person.name}}"> <br> <label>Phone: </label> <input name="phone" value="{{person.phone}}"> <br> <label>Age: </label> <input name="age" value="{{person.age}}"> <br> <input type="hidden" name="id" value="{{person.id}}"> <input type="submit" value="Submit"> </form> Here I need to check all input fields those should not be blank before submit but when I am clicking on submit button those error are coming. Please help me to resolve this error. -
Django rest framework nested serializer inside non-model serializer
I have a page where there are few separate serializers and they dont have relation. Instead of calling them one by one, I want to call all of them at once. So want to create a single serializer with each of them inside them as fields(nested serializer). Like this: class MarkSerializer(serializers.ModelSerializer): # Shows list of marks class Meta: model = Mark fields = blah blah class TopCricketerSerializer(serializers.ModelSerializer): # Show list of top cricketers and more.. Here is common serializer I am planning: CommonSerializer(serializers.Serializer): # Correct me if am using wrong serializer of if no serializer needed marks = MarkSerializer(many=True) top_cricketers = TopCricketerSerializer(many=True) # more such non-related fields Please let me know if I am not clear. -
GET request returns [ object Object] in django framework
I have successfully created an API using django framework, and http://127.0.0.1:8000/tuto/users/ in the browser get me the user list, Now i want to dislay it with on my web page, yet it returns [ object Object] <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </head> <body> <div id="users"> <p>No users are available.</p> </div> <script> $(document).ready(function() { $.get("/tuto/users/").success(function (data) { window.alert(data) } }); }); </script> </body> </html> I get the alert message of [object Object] -
django cache.clear() ending session (logout)
I'm using memcached in Django to cache the entire site. https://docs.djangoproject.com/en/1.11/topics/cache/#the-per-site-cache I've added some code in a post-save signal handler method to clear the cache when certain objects are created or updated in the model. from proximity.models import Advert # Cache from django.core.cache import cache @receiver(post_save, sender=Advert) def save_advert(sender, instance, **kwargs): # Clear cache cache.clear() Unfortunately now after creating a new object, the user is logged out. I think that the reason can be that I'm caching sessions. # Cache config CACHE_MIDDLEWARE_SECONDS = 31449600 #(approximately 1 year, in seconds) CACHE_MIDDLEWARE_KEY_PREFIX = COREAPP CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } } SESSION_ENGINE = "django.contrib.sessions.backends.cache" Should I use per-view cache maybe? -
Rosetta can't find anything to translate "Nothing to translate!"
Versions: Python 3.5.1 django 1.10 django-rosetta 0.7.13 I followed the rosetta tutorial. After creating some sentences to translate in a template using {% trans "sentence" %} (and {% load i18n %}), and running django-admin's makemessages and compilemessages, rosetta still cannot find anything to translate: Nothing to translate! You haven't specified any languages in your settings file, or haven't yet generated a batch of translation catalogs. Please refer to Django's I18N documentation for a guide on how to set up internationalization for your project. Notes: I had to solve some other bugs along the way. See here. I looked in the locale folder and the .po and .mo files are there, and they look correct (i.e. have the sentences I made in the template). Here's the .po file. # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-06-13 13:31+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: templates/www/batch.html:8 msgid "(mother) and" msgstr "" #: templates/www/batch.html:8 … -
GeoIP2 raising error "Invalid GeoIP city data file", how can I fix it?
I have downloaded files with country and city data sets from here:http://dev.maxmind.com/geoip/geoip2/geolite2/ and moved unziped files to geoip folder located in base_dir (also I have renamed them to GEOIP_COUNTRY and GEOIP_CITY), my GEOIP_PATH looks like this: GEOIP_PATH = os.path.join(BASE_DIR, "geoip").When I run simple code from django.contrib.gis.geoip2 import GeoIP2 g = GeoIP2() g.country('google.com') The exception "GeoIP2Exception: Invalid GeoIP country and city data files is raised". Please help me to fix it. -
django - doing arithmetic of some context values inside template
I have two models as given below. PRODUCT_TYPE=(('TL','Tubeless Tyre'), ('TT','Tubed Tyre'), ('NA','Not applicable')) class Product(models.Model): product_group=models.ForeignKey('productgroup.ProductGroup', null=False,blank=False) manufacturer=models.ForeignKey(Manufacturer, null=False,blank=False) product_type=models.CharField(max_length=2, choices=PRODUCT_TYPE,) opening_stock=models.PositiveIntegerField(default=0) def __str__(self): return '%s (%s, %s, %s) o.stock = %d ' % (self.product_group, self.manufacturer, self.product_type ,self.opening_stock) unique_together = ('product_group', 'manufacturer','product_type') def get_total_stock_in(self): Stock.objects.filter(product=self.id,ttype='I').aggregate(Sum('quantity')) def get_total_stock_out(self): Stock.objects.filter(product=self.id,ttype='I').aggregate(Sum('quantity')) and TRANSACTION_TYPE=(('I','Stock In'),('O','Stock Out')) class Stock(models.Model): product=models.ForeignKey('product.Product', blank=False,null=False) date=models.DateField(blank=False, null=False,) quantity=models.PositiveIntegerField(blank=False, null=False) ttype=models.CharField(max_length=1,verbose_name="Ttransaction type",choices=TRANSACTION_TYPE, blank=False) added_date=models.DateTimeField(blank=False, auto_now=True) def get_absolute_url(self): return reverse('product_detail', args=[str(self.product.id)]) def __str__(self): return ('[%s] %s (%s) %d' %(self.product, self.date, self.ttype, self.quantity)) and a view as.. class ProductDetail(DetailView): model=Product def get_context_data(self, **kwargs): context = super(ProductDetail, self).get_context_data(**kwargs) product_id=self.kwargs['pk'] context['total_stock_in']=Stock.objects.filter(product=product_id,ttype='I').aggregate(Sum('quantity')) context['total_stock_out']=Stock.objects.filter(product=product_id,ttype='O').aggregate(Sum('quantity')) return context Now, inside the template product_detail.html, I need to display the result of opening_stock+total_stock_in-total_stock_out as the current balance. Here's my template. Opening stock : {{object.opening_stock}} <br> Total Stock In: {{total_stock_in.quantity__sum}} <br> Total Stock Out: {{total_stock_out.quantity__sum}} <br> Balance stock : ??? -
Get method by django
For a university project i need to make a search using the WikiMedia Api in my little site (while remaining on it). For the server i decided to use Django. My question is, can i "interface" my html page with a python script to obtain the result? For html i've written this code, is ok? <form id="searchThis" action="/search" style="display:inline;" method="get"> <input class="searchBox" name="q" type="text"/> <input id="searchButton" value="Go" type="submit"/> </form> i ask you all sorry for bad programming but i'm at the beginning and i need to learn! -
CSV or xls file upload by he user to populate models in django
What is the correct way to allow csv file upload by the user and parse the data from it to populate the django models.How to handle it in a view using a form with file field. -
A Django model field with MANY default values?
I am new to Django and I have a project that I need to create an easy translating feature for. The idea that I have is to create a model that will have two fields for the text. One of the fields will be all the text from the site in a default language (English), and I would have the texts aligned to the left side of the page and empty forms on the right side where the translator can input the translations. I will be using polib library to take the values and input them back in the PO file and the with the features I will compile the PO file into a MO file and I will have the site translated. I need a way to securely associate the populated default language fields to the forms. Is this idea plausible at all ? And can you give me advice on how I should go about this process? -
django 1.11.2 serializer nested json array
I am new to both python and django and I would appreciate some guidance with a problem I'm having with Django REST, nested json and the serializer. I wish to post: { "Server": [ { "serverSerialNumber": "0000", "serverUniqueKey": "2222" }, { "serverSerialNumber": "0001", "serverUniqueKey": "2223" } ] } This is my serializer: from django.contrib.auth.models import User, Group from rest_framework import serializers from .models import Api class ApiSerializer(serializers.ModelSerializer): """Serializer to map the Model instance into JSON format.""" class Meta: """Meta class to map serializer's fields with the model fields.""" model = Api fields = ('id', 'serverSerialNumber', 'serverUniqueKey', 'date_created', 'date_modified') read_only_fields = ('date_created', 'date_modified') depth = 1 I simply receive the following back: { "serverSerialNumber": [ "This field is required." ] } So I am not understanding how to use 'depth' or I'm doing something silly. Please advise. Thanks, D -
Django NoReverseMatch Error when passing arguments on redirect
Hi im trying to redirect from one view function to another and passing a list of lists as argument. urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^checkFiles/', views.checkFiles, name='checkoutFiles'), url(r'^$', views.home, name='home'), url(r'^upload/', views.upload, name='upload'), url(r'^login', views.loginview, name='loginview'), url(r'^logout/', views.logoutview, name='logoutview'), url(r'^confirm_files/', views.upload, name='confirm_file'), url(r'^upload/', views.del_files, name='del_files'), ] views.py for redirecting from views.upload to views.checkoutFiles i'm using this command return redirect(reverse('checkoutFiles', kwargs={'ACCEPTED_FILES':ACCEPTED_FILES})) ... def checkFiles(request, ACCEPTED_FILES): print ACCEPTED_FILES return render(request, 'confirm_files.html', { 'ACCEPTED_FILES': ACCEPTED_FILES }) and im getting this error message NoReverseMatch: Reverse for 'checkoutFiles' with keyword arguments '{'ACCEPTED_FILES': [[u't2_r0Oqwl7.txt', '0.98 KB', u'text/plain']]}' not found. 1 pattern(s) tried: ['checkFiles/'] django version: 1.11.2 -
Check Django User Group
So I want to change what information is displayed based on the group the user is in. So: {% if user.is_staff %} ...... That works but when I try and do {% if user.is_China %} This group doesn't work? Is there a specific thing I need to do to find out if the user is part of a group? -
Cannot access rosetta
Versions: Python 3.5.1 Django 1.10 django-rosetta 0.7.13 The installation guide tells you to add the following to your project's settings.py: from django.conf import settings if 'rosetta' in settings.INSTALLED_APPS: urlpatterns += patterns('', url(r'^rosetta/', include('rosetta.urls')), ) However, this just results in an error: NameError: name 'patterns' is not defined -
Correct way to insert a django dropdown inside every column in html table
I want to insert a django dropdown form {{ proxies_select }} into this template: {% extends "base.html" %} {% block title %} Optimize Proxies {% endblock %} {% block styles %} <style type="text/css"> tfoot { display: table-header-group; } html { width: 57.5%; } </style> {% endblock %} {% block content %} <div id="title"> <b style="font-size:200%" ;>Optimize proxies<br></b> </div> <div id="proxy_history_dialog" title="Proxy history" style="display:none;"> </div> {{ proxies_select }} <table id='p_table-id' class="display" cellspacing="0" width="50%"> <thead> <tr> {% for col_name in table_headers %} <th>{{ col_name }}</th> {% endfor %} <th>Actions</th> <th>Change proxy</th> </tr> </thead> <tfoot> <tr> {% for col_name in table_headers %} <th>{{ col_name }}</th> {% endfor %} <th>Actions</th> <th>Change proxy</th> </tr> </tfoot> <tbody> {% for data_row in table_data %} <tr> {% for item in data_row %} <td>{{ item }}</td> {% endfor %} {# actions column#} <td></td> {# proxie change column#} <td>{{ proxies_select }}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} which is rendered to this: <!DOCTYPE HTML> <html lang="en"> <head> <title> Optimize Proxies | Upstream Commerce</title> <style type="text/css"> tfoot { display: table-header-group; } html { width: 57.5%; } </style> </head> <body> <img id="loader" src="/static/img/loader_animation_large.gif" style=" width:36px; height:36px; display: none; position:absolute; top:50%; left:50%; margin-top:-18px; margin-left:-18px;"/> <p><a href="/accounts/logout/">Logout</a> | <a href="/accounts/profile/">Home</a></p> <div … -
Django tests, mocking Instagram response error
For past days I've been trying to write a simple test that checks if my app works. I was introduced to testing right after I got my program done so that's why I'm writing tests afterwards. I'm using python-instagram-ext as a library and python version 3.5.2 The actual program works correctly. It simply gets the data from instagram, saves some of it to variable and prints it out. def handle_instagram(self, max_tag_id, search_string=settings.SEARCH_STRING, return_count=1): instagram_api = InstagramAPI(access_token=access_token, client_secret=client_secret) search_string = search_string.replace('#', '') recent_media, next_ = instagram_api.tag_recent_media(count=5, max_tag_id=None,tag_name=search_string) id = recent_media[0].id print(id) And that part works very well. But I don't want my test to request data from instagram API so I'm using mock to mock that function. from django.test import TestCase from palautebot.models import Feedback from django.core.management.base import BaseCommand from palautebot.management.commands.palautebot import Command import instagram import datetime class TestPalautebotTests(TestCase): palautebot_cmd = Command() @mock.patch('palautebot.management.commands.palautebot.InstagramAPI') def test_handle_instagram(self, palautebot_instagram): instagram_api = palautebot_instagram.InstagramAPI.return_value user = instagram.models.User(1234, full_name='Test Account', username='test', profile_picture='http://pic.jpg') recent_media = [instagram.models.Media( users_in_photo= [], comment_count= 0, link= 'https://www.google.fi', filter= 'Crema', caption= instagram.models.Comment(created_at=datetime.datetime(2017, 6, 12, 9, 5, 10), user=user, id='1234', text='#nofilter Instagram test'), like_count= 0, id= '0000000000000000001_0000000001', comments= [], images= { 'thumbnail': instagram.models.Image('http://www.google.fi', 50, 50), 'low_resolution': instagram.models.Image('http://www.google.fi', 150, 150), 'standard_resolution': instagram.models.Image('http://www.google.fi', 400, 400) }, tags= …