Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the table on admin site?
I'm new to Django and I would like to change the table that is on the admin site. Now there is an User class and a Group class, I would like to add my own class, 'Games', to the admin site which have the variables 'name' and 'size'. The class 'Games' is in my models.py. How do I do this? -
SASL bind not working with pyldap
I'm trying to use the pyldap library to authenticate django admin users using AD logins. However every time I try to use the sasl_interactive_bind_s function(which is used by django-auth-ldap-ad) it returns this: Traceback (most recent call last): File "ms_ad_bind.py", line 33, in <module> l.sasl_interactive_bind_s("", sasl_auth) File "C:\Users\mvanorde\AppData\Local\Programs\Python\Python35-32\lib\site-packages\ldap\ldapobject.py", line 404, in sasl_interactive_bind_s return self._ldap_call(self._l.sasl_interactive_bind_s,who,auth,RequestControlTuples(serverctrls),RequestControlTuples(clientctrls),sasl_flags) AttributeError: 'LDAP' object has no attribute 'sasl_interactive_bind_s' In this trackback I used the ms_ad_bind.py from the pyldap git repo do make sure I'm using the function the way it was intended. A simple bind works without issues, but the SASL bind does not. I'm not able to find a solution for this anywhere on google. Has anyone seen this error or know how to fix it? I'm running Python 3.5, and due to issues with lber.h when installing pyldap via pip I had to use a whl file and the only one I'm able to find for python 3.5 is here. -
Django - Disable Page Level Caching by User
I've set up page level caching for many of our pages. However once in a while an admin user logs in to preview potential changes to the site. Is there a way to disable page level caching just for these users? I read through the docs but I didn't see anything. -
How to sanitize or randomize sensitive database fields
What's the most efficient method or tool to randomize a list of database table columns to obscure sensitive information? I have a Django application used by several clients, and I need to onboard some development contractors to do work on the application. When they work on bugs (e.g. page /admin/model/123 has an error), ideally they'd need a snapshot of the client database in order to reproduce and fix the bug. However, because they're off-site contractors, I'd like to mitigate risk in the event they expose the client database (unintentionally or otherwise). I don't want to have to explain to a client why all their data's been published online because a foreign contractor left his laptop in an unlocked car. To do this, I'd like to find or write a tool to "randomize" sensitive fields in the database, like usernames, email addresses, account numbers, company names, phone numbers, etc so that the structure of the data is maintained, but all personally identifiable information is removed. Presumably, this is a task that many other people have had to do, but I'm not sure what the technical term is, so I'm not finding much through Google. Are there any existing tools to do … -
python/django: Invalid block tag: 'paginate' with django-twitter-endless-pagination
I am trying to use django-endless-pagination as twitter style. I followed the documentation as in link. When I trying to render the template, it raises an error : Invalid block tag: 'paginate'. I would appreciate helping me solve this issue or suggest an alternate approach for infinite scroll in django. view.py: @page_template('entry_index_page.html') def entry_index(request, template = 'entry_index.html', page_template = 'entry_index_page.html', extra_context=None): context = { 'entries': Entry.objects.all(), } if extra_context is not None: context.update(extra_context) if request.is_ajax(): template = page_template return render_to_response( template, context, context_instance=RequestContext(request)) settings.py: INSTALLED_APPS = ( 'endless_pagination', ) from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS TEMPLATE_CONTEXT_PROCESSORS += ( 'django.core.context_processors.request', ) entry_index.html: <h2>Entries:</h2> {% include page_template %} {%load staticfiles%} {% block js %} {{ block.super }} <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="{%static 'endless-pagination.js'%}"></script> <script>$.endlessPaginate();</script> <script> $.endlessPaginate({ paginateOnScroll: true, paginateOnScrollMargin: 20 }); {% endblock %} entry_index_page.html: {% load endless %} {% paginate entries %} {% for entry in entries %} {{entry.name}} {% endfor %} {% show_more %} -
Django Rest Framework. SerializerMethodField or source?
Question about DRF serializers. Especially ModelSerializer. There are two versions with Foreign Key: field = CharField(source='user.name') field = SeriaizerMethodField() get_field(self, obj): return obj.user.name What will work better / quickly ? -
Where can i find Django get_absolute_url?
I have django 1.9.12 installed. Where is now get_absolute_url from django.db.models.base ? How can i find it? I tried to find it in django.db.models.base, but can't find it. -
Loading Content into Django Ckeditor
I am using Django (1.10) Ckeditor to run as an email editor. I would like to know how to preload database content into the Ckeditor when it is first loading. My Django template code is as below. Specifically, I would like the loop {% for field in table %} to appear in the Ckeditor. Could anyone provide suggestions? Thanks a lot. <html> <head> {% load static %} <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> </head> <body> <div> <p>From:<input></input></p> <p>To:<input></input></p> <p>Cc:<input></input></p> <p>Bcc:<input></input></p> <p>Subject:<input></input></p> </div> <div> <form method="POST" action=""> <p> <input type="submit" name="import" value="Import"> <input type="submit" name="reset" value="Reset"> <input type="submit" name="finish" value="Finish"> </p> <br> {% csrf_token %} {{ form.as_p }} </form> {% for field in table %} <p name="{{field.id}}">{{ field.gp_Email }}</p> <p name="{{field.id}}">{{ field.N_tag }}</p> <p name="{{field.id}}">{{ field.NewsPaper }}, {{ field.Section}}, {{field.Title}}</p> <p name="{{field.id}}">{{ field.Content|safe }}</p> {% endfor %} </div> </body> </html> -
Django: file change tracking stopped working
Django suppose to auto-refresh whenever project files are have changed. For me it suddenly stopped working. Any idea what the reason might be, or how to diagnose this problem? Have tried to remove all PYC files. Only restarting the server makes things update. Server log is empty - nothing happens when Python files are updated. Config, dev-environment hasn't been touched - it just stopped updating. -
Firebase Cloud Messaging Issue
Currently doing a project which requires me to communicate and send notifications to my android device(s), from my server (django, running sqlite3 which is built in). In order to make my life easier, i'll be utilising on Google's Firebase Cloud Messaging to bridge the gap and send the notifications to the android devices easily. On Django(my server side), i'm using django-fcm library to do a http requests to the FCM server whenever i need to send a notification to my devices, which i believe have been set up properly. The problem i'm facing currently would be that even though i have done a successful post from Django side to FCM server, the notification does not show on the FCM Console, and i have tried my best to do the necessary research to find a solution but to no avail. By using the methods provided by this library, i've tried sending a message and this is the response given: Kzhan00b-3:eldersense_website Kzhan00b$ python3 manage.py fcm_messenger --devices Devices list: (#7) Zhong Han Kzhan00b-3:eldersense_website Kzhan00b$ python3 manage.py fcm_messenger --device_id=7 --msg='hello' Using default settings.FCM_MAX_RECIPIENTS value 1. Change it via settings [OK] device #7 (Zhong Han): (['cbUqW...IimVXB'], {'results': [{'message_id': '0:1484576499555513%775b332838eb0007'}], 'multicast_id': 6536553600879447077, 'success': 1, 'failure': 0, … -
How to read Python list in Javascript [in a Django template]
I'm programming in oTree (which is a Django based environment for social experiments) and I have the following problem. I defined some lists in Python and I'd like to import them and use them in an HTML template. If I print them in HTML I manage to see them without any problem, however, once I need to use them in Javascript, the program fails to read them and the single quotes of the elements of the list are converted in &#39;. The list is imported like this var filtered_elements = {{ array }};. I think the problem is exactly here, as JS cannot work with them. Do you have any suggestion on how to do that? I considered using JSON, but since I'm quite new to programming, I cannot understand if it's just a waste of time or there is a simpler way out. Thanks for your answers! -
How to Dont Repear Yourself (DRY)
I have basic authorization in two places in my code. I want to seperate this as one function and dont repeat code. My app: from django.shortcuts import render from django.views.generic import View from django.http import HttpResponse, Http404 from django.contrib.auth import authenticate from django.core.exceptions import PermissionDenied import base64 from notes.models import Note, load_initial_data class NoteListView(View): def filter_queryset(self, query_set): query_params = self.request.GET if 'board' in query_params: query_set = query_set.filter(board=query_params['board']) return query_set def get(self, request): load_initial_data() query_set = self.filter_queryset(Note.objects.all()) basic_auth = True # this lines below ! if basic_auth: if 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() if len(auth) == 2: if auth[0].lower() == "basic": uname, passwd = base64.b64decode(auth[1]).split(':') user = authenticate(username=uname, password=passwd) if user is not None and user.is_active: request.user = user if not request.user.is_staff: raise PermissionDenied return HttpResponse(query_set) response = HttpResponse() response.status_code = 401 response['WWW-Authenticate'] = 'Basic realm="%s"' % "Basic Auth Protected" return response else: return HttpResponse(query_set) class NoteView(View): def get_object(self, obj_id): try: return Note.objects.get(id=int(obj_id)) except IndexError: raise Http404 def get(self, request, note_id): load_initial_data() basic_auth = True #this lines below if basic_auth: if 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() if len(auth) == 2: if auth[0].lower() == "basic": uname, passwd = base64.b64decode(auth[1]).split(':') user = authenticate(username=uname, password=passwd) if user is not None and user.is_active: … -
Django 1.8: Issue with using cleaned_data
I am having a weird issue. I am using a Select field that is bound with data returned from Model. It is defined as: choices = Subscription.objects.filter(is_full_version=False) subscription_id = forms.ModelChoiceField(queryset=choices) request.POST returns the id from value attribute of option but when I call: form.cleaned_data.get('subscription_id') it rather returns: 'subscription_id': <Subscription: Gold> Gold is text rather Id. request.POST rather returns what I want: subscription_id': [u'3'] What's that? -
Django inheriting from multiple model classes
So I have a base abstract model class class AbstractBase(models.Model): category = models.CharField() // Some fields class Meta: abstract = True Now many classes inherit from this Base. Each category has its own fields class Category1(AbstractBase): //some code class Category2(AbstractBase): //some code . . . class CategoryN(AbstractBase): //some code Now I do not wish to create separate inlines etc for each of these models. This is because in the admin only one of these models need to be displayed depending on which category it is. class CategoryAdminInLine(nested.NestedTabularInline): model = Category fields = //some common fields Is there any easy way to do it? -
Django ORM group by
I have the following model. Class A(models.Model): tmp_field = models.IntegerField() ... ... Now I want to fetch only ids and group them together based on the tmp field. My query looks like A.objects.all().values('id') So I want something like this. [ {tmp1: [id1, id2, id3]}, {tmp2: [id5, id6, id7]}, {tmp3: [id12, id213, id1299]} ...] How do I group them by tmp_field. -
i have a an implementation of vsm running on python which works well on command line, but when linked to django, it doesn't retrieve any result
class HomeView(View): template = 'index.html' template_two = '' result = '' query = '' # def post(self,request): # return render(request,self.template) def get(self,request): session = request.session['id'] # print list(request.session.keys()) # print "sldf" return render(request,'index.html',{'id':session}) def post(self,request): message = 'You Submitted an empty query' if request.method == 'POST': if 'search' in request.POST: message = 'Post has a value' search = request.POST['search'] all_docs = models.Documnent.objects.all().filter().values() """vsm.py implements a toy search engine to illustrate the vector space model for documents. It asks you to enter a search query, and then returns all documents matching the query, in decreasing order of cosine similarity, according to the vector space model.""" from collections import defaultdict import math import sys import time # We use a corpus of four documents. Each document has an id, and # these are the keys in the following dict. The values are the # corresponding filenames. document_filenames = {0: r"C:\PythonProject\MLKMS\data\lotr.txt", 1: r"C:\PythonProject\MLKMS\data\silmarillion.txt", 2: r"C:\PythonProject\MLKMS\data\rainbows_end.txt", 3: r"C:\PythonProject\MLKMS\data\the_hobbit.txt", 4: r"C:\PythonProject\MLKMS\data\cisco.txt", 5: r"C:\PythonProject\MLKMS\data\asimo.txt", 6: r"C:\PythonProject\MLKMS\data\atlas.txt", 7: r"C:\PythonProject\MLKMS\data\baxter.txt", 8: r"C:\PythonProject\MLKMS\data\bigdog.txt", 9: r"C:\PythonProject\MLKMS\data\collect.txt", 10: r"C:\PythonProject\MLKMS\data\curiosity_rover.txt", 11: r"C:\PythonProject\MLKMS\data\facebk.txt", 12: r"C:\PythonProject\MLKMS\data\facebook.txt", 13: r"C:\PythonProject\MLKMS\data\goliath_tracked_mine.txt", 14: r"C:\PythonProject\MLKMS\data\iRobot_Create.txt", 15: r"C:\PythonProject\MLKMS\data\justin.txt", 16: r"C:\PythonProject\MLKMS\data\mobiles.txt", 17: r"C:\PythonProject\MLKMS\data\mq-9_reaper.txt", 18: r"C:\PythonProject\MLKMS\data\news.txt", 19: r"C:\PythonProject\MLKMS\data\packbot.txt", 20: r"C:\PythonProject\MLKMS\data\parrot_AR_drone.txt", 21: r"C:\PythonProject\MLKMS\data\roomba.txt", 22: r"C:\PythonProject\MLKMS\data\turtlebot.txt", 23: r"C:\PythonProject\MLKMS\data\UICSCMSC.txt", 24: r"C:\PythonProject\MLKMS\data\uniofbath.txt", 25: r"C:\PythonProject\MLKMS\data\Walmart.txt", 26: r"C:\PythonProject\MLKMS\data\windows.txt", … -
Reduce response time for REST API in Django
In the following code what can be done to optimize the response time so that it is inside 100ms ,50000 request are done as shown below, def update(request): try: response_dict = {'status':0} lat = request.POST.__getitem__('latitude') lon = request.POST.__getitem__('longitude') accuracy = request.POST.__getitem__('accuracy') loc = location(latitude=lat,longitude=lon,accuracy=accuracy) loc.save() except Exception as e: logger.error(e) return HttpResponse(simplejson.dumps(response_dict), content_type='application/json') html <label class="radio"><button type="button" class="btn btn-default" id="update">Update</button>&nbsp;&nbsp;&nbsp;&nbsp;<span id='downloadfile'></span></label><br><br> <script> function sendlocation(snddata){ $.post("/reports/update/", snddata, function callbackHandler(data, textstatus) { if (data.status == 1) { console.log("unsuccessfull") } }, "json" ); } $('#update').click(function(){ var snddata = {}; var lat = 12.97161923; var lon = 77.59463452; for (i=0; i < 50000; i++) { snddata["latitude"] = lat+0.5 snddata["longitude"] = lon+0.5 snddata["accuracy"] = 0.7 sendlocation(snddata); } }); -
accessing a non model field in pre_save signal
I need to add a simple non model field in a django form: <input type="text" name="setupwork" value=""/> then access its value on the pre_save signal. Is there any way to do so, I looked into pre_save parameters: sender, instance, using, **kwargs but couldn't find that field. -
Django REST: Custom APIView
Running a Django project with REST API. Creating custom APIView router. I would like to overwrite put methods. Now how do I add the fields I want, so they got displayed in the REST GUI. So instead of this Media type and Content I display fields I want: My current code looks like this: def put(self, request, *args, **kwargs): import pdb pdb.set_trace() I don't understand how to pass fields to the GUI. There is no information on the reference page. And there are no clues on GIT. -
webpack 2 react code splitting
I am trying to split the react code at routes but I am receiving this error: Uncaught SyntaxError: Unexpected token < Here is my webpack code: var path = require('path') var webpack = require('webpack') var HappyPack = require('happypack') var BundleTracker = require('webpack-bundle-tracker') var path = require('path') var ExtractTextPlugin = require("extract-text-webpack-plugin") var polyfill = require("babel-polyfill") function _path(p) { return path.join(__dirname, p); } module.exports = { context: __dirname, entry: { index: './assets/js/index', }, output: { path: path.resolve('./assets/bundles/'), filename: '[name]-[hash].js' }, devtool: 'inline-eval-cheap-source-map', plugins: [ new BundleTracker({filename: './webpack-stats.json'}), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' }), new HappyPack({ threads: 4, loaders: [ 'babel-loader' ], }), new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /pt-br/) ], module: { rules: [ { test: /\.css$/, include: path.resolve(__dirname, './assets/css/'), use: ["style-loader", "css-loader", "resolve-url-loader"] // use: ExtractTextPlugin.extract({ fallbackLoader: "style-loader", loader: ["css-loader", "resolve-url-loader"]}) }, { test: /\.scss$/, include: path.resolve(__dirname, './assets/css/'), use: ["style-loader", "css-loader", "resolve-url-loader", "sass-loader"] // use: ExtractTextPlugin.extract({ fallbackLoader: "style-loader", loader: ["css-loader", "resolve-url-loader", "sass-loader"]}) }, { test: /\.scss$/, include: path.resolve(__dirname, './assets/vendors/'), use: ["style-loader", "css-loader", "resolve-url-loader", "sass-loader"] // use: ExtractTextPlugin.extract({ fallbackLoader: "style-loader", loader: ["css-loader", "resolve-url-loader", "sass-loader"]}) }, { test: /\.jsx?$/, include: path.resolve(__dirname, './assets/js/'), exclude: /node_modules/, use: [{ loader: 'happypack/loader', }] }, { test: /\.png$/, use: { loader: 'file-loader' , options: { name: '/static/img/[name].[ext]' } } … -
Deployment with Django and Uwsgi
My problem is that uwsgi doesn't server static files of the django project. I am very new in web development and I was following this tutorial with uswgi deployment (https://uwsgi.readthedocs.io/en/latest/tutorials/Django_and_nginx.html) I stuck on the stage when uwsgi run django. I was expecting that uwsgi will server static files after I ran: python manage.py collectstatic and then uwsgi --http :8000 --module myproject.wsgi But when I get on 127.0.0.1:8000 I see something like this enter image description here The structure of the project is trivial --myproject: -----myproject: -------myproject: ----------init.py ----------settings.py ----------urls.py ----------wsgi.py -------static -------manage.py -------db.sqlite3 -----venv Thank you for any hint or help. -
Django elastic search populate foreign key fields
Hi i have a user model and i have extended it with a profile model class ProfileIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) username = indexes.CharField(model_attr='user') first_name = indexes.CharField(model_attr='first_name') last_name = indexes.CharField(model_attr='last_name') user = indexes.CharField(model_attr='user') def get_model(self): return Profile def index_queryset(self, using=None): """Used when the entire index for the profile model is updated""" return self.get_model().objects.all() def prepare_tags(self, obj): return [tag.name for tag in obj.tags.all()] def prepare_username(self, obj): return obj.user.username def prepare_last_name(self, obj): print obj.user.last_name, " : <== LAST NAME\n" return obj.user.last_name# def prepare_first_name(self, obj): print obj.user.first_name, " : <== FIRST NAME\n" return obj.user.first_name i want the search result object to contain the first name and last name of user whic is there in Django's default User model.How will i obtain such a result? -
Django middleware to handle only non media requests
Written a middleware which does a small computation work. I don't want my middleware to work for media requests (css, js, images) It will a additional load to server. I have tried both process_request and process_view function, both of them are executed for media request. Any idea to exclude media request from middleware processing? My Django version is 1.5.5 -
Django How to insert Amount (credit or debit)and update Main Balance in Transaction Model
I'm new to python and Django. i'm building a bank application which allows you create bank accounts and deposit, withdraw and transfer money between accounts. models.py class Account(models.Model): customer = models.ForeignKey(Customer) Account_Number = models.PositiveIntegerField(primary_key=True) Account_Type = models.CharField(max_length=30, blank=True, null=True) Activation_Date = models.DateTimeField(default=datetime.datetime.now) Status = models.CharField(max_length=30,choices=STATUS_CHOICES) Account_Opening_Branch = models.CharField(max_length=30) Account_Opening_City = models.CharField(max_length=30) Account_Open_Under = models.CharField(max_length=30) Linked_Accounts_Cards = models.CharField(max_length=30) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return str(self.Account_Number) def __str__(self): return str(self.Account_Number) class Transaction(models.Model): From_account = models.ForeignKey(Account) To_Account_Number = models.PositiveIntegerField() Account_Type = models.CharField(max_length=30,blank=True, null=True) Transaction_Date = models.DateTimeField(default=datetime.datetime.now) Reference_Number = models.CharField(max_length=30,blank=True, null=True) Transaction_Description = models.CharField(max_length=30,blank=True, null=True) Credit = models.DecimalField(max_digits=10,decimal_places=2,blank=True) Debit = models.DecimalField(max_digits=10,decimal_places=2,blank=True,default=0) Balance = models.DecimalField(max_digits=10,decimal_places=2) view.py def Transaction_Form(request): form = TransactionForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() return render(request, "Customer/Transfer.html") context = { "form": form, } return render(request, "Customer/Transaction_Form.html", context) forms.py class TransactionForm(forms.ModelForm): class Meta: model = Transaction exclude = ('Account_Type','Reference_Number','Transaction_Date','Transaction_Description','Credit') fields = [ "From_account", "To_Account_Number", "Debit", "Balance", ] How to update Balance With Account Number.If I credit Amount ,than first enter in credit column than Upadate Balance simarly to Debit I don’t know what is logic for credit and debit -
How to use fetch data which is coming from django rest api in html
I want to use coordinates of polygon of a area which is coming from django rest api output. I want to load it on html file to display the polygon on google map. So,how to fetch that coordinates which is in json format. Is this possible?