Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elastic Beanstalk: No module named settings
I am trying to run a django app on Amazon Elastic Beanstalk and I'm following this tutorial. However, when deploying, I get a 500 error, and when looking at the logs: ImportError: No module named settings [Tue Sep 06 15:22:32.138981 2016] [:error] [pid 1940] [remote 127.0.0.1:42845] mod_wsgi (pid=1940): Target WSGI script '/opt/python/current/app/fasttext/wsgi.py' cannot be loaded as Python module. [Tue Sep 06 15:22:32.139006 2016] [:error] [pid 1940] [remote 127.0.0.1:42845] mod_wsgi (pid=1940): Exception occurred processing WSGI script '/opt/python/current/app/fasttext/wsgi.py'. It seems like my wsgi.py file is the issue: """ WSGI config It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") application = get_wsgi_application() I read many topics on SO and other sites, but none of the solutions worked for me. Here is my .ebextensions/django.config file: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: fasttext/wsgi.py Does anyone know how to fix this ? Thanks -
Why is Django finders.find not finding path to static file?
I am trying to include a common block of HTML markup that contains my website's terms and conditions inside two separate applications. One application will display the terms and conditions within a scrolling textbox inside of a form that the user has to agree to. The other application just displays the terms from inside a static page when the user clicks a link in the footer. I'm using the following simple template tag inside each app to identify the HTML file for the app which displays the terms inside the form page: # profile/templatetags/includestatic.py or footer/templatetags/includestatic.py register = template.Library() @register.simple_tag def includestatic(path, encoding='UTF-8'): file_path = finders.find(path) with open(file_path, "r", encoding=encoding) as f: string = f.read() return escape(string) The above tag was explained in this Stackoverflow question. I then include this HTML file in each Django template: # profile/templates/terms_conditions.html or footer/templates/terms_conditions.html {% load includestatic %} ... {% includestatic "common/static/terms_and_conditions.html" %} After creating the above code, I reran the "collectstatic" and restarted gunicorn. However, the following error is being flagged for the includedstatic command in either template and it's being raised by the finders.find command in the includestatic template tags because finders.find(path) isn't returning any path: Exception Type: TypeError Exception Value: coercing β¦ -
Uniquely identifying ManyToMany relationships in Django
I'm trying to figure out how best to uniquely identify a ManyToMany relationship in my Django application. I have models similar to the following: class City(models.Model): name = models.CharField(max_length=255) countries = models.ManyToManyField('Country', blank=True) class Country(models.Model): name = models.CharField(max_length=255) geo = models.ForeignKey('Geo', db_index=True) class Geo(models.Model): name = models.CharField(max_length=255) I use the ManyToManyField type for the countries field because I want to avoid city name duplication (i.e. there may be a city name like "Springfield" that appears in multiple locations). In another place in my application, I want to be able to uniquely identify the city-country-geography relationship. That is, I need to know that a user whose city is "Springfield" resides in the United States, versus Canada, for example. As a result, I need to know which of the ManyToManyField relationships my city maps to. My user looks something like this: class MyUser(models.Model): # ... other fields ... city = models.ForeignKey('City', db_index=True, blank=True, null=True) This setup clearly does not capture the relationship between city and country properly. What's the best way to capture the unique relationship? Would I use a custom through-table with an AutoField acting as a key, and change my user to point to that through-table? -
COUNT(id) instead of COUNT(*) in Django
I'm paginating a list view for a model with many fields, so it takes a lot of time to execute MyModel.objects.filter('some filter').count(), because on SQL level it runs SELECT COUNT(*) FROM mytable instead of: SELECT COUNT(id) FROM mytable even if I write explicitly MyModel.objects.only('id').count() How can I make Django run COUNT(id) on .count() -
Error: django.core.exceptions.AppRegistryNotReady: The translation infrastructure... in python
What I want to do: I'm trying to run tests with unittest for functions in my views. Outcome: I'm getting the following error: ....env/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 189, in _fetch "The translation infrastructure cannot be initialized before the " django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time. Imports used: import unittest from django.test import Client from django.core.wsgi import get_wsgi_application import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") import sys sys.path.append('../../mysite/') from mysite.settings import * from views import * application = get_wsgi_application() As you can see I tried this answer with no success: appregistrynotready-the-translation-infrastructure-cannot-be-initialized I followed this one too: upgrading-to-django-1-7-getting-appregistrynotready-for-translation-infrastruct Imports I found with ugettext & ugettext_lazy: from django.utils.translation import ungettext, ugettext_lazy as _ from django.utils.translation import ungettext, ugettext, ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _ Some code I found with ugettext return ugettext('%(number)d %(type)s') % {'number': delta.seconds, 100 'type': count(delta.seconds)} I was wondering if there could be a problem with any of these. -
Django - TinyMCE - admin - How to change editor size?
I can't seem to find any way to hange editor size in TinyMCE. I edit posts on my site in Django administration and to make it easier I looked for a better editor than just a textfield. I succesfully installed TinyMCE, but the editor is tiny, which makes editing very annoying. Here's how it looks like. Here is my models.py from django.db import models from tinymce.models import HTMLField class Post(models.Model): title = models.CharField(max_length=140) # body = models.TextField() date = models.DateTimeField() body = HTMLField() def __str__(self): return self.title Here is my admin.py: from django.contrib import admin from blog.models import Post admin.site.register(Post) And here is my urls.py: from django.conf.urls import url, include from django.views.generic import ListView, DetailView from .models import Post urlpatterns = [ url(r'^$', ListView.as_view( queryset=Post.objects.all().order_by("-date")[:25], template_name='blog/blog.html')), url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Post, template_name='blog/post.html')), ] I've been trying and googling for the past 2 hours, but I can't figure it out. Can anyone help me? Thanks. -
Add objects to list with AngularJS and Django. Html page doesn't recognize js
I'm trying to add objects to a list with AngularJS and Django. I had some code working to just count the amount of clicks I do and worked further on that. But now I have more code it seems like my html page doesn't recognize my javascript controller anymore. I tried it again from scratch but without success. What am I doing wrong? html page: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Calc</title> </head> <body ng-app="coco"> <div ng-controller="cocoCtrl"> <p>CALCULATING BONDS</p> <div> <input placeholder="Cashflow value" type="number" ng-model="value"> <input placeholder="Cashflow date" type="date" ng-model="date"> <!-- new cashflow submitted here --> <button ng-click="submitCashflow(value,date)">Cashflow</button> </div> <div id="cashflow-target"> <div ng-repeat="cashflow in cashflows"> <div class="cashflow-value"> [[ cashflow.value ]]</div> <div class="cashflow-date"> [[ cashflow.date ]]</div> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <script type="text/javascript" src="{%static "js/controller.js" %}"></script> <script type="text/javascript" src="{%static "js/app.js" %}"></script> <script type="text/javascript" src="{%static "js/cashflow.js" %}"></script> </body> </html> controller.js: app = angular.module('coco',[]); app.controller('cocoCtrl',['$scope',function($scope){ $scope.cashflows = {}; Cashflow.query(function(response) { $scope.cashflows = response; }); $scope.submitCashflow= function(value, date) { var cashflow = new Cashflow({value: value, date: date}); cashflow.$save(function(){ $scope.cashflows.unshift(cashflow); }) }; $scope.save = function(){ $(".data").html("Click" + $scope.cashflows); $scope.num += 1; }; }]); -
Django multiple reCaptcha (v2) don't show up
I have an issue with django-recaptcha2. I'm creating blog, I tried to add comments with replies to my posts and with captcha validation at adding new comments. I had some problems with multiple captcha at same page with django-recaptcha (v1), so I choose django-recaptcha2 which was told to support multiple recaptcha. Here's my comment form: class CommentForm(forms.Form): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) content = forms.CharField(label="", widget=forms.Textarea) captcha = ReCaptchaField(widget=ReCaptchaWidget(explicit=True)) I tried to render it at my html page with undermentioned code (after following step-by-step these GitHub instructions on "Multiple render example"). It didn't work. Captcha field shows up only once in non-reply comment form, in replies there is only captcha title/label. I'm wondering if it is even possible to render multiple captcha using "for" loop in such way. Html part: {% extends "base.html" %} {% load recaptcha2 %} <!-- head extension --> {% block head_extra %} {% recaptcha_explicit_support %} {% endblock head_extra %} <!-- body extension --> {% block content %} <!-- post display part --> <!-- ... --> <h2>Comments</h2> <form method="POST" action='.'>{% csrf_token %} {{ comment_form }} <input type="submit" value="Post comment" class="btn btn-default" > </form> {% for comment in comments %} <!-- parent comment display part --> <!-- β¦ -
Search results with spaces in the middle of a word
I have a problem with spaces in the middle of a word (a search result via whoosh). I get for example: "k ΓΆ nnen" "Γ ber" This is my code, but it does not work: {% with object.content|safe as text %} <p>{% highlight text with query html_tag "i" max_length 50 %}</p> {% endwith %} -
Cache all pages with @cache decorator, Django
I have some pages that are cached on a weekly basis, however, when new data is inserted, I need to clear the cache and update it. This is my current solution, it works but the code isn't very clean and it takes a very long time to load, any suggestions? @staff_member_required def reset_cache(request): from django.core.cache import cache import urllib2 cache.clear() urllib2.urlopen('http://XXXXXX.com/api/gyms/') urllib2.urlopen('http://XXXXXX.com/api/fitness/') urllib2.urlopen('http://XXXXXX.com/api/supplement_stores/') urllib2.urlopen('http://XXXXXX.com/api/food_stores/') urllib2.urlopen('http://XXXXXX.com/api/food_menu/') urllib2.urlopen('http://XXXXXX.com/api/workouts/') urllib2.urlopen('http://XXXXXX.com/api/articles/') urllib2.urlopen('http://XXXXXX.com/api/events/') urllib2.urlopen('http://XXXXXX.com/api/supplement_search/') return HttpResponse('DONE') -
Python ImportError: No module named
I try to run django project, which has this structure: projectx βββapps β βββ app1 | | βββ __init__.py | | βββ ... β βββ app2 | βββ __init__.py | βββ ... βββproject β βββ settings.py β βββ urls.py β βββ __init__.py | βββ ... βββ manage.py βββ ... It has two apps in one project. Well, while running python manage.py runserver I get ImportError: No module named apps $ echo $PYTHONPATH gives /home/alexander/Work/projectx Django version 1.9.8 INSTALLED_APPS = [ ... 'apps.app1', 'apps.app2' ] -
Use javascript variable with django template
I have a brain model with different resolutions and I want to let the user to change the resolution of the the model by just choosing his desired resolution from a select tag. I mean I have the complete models loaded and without sending a POST to the server I want to change the view of the brain model. The problem is that I can't pass the read value from the select to my django tag to choose the suitable moedl to render. This is my code: <body> <select id="resolution_options" onchange="change_brain_resolution()" name="resolution_options"> {% for brain in brains %} <option value="{{ brain.resolution }}"> {{ brain.resolution_title }} </option> {% endfor %} </select> <script> function change_brain_resolution() { var selcted_resolution = getElementById('resolution_options').value; {% for brain in brains %} // Here is my problem !! {% if brain.resolution == selcted_resolution %} // Do drawing {% endfor %} } </script> </body> The reson of why I don't want to do a POST is because there are many other things the user have been drawing and doing and he may want to change the resolution of the brain model in order to have a better view or performance but he wants to keep the other objects in β¦ -
Having error null value in column "publicatithon_date" violates not-null constraint in django
Hello I'm new to django and I'm learning django with this book: djangobook.com and I stuck in chapter 5 & 6 because when I try to check my work(in http://127.0.0.1:8000/admin/books/book/add/) I get some errors and I was trying to fix those errors and after that they gone but I got a new error and I tried to figure out how to solve it but I still don't know how. This is my error: IntegrityError at /admin/books/book/add/ null value in column "publicatithon_date" violates not-null constraint And you can see all of my codes here: https://github.com/Anahitahf/mysite2 How can I solve this error? Thanks in advance for any feedbacks. -
When should token be generated using oAuth
I am striving to understand oAuth2 to implement in my REST API. I am using DRF in my backend and react native for building mobile app. I can create user registration and login in DRF but when and where should i actually create a token. Do i have to create token when user registers or when user logins ? I might get negative voting but i know some expert will enlighten me. The usecase is i have a mobile app called foodie where user can create their account and login. User can login and create account from web too. Where should i actually implement oAuth token in my code? serializers.py class UserCreateSerializer(ModelSerializer): class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'password', 'confirm_password' ] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): username = validated_data['username'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] email = validated_data['email'] password = validated_data['password'] confirm_password = validated_data['password'] user_obj = User( username = username, first_name = first_name, last_name = last_name, email = email ) user_obj.set_password(password) user_obj.save() return validated_data class UserLoginSerializer(ModelSerializer): # token = CharField(allow_blank=True, read_only=True) username = CharField() class Meta: model = User fields = [ 'username', 'password', # 'token', ] extra_kwargs = {"password":{"write_only": True}} β¦ -
Using gmail api with Django
I'm trying to use gmail api, but thought install oauth2client in library i don't have django_orm file. I'm using Django 1.9.6 with python 2.7.11 -
Django: Boost up the queries to models editable by admins only
First of all, my database is in Cloud SQL where each different query has a latency. So need to reduce the total number of queries to the Cloud SQL. In order to avoid the hits to the tables like the configuration, rank-table and so on which is in the Cloud SQL which is only editable by the admins that to once in awhile like in updates. Also their are forging keys in the user intractable tables to these read only tables to the users editable by admins. So is their any ways to avoid this latency which will increase the performance of the app.Like multiple database or making copy of the table in the local or redis cache or anything which might help it out. Thank you for your help. -
NoReverseMatch at /auth/reset/ Reverse for '' with arguments '()' and keyword arguments '{TEXT}' not found. 0 pattern(s) tried: []
trying to set up Django Password Reset. Sending an Email is working but not with the reset_email Template im using: Someone asked for password reset for email {{ email }}. Follow the link below: {{ protocol}}://{{ domain }}{% url 'confirm' uidb64=uid token=token %} my urls.py: url(r'^reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', views.reset_confirm, name='reset_confirm'), url(r'^reset/$', views.reset, name='reset'), my views: from django.core.urlresolvers import reverse from django.contrib.auth.views import password_reset, password_reset_confirm def reset_confirm(request, uidb36=None, token=None): return password_reset_confirm(request, template_name='reset_confirm.html', uidb36=uidb36, token=token, post_reset_redirect=reverse('accounts:login')) def reset(request): return password_reset(request, template_name='reset.html', email_template_name='reset_email.html', subject_template_name='reset_subject.txt', post_reset_redirect=reverse('accounts:login')) and the concrete Errormsg with {url ... } highlighted: NoReverseMatch at /auth/reset/ Reverse for 'password_reset_confirm' with arguments '()' and keyword arguments '{u'uidb64': 'Mjg', u'token': u'4f3-661d633360a4ee3e23c2'}' not found. 0 pattern(s) tried: [] 1 Someone asked for password reset for email {{ email }}. Follow the link below: 2 {{ protocol}}://{{ domain }} {% url 'password_reset_confirm' uidb64=uid token=token %} changing the uidb64 to 36 in the reset_email Template didn't help. Any Idea? -
Conditional in Django Tables
I am trying to include a conditional in my Django table, but I am having some issues finding the correct syntax to do so. I have a boolean field in one of my models, and based on that value - I would like to render a different label_link and callback url for that specific db record. Here is the code I am using: class Feature(BaseTable): orderable = False title_english = tables.Column() featured_item = tables.Column() if (featured_item == False): actions = tables.TemplateColumn(""" {% url 'add_feature' pk=record.pk as url_ %} {% label_link url_ 'Add to Features' %} """, attrs=dict(cell={'class': 'span1'})) else: actions = tables.TemplateColumn(""" {% url 'remove_feature' pk=record.pk as url_ %} {% label_link url_ 'Remove From Features' %} """, attrs=dict(cell={'class': 'span1'})) Now I am aware currently that this is just checking to see if the value exists - therefore always rendering the code under the else statement. I have been unable to find any documentation that covers this particular nuance of Django tables. Note: I'm using Django 1.5 and Python 2.7 -
form._raw_value(fieldname) gone in Django 1.9
I have code which uses form._raw_value(fieldname). This is gone in Django 1.9. Is there a way to access the raw value in 1.9+? -
How to display Foreign Key's choices in django-admin?
I have small problem related to django-admin panel. I have 2 models: from django.db import models class Subject(models.Model): subject = models.CharField(max_length=30, choices=[('P', 'Personal'), ('W', 'Work')]) def __str__(self): return self.subject class BlogPost(models.Model): id = models.AutoField(unique=True, primary_key=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) text = models.TextField(null=False) pic = models.ImageField(upload_to='static/img/', default='static/img/no-image.png') date = models.DateTimeField() def __str__(self): return self.subject But in admin panel whenever I try to create blog post, dropdown menu doesn't show any of subject's choices. Do I need to edit admin render function ? -
Command "python setup.py egg_info" failed when installing a package
I am trying to install a bunch of dependencies from the requirements.txt file of a cloned Django project. However, when it's trying to install one of them, vobject-0.8.1c the following error is displayed and none of the dependencies are installed: Command "python setup.py egg_info" failed with error code 1 in c:\users\xxxxxx\appdata\local\temp\pip-build-n_0xlr\vobject\ I have spent hours trying to solve this problem. All the issues I see about it suggest installing or upgrading setuptools and ez_setup. I have done that and I still get the error, so the project keeps having a ton of missing dependencies. I am on Windows. What can I do? How can I install these dependencies? -
How should I configure my timezone
I don't know if I'm stupid or something. But using the following settings with Django/Mezzanine I don't get what I want: USE_TZ = True TIME_ZONE = 'UTC' This sets ALL posts to the UTC automatically. So: POST IS SET TO PUBLISHED 8 AM POST IS PUBLISHED 10 AM Screenshot: http://i.imgur.com/A9mnBR5.png When pressing the now button I get the current time in my own time zone, but it is still published 2 hours later. My current time zone is Europe/Stockholm. I want it to actually get published at 8 AM and visible when 8 AM occurs in the users actual time zone. I don't know how that is possible. Hopefully this makes sense to you guys. -
django migrate error TypeError
i try migrate this code: from django.db import models class User(models.Model): ids = models.IntegerField(default=0) and i get error: TypeError: expected string or bytes-like object help me please, thanks. -
How to use serializers.ListField in DRF?
I have a serializer class show as below: class RegisterPOSTSerializer(serializers.Serializer): username = serializers.CharField() sessionage = serializers.IntegerField() active = serializers.BooleanField() homes = serializers.ListField( child=serializers.IntegerField() ) homedefault = serializers.IntegerField() groups = serializers.ListField( child=serializers.IntegerField() ) And this is data dump from javascript {"active":1,"username":"MDC","sessionage":1800,"groups":[2],"homes":[1,2],"homedefault":1} This is how i use serializer: serializer = RegisterPOSTSerializer(data=request.data) serializer.is_valid(): return HttpResponse(JSONRenderer().render(serializer.data), content_type="application/json", status=200) This is the return data: {"sessionage":1800,"active":true,"homes":[],"homedefault":1,"groups":[],"username":"MDC"} Why 'homes' and 'groups' are empty? And how can i retrieve them? -
How to get the model name of a corresponding db table
I know the table name in mysql that i am working on. I need to find the corresponding model name. Is there a way to find the model name?