Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Building an API to communicate between an android app and a database
I have no experience with creating an API and I am a part of a group project where I need to create one for a cooking Android application that will make requests to a database for recipes. Are there any good tutorials for beginners? I know C++ and a little Java. I was recommended flask, django, and node, but I also found play framework and casablanca. I don't really understand the differences between these frameworks or really how I make sure the API understands the requests from the application and can then return data from the database. Any suggestions or explanations will be greatly appreciated. -
Django - correctly redirecting based on category
I'm having two issues: (1) When a blog post hyperlink is clicked (taking you to the details of that post), I am having difficulty redirecting to a page depending on the category of the post clicked. Here's what I tried in views.py: def pt_detail(request, slug, category): ptpost = get_object_or_404(Post, slug=slug, category__slug=category) if ptpost.category == "progresstracker": return render(request, 'blog/pt_detail.html', {'ptpost': ptpost}) else: return render(request, 'blog/computerscience.html', {'ptpost': ptpost}) It's not redirecting anything properly as a post with any category ("progresstracker" or otherwise) gets sent to a blank computerscience.html page. If I change "computerscience" to "pt_detail" in the above and click a post with category "progresstracker" it will go to the correct page. I'd also like to add a few other category and corresponding return render's which, in this case, I'd presumably add with elif's. (2) I'd like to add a "subcategory" field to my model that allows for blank values. If I have a category, subcategory, and slug for a blog post I'd like to display the full post in url // and if subcategory is blank, simply / (versus //). Is it a regex issue to avoid two "//"s if is blank? Here's the rest of my code: urls.py urlpatterns = … -
Why isn't there a simple group_by in Django?
I have a model: class Person(models.MyModel): department = models.ForeignKey('Department') start_date = models.DateField() class Department(models.SomeModel): name = models.CharField() I want, in my template, to be able to create a simple table where I can group people by two attributes: department__name and start_date. In this way, people with the same department name which started in the same date would be displayed in the same row. I know there is a template tag called regroup, but I can only give three arguments, and only one of them can be the grouper. Well, I thought I could do this query in my view.py with something like this: Person.objects.all().group_by('start_date','department__name') But I was wrong. There is no such method. Any way to achieve this in a simple way? -
Unable to pass parameters in url tag from django template
href="{% url 'url-name' %}?{{request.GET|get_encoded_dict}}" I am trying with this,but it send emptys data in the url. I am not able to fetch the data passed in the view. My request.GET contains nothing in the view. in HTML template request.GET contains a dict which I am encoding it in get_encoded_dict. @register.filter def get_encoded_dict(data_dict): return urllib.urlencode(data_dict) If I display the data fetched by get_encoded_dict it shows me the data, but not able to pass it in url. Checked with this didn't work. Thank you -
Django doesn't keep User logged in between views
I am quite new to web programming and django especially. I am trying to implement symple login service using Ajax. The user seems to be logged in succesfully however when the view is changed he uppears ulogged again. Appreciate any help. Thanks. Login template: <form class="login-form" action=""> {% csrf_token %} <input type="text" id="usernamelog" /> <input type="password" id="pwdlogin" /> <button onclick="login(event)">login</button> <p class="message">Not registered? <a href="#">Create an account</a></p> </form> Login Ajax: function login(e) { e.preventDefault(); var username = $("#usernamelog").val(); var pwd = $("#pwdlogin").val(); $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); $.ajax({ url : "/loginscript/", type : "post", data : { username: username, password : pwd, } }).done(function(data) { if (data == "good") { document.getElementById('usernamelog').value ="good"; window.location='../ehealth' }else{ document.getElementById('usernamelog').value ="bad"; } }); } function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } … -
Faster Django Admin Paginator: Cannot get this Django snippet to work
I found this snippet for improving the performance of large database table queries in Django admin lists: https://djangosnippets.org/snippets/2593/ There are some issues about it when using it with Django 1.10, which are already discussed in my previous question here: How to speed up Django's admin pages with PostgreSQL count estimates? Particularly, _count needs to renamed to count and query_set to queryset. Here's a short version of the relevant part of the snippet: from django.core.paginator import Paginator from django.core.cache import cache class FasterAdminPaginator(Paginator): def _get_count(self): if self.count is None: try: key = "adm:{0}:count".format( hash(self.object_list.query.__str__()) ) self.count = cache.get(key, -1); if self.count == -1 : if not self.object_list.query.where: # estimates COUNT: https://djangosnippets.org/snippets/2593/ cursor = connection.cursor() cursor.execute("SELECT reltuples FROM pg_class WHERE relname = %s", [self.object_list.query.model._meta.db_table]) self.count = int(cursor.fetchone()[0]) else : self.count = self.object_list.count() cache.set(key, self.count, 3600) except: # AttributeError if object_list has no count() method. self.count = len(self.object_list) return self.count count = property(_get_count) Problem is, I still cannot get it to work. Current error log excerpt: maximum recursion depth exceeded while calling a Python object ... result_count = paginator.count ... if self.count is None: No idea how to get the snippet working. -
Access django server on VirtualBox/Vagrant machine from host browser?
I have a Django web server on a VirtualBox/Vagrant machine running "bento/centos-6.7-i386". I have followed this guide to create a Django project: https://docs.djangoproject.com/en/dev/intro/tutorial01/ I have a web server running at http://127.0.0.1:8000/ inside my guest machine. This is the first time I am running a Django web server. It is supposed to be a hello world app. How can I access this web application from my host browser? I tried adding this line - config.vm.network "private_network", ip: "55.55.55.5" in the vagrant file and then trying to run the "python manage.py runserver 0.0.0.0:80" command as per 1 of the solutions explained in previous discussions by others but I couldnt access the site from my host browser using 55.55.55.5:8000. How can I access the web server from my browser? Kindly help me,I'm quite new to vagrant. Following given is my Vagrant File: # -- mode: ruby -- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "bento/centos-6.7-i386" config.vm.network "forwarded_port", guest: 8000, host: 8000 config.vm.network "forwarded_port", guest: 8080, host: 8080 config.vm.network "forwarded_port", guest: 5000, host: 5000 config.vm.network "private_network", ip: "10.10.10.10" end -
Django - How to filter dropdown based on user id?
I'm not sure how to filter dropdown based on user id. Not I want for user id 2. I want exactly like this for user id 2. Model @python_2_unicode_compatible # only if you need to support Python 2 class PredefinedMessage(models.Model): user = models.ForeignKey(User) list_name = models.CharField(max_length=50) list_description = models.CharField(max_length=50) def __str__(self): return self.list_name class PredefinedMessageDetail(models.Model): predefined_message_detail = models.ForeignKey(PredefinedMessage) message = models.CharField(max_length=5000) View class PredefinedMessageDetailForm(ModelForm): class Meta: model = PredefinedMessageDetail fields = ['predefined_message_detail', 'message'] exclude = ('user',) def predefined_message_detail_update(request, pk, template_name='predefined-message/predefined_message_detail_form.html'): if not request.user.is_authenticated(): return redirect('home') predefined_message_detail = get_object_or_404(PredefinedMessageDetail, pk=pk) form = PredefinedMessageDetailForm(request.POST or None, instance=predefined_message_detail) if form.is_valid(): form.save() return redirect('predefined_message_list') return render(request, template_name, {'form':form}) html file {% extends "base.html" %} {% load i18n %} {% block content %} <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> {% endblock %} -
Django and AngularJS setting browser cookie
I have to set a Browser cookie after the user logs in. Now the problem is that my company has a Single Sign On Server. When User logs in through the SSO, user is redirected to my application. I get employee information and a Auth Token from the SSO. How can I access the information and make a browser cookie? Since the success function of the Login request is not handled at my end how do I access the information in my AngularJS application? Can I set a browser cookie directly from Django? -
Disappearing {% csrf_token %} on website file
When I wanted use my registration form in my site, I get ERROR 403: "CSRF verification failed. Request aborted." In source of this website I realised that is missing. This is part of view-source from my site: <div style="margin-left:35%;margin-right:35%;"> <fieldset> <legend> Wszystkie pola oprócz numeru telefonu należy wypełnić </legend> <form method="post" action="."> <p><label for="id_username">Login:</label> <input id="id_username" maxlength="30" name="username" type="text" required/></p> <p><label for="id_email">Email:</label> <input id="id_email" name="email" type="email" required /></p> <p><label for="id_password1">Hasło:</label> <input id="id_password1" name="password1" type="password" required /></p> <p><label for="id_password2">Powtórz hasło:</label> <input id="id_password2" name="password2" type="password" required /></p> <p><label for="id_phone">Telefon:</label> <input id="id_phone" maxlength="20" name="phone" type="text" /></p> <p><label for="id_log_on">Logowanie po rejestracji:</label><input id="id_log_on" name="log_on" type="checkbox" /></p> <input type="submit" value="Rejestracja"><input type="reset" value="Wartości początkowe"> </form> </fieldset> </div> I was surprised of that, because in my files on Pythonanythere this fragment of code is present. This is part of my file register.html on Pythonanythere: <div style="margin-left:35%;margin-right:35%;"> <fieldset> <legend> Wszystkie pola oprócz numeru telefonu należy wypełnić </legend> <form method="post" action=".">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Rejestracja"><input type="reset" value="Wartości początkowe"> </form> </fieldset> </div> What am I doing wrong that my webpage don't see this piece of code? It is seamed on server but on webpage view-source It isn't. -
I am getting following error.i download oracle client and provide neccesary path to env varibles
import cx_Oracle Traceback (most recent call last): File "", line 1, in ImportError: DLL load failed: %1 is not a valid Win32 application. -
Django-hstore and admin widget: way to unsort hstore data
I'm use Django-hstore library, and there is pretty admin widget. The subject table store computer's components, something like this: class Component(models.Model): name = models.CharField(max_length=64) purchase_date = models.DateField(blank=True, null=True) product_page = models.URLField(blank=True, help_text='url to pruduct page') <...> data = hstore.DictionaryField(blank=True) def load_cpu_data(self): if self.product_page: info = cpu_data(self.product_page) if info: # info is a SortedDict with proper order for key, value in info.items(): self.data[key] = value self.save() Next, I get data from cpu-world.com about necessary CPU and I have following inline data in admin: Look great, but sorting alphabetically instead logical, in order of entering data into database in view. Example of proper order, like on cpu-world: Family Model number Frequency Socket Microarchitecture Processor core Manufacturing process Data width The number of CPU cores The number of threads Integrated graphics Thermal Design Power Is there technique, or trick, or something to help me show data in desired sequence? For example, I found python have OrderedDict data type, which similar to what I need. But apparently hstore inner structure mess data order. -
Override ModelViewSet's queryset with filter backends applied
Is it possible to take into account MyModelViewSet's filter_backends when creating custom queryset? class MyModelViewSet(viewsets.ModelViewSet): filter_backends = (CustomFilter, ) serializer_class = MySerializer def get_queryset(self): # It should not return all objects, but only results from `CustomFilter` queryset = LedgerEntry.objects.all() # some extra filtering return queryset How should I implement this? Django: 1.10 Django Rest Framework: 3.4.6 -
Django-JS-fade in menu don't work
I started a project on Django. In one of my app, I did a template with a two menu, one black one white with fade in and fade out (using semantic ui ) here the code <!-- Menu fixe --> <div class="ui large top fixed hidden menu" > <div class="ui container"> <a class="active item" id="acc_menu">Accueil</a> <a class="item">Comment ça marche </a> <a class="item">Vous voyagez ?</a> <!-- <a class="item">besoin 1</a> --> <div class="right item"> <a class="ui inverted red button" id="connexction1">Connecxion</a> <a class="ui inverted red button" id="inscription1">Inscription</a> </div> </div> </div> <!-- Menu noir --> <div class="pusher"> <div class="ui inverted segment" id="menu_fixe"> <div class="ui container"> <div class="ui large secondary inverted pointing menu"> <a class="active item" id="acc_menu">Accueil </a> <a class="item">Comment ça marche </a> <a class="item">Vous voyagez ?</a> <!-- <a class="item">besoin 1</a> --> <div class="right item"> <a class="ui inverted red button" id="connexction">Se connecter</a> <a class="ui inverted red button" id="inscription">S'inscrire</a> </div> </div> </div> </div> </div> {% block extrahead %} <! -- other loading --!> <script src="{% static 'js/base.js' %} "></script> <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %} "/> {% endblock %} with this js file : base.js $(document).ready(function() { // fix menu when passed $('#menu_fixe') .visibility({ once: false, onBottomPassed: function() { $('.fixed.menu').transition('fade in'); }, onBottomPassedReverse: function() { … -
How to speed up Django's admin pages with PostgreSQL count estimates?
It's quite known that Django's admin list views are getting rather slow when the database tables have lots of rows. That's because the Django paginator uses by default a (slow) PostgreSQL COUNT query. As estimate would be fine for us and it's much faster, e.g.: SELECT reltuples FROM pg_class WHERE relname = "my_table_name" There is snippet available to fix this issue, but it's unclear to me how to actually use it: https://djangosnippets.org/snippets/2593/ Also, the snippet is not supposed to work on filtered results. That's because the estimate count as shown above doesn't work here. Is there another way to speed up filtered list views in Django admin pages? -
Why i cant register custom middleware?
I get an error: TypeError: object() takes no parameters My setup: 1) middleware function in motion/middleware/CountVisits: class Count(object): def process_request(self,request): if request.session['visits']: request.session['visits']+=1 else: request.session['visits']=1 Settings: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'motion.middleware.CountVisits.Count', ] -
Django: Store many forms into one table
I'm using django v1.8. A have one table split into four forms. Example from my views.py ext_cent = ExternalCentersForm(request.POST, prefix='extcent') ext_cent_diagnostic = ExternalCentersDiagnosticForm(request.POST,prefix='extcentDiagn') ext_cent_outcomes = ExternalCentersOutcomesForm(request.POST,prefix='extcentOutcomes') ext_cent_outcomes2 = ExternalCentersOutcomes2Form(request.POST,prefix='extcentOutcomesTwo') When I'm trying to save them I use ext_cent_object = ext_cent.save(commit=False) ext_cent_object.author = request.user ext_cent_object.save() ext_cent_diagnostic_object = ext_cent_diagnostic.save(commit=False) ext_cent_diagnostic_object.author = request.user ext_cent_diagnostic_object.save() ext_cent_outcomes_object = ext_cent_outcomes.save(commit=False) ext_cent_outcomes_object.author = request.user ext_cent_outcomes_object.save() ext_cent_outcomes2_object = ext_cent_outcomes2.save(commit=False) ext_cent_outcomes2_object.author = request.user ext_cent_outcomes2_object.save() As I result for each form I have a new row in my table containing only values from the specific form. I need to store all these form's data into one table. -
MapField is not displayed in Django Rest Framework Mongoengine
I have a model with following attributes. class File(DynamicDocument): country = fields.StringField(max_length=100, unique=True) languages = fields.MapField(fields.MapField( fields.EmbeddedDocumentField(AudioImage))) I am trying to use Django Rest Framework Mongoengine as follows: from rest_framework_mongoengine.serializers import DocumentSerializer class TestSerializer(DocumentSerializer): class Meta: model = File It simply gives the following output: But I wanted it to address the tree like structure with all the fields from AudioImage class as well. Did I miss anything? or There is another way for MapField ? -
ACCOUNT_EMAIL_VERIFICATION = 'mandatory' not working
I wanna have a website which verifies it's users by sending them verification email. searching for a good tutorial, I came to this which helped me a lot; but still I have problems. I don't know why no email is sent to the sample email which I registered with, nor is written in PyCharm terminal (as it's said in the tutorial). would you please help me, at which part am I making mistake? my code : #settings.py SITE_ID = 1 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'debug': DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', "django.template.context_processors.media", ], }, }, ] # Custom allauth settings # Use email as the primary identifier ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_EMAIL_REQUIRED = True # Make email verification mandatory to avoid junk email accounts ACCOUNT_EMAIL_VERIFICATION = 'mandatory' # Eliminate need to provide username, as it's a very old practice ACCOUNT_USERNAME_REQUIRED = False AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin and to ensure compatibility with other packages 'django.contrib.auth.backends.ModelBackend', # 'allauth' specific authentication methods 'allauth.account.auth_backends.AuthenticationBackend', ) #urls.py urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^accounts/', include('allauth.urls')), url(r'^$', views.main_page), url(r'^admin/', admin.site.urls), url(r'^home/', views.home), url(r'^wallets/', views.wallets), url(r'^trans-history/', views.trans_history), url(r'^reports/', … -
Access Django simple history logs outside from admin?
I have integrated Django simple history in my project. I have API build using Django rest framework (DRF) and front-end using Angularjs. The logs history for the objects are saved without any problems using DRF and agularjs. models.py from datetime import datetime from django.db import models from simple_history.models import HistoricalRecords class Person(models.Model): """ Person model""" first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) workphone = models.CharField(max_length=15, blank=True, default='') avatar = models.FileField(upload_to="", blank=True, default='') createdtstamp = models.DateTimeField(auto_now_add=True) history = HistoricalRecords(inherit=True) def __unicode__(self): return "%s" % self.first_name How can I acess saved simple history logs outside django admin? Serialize logs queryset and return response in json format. from person.models import Person from datetime import datetime >>> person = Person.objects.all() >>> person.history.all() -
Django CSRF & JS Fetch API. Correct headers but still 403 [duplicate]
This question already has an answer here: Django 1.9 AJAX form CSRF token 403 error - “CSRF cookie not set” 1 answer I can't get Django to receive an ajax post request. My csrf header looks correct but I can't get it to pass. It fails with the message Forbidden (CSRF cookie not set.) Oddly I also can't disable csrf with the @csrf_exempt decorator. my view: # from django.views.decorators.csrf import csrf_exempt class Schedules(View): # @csrf_exempt - doesn't work def post(self, request): return HttpResponse('schedules post') my JS fetch statement I've tried sending in the body, as a header, both but all approaches fail. fetch('/api/schedules', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'credentials': 'same-origin', 'X-CSRFToken': getCookie('csrftoken'), }, body: JSON.stringify({ "data": {"hello": "world"}, "csrfmiddlewaretoken": getCookie('csrftoken') }) }) And an example request with correct headers: I've also tried grabbing a csrf token that was rendered in a template from the DOM with the same lack of results. Can anyone see what I'm missing or help me further debug. -
Access to django template variable from js block
I have js code in my django template but project use Grunt js, so code must be in js block {% block extrajs %}. This is my code in template: <script type="text/javascript"> var pub_date = {{ obj.pub_date|date:'YmdHi' }}; var hour = moment().startOf('hour').fromNow(); var time_ago = moment(pub_date, "YYYYMMDDhhmm").locale('{{ LANGUAGE_CODE }}').fromNow(); document.write(time_ago); </script> Here I try test my code but without success, I get empty alert window: $(document).ready(function(){ var pub_date = '{{ obj.pub_date|date:'YmdHi' }}'; alert(pub_date); }); Question is, how I can get access from js block to variable in template? -
Django_mongoengine: ServerSelectionTimeOutError
I am using django_mongoengine for my django application. I am using webfaction to host both website and db. I followed the instructions from webfaction documentation to set up MongoDB. When I try to run the application, I get the error ServerSelectionTimeoutError: No servers found yet MongoDB_DATABASES part in settings.py looks like the following: MONGODB_DATABASES = { 'default': { 'name': 'myDBName', "password": 'myDbPassword', "username": 'myDbUser', 'port': portNumber, } } If I remove the password and username parts, it runs the app and loads the login page. But when I try to login, it gives authentication failed error which is understandable. Am I missing something in my settings file or do I need to modify anything in the MongoDB app? Thanks. -
Error following Django App Engine flexible tutorial
I am having some trouble following google's tutorial here: https://cloud.google.com/python/django/flexible-environment Everything works fine till I get to the point of running python manage.py migrate at which point the error was: django.core.exceptions.ImproperlyConfigured: If set, STATIC_URL must end with a slash Note that google's documentation specifically says: Set the value of STATIC_URL to '/static.' Nonetheleess, I changed the settings.py to set STATIC_URL = '/static/' (which was the default to begin with), and got the error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb' I could not resolve either of the errors. Thank you for the help. -
Django update model after condition
I have a model like this class Foo(models.Model): bet = models.IntegerField() end_date = models.DateTimeField() \\some date in the future is_canceled = models.BooleanField(default=False) I need automatically set is_canceled = True when end_date = datetime.now()