Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix Django Translation ASCII decode error?
I have this django website translating from english to german from the locale/lc_messages/django.po and django.mo files. But, when i try to translate the words which are in german letters like ü and ä, it gives me the error 'ascii' codec can't decode byte 0xe3 in position 6: ordinal not in range(128) As far as I can think, django is trying to decode the unicode characters through ASCII which is not possible. But how do i fix this ? Where should I make the setting for django to decode through utf-8 and not through ASCII. Or let me know if I am wrong. -
Issue reading variable from context processor related to google analytics
I try to deploy google analytics with Django and I face something which have to be quite simple. I have followed the instructions from here and here and I can make the analytics work when I include directly in my script the Google Analytics ID. But when I try to load it from Django nothing is loaded. Here is the different parts of the code: First the ga.html file which included the script retrieved from google analytics page: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o) [0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google- analytics.com/analytics.js','ga'); ga('create', '{{ GOOGLE_ANALYTICS_ID }}', 'auto'); ga('send', 'pageview'); </script> Then my context_processor: def google_analytics(request): """ Use the variables returned in this function to render your Google Analytics tracking code template. """ ga_prop_id = getattr(settings, 'settings.GOOGLE_ANALYTICS_ID', False) if ga_prop_id: return { 'GOOGLE_ANALYTICS_ID': ga_prop_id, } return {} Then I added the context processor in my settings.py file: 'project.context_processors.google_analytics', .. And also in the settings.py file I retrieve the api key (set in my environmental variables): GOOGLE_ANALYTICS_ID = os.environ.get('GOOGLE_ANALYTICS_ID', False) Lastly in my site_base.html I pass the script as: {% include "ga.html" %} -
sqlalchemy syntax to search on joined object attribute
suppose I Have a couple of objects, in parent - childs relation class Artist(Base): __tablename__ = "artists" id = Column(Integer, primary_key=True) name = Column(String) class Album(Base): __tablename__ = "albums" id = Column(Integer, primary_key=True) title = Column(String) artist_id = Column(Integer, ForeignKey("artists.id")) artist = relationship("Artist", backref=backref("albums")) If I want to find "the artists whit one album titled foobar" I can do session.query(Artist).join(Album).filter(Album.title=="foobar") Is this the simplest syntax possible or there is some sugar I'm missing from documentation / googling sparing me the explicit join ? ie with Django ORM I could: Artist.objects.filter(albums__title='foobar') ( not having to explicitly import Album and add a join method is more convenient if I need to build my query at runtime, like from params of a user interface ) -
Extending Ember JSONAPIAdapter findAll for fetching json from custom url
I'm relatively new to Ember.js and I'm trying to studing how ember works and I've this problem: from an Ember.js route I will call my django api like this: this.store.findAll('MYMODEL', 'ANOTHER_MODEL_ID') This findAll will produce an api call like /mymodel/another_model_id/ where another_model_id is a dynamic id (uuid like string). I've tried to override the findAll method with a custom adapter (mymodel adapter) that extends the ApplicationAdapter (JSONAPIAdapter with a custom buildUrl for adding trailing slash). But my attempt failed, because in findAll overridden method I can't reach the ANOTHER_MODEL_ID parameter. I've also tried to override urlForFindAll and buildUrl methods with the same results. What is the best method for doing this kind of things and how can I do? -
nginx holding request in pending state in case of load of hardly 50 users
I have two Nginx servers installed on different Amazon EC2 instances, One for Frontend and another one for backend. On frontend we are using angular and on backend we have python, Django & Django REST framework in place. My site works perfect in case of low traffic but as soon as we increase the traffic using JMETER tool of around 50 users load it slows down significantly. I tried removing the frontend server from picture and tried firing REST calls through postman, i also putted logs at the top of that REST function and at the end of that rest function. After doing this i found that the time taken is between the REST call reaches to the function and function takes no time to execute the request and send back the response, this exercise was done at the time of load. We also checked the slow query and found that there were no slow query logged at the DB level. Configuration files of backend server are as follows: user ubuntu; worker_processes 4; pid /var/run/nginx.pid; worker_rlimit_nofile 256000; events { worker_connections 4000; multi_accept on; use epoll; } http { ## # Basic Settings ## # Caches information about open FDs, freqently … -
Debug Visual Studio Publish to Azure - Django
I have Django app that I need to test publish on Azure websites. I try the Publish on visual studio but it fails with no log output I am using the Web Deploy publish feature. https://github.com/Microsoft/PTVS/wiki/Django-and-MySQL-on-Azure ------ Build started: Project: ota, Configuration: Release Any CPU ------ ------ Publish started: Project: ota, Configuration: Release Any CPU ------ ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ========== ========== Publish: 0 succeeded, 1 failed, 0 skipped ========== pretty useless, right? I should mention I imported the project later as python project and VS recognized it, and I created virtual env with all necessary python libs and I can debug the project on localhost. But publishing to Azure is failing and I can't debug because there is no useful trace -
How to download files form remote directory using python?
I have a remote directory with mp4 files and I need to download them into my Desktop . So basically I need to download a remote directory with given url . How to do it ? -
django authenticate() for custom user model
Below is my custom user model: class CUserManager(BaseUserManager): def _create_user(self, email, first_name, password, is_staff, is_superuser, **extra_fields): """ Creates and saves a User with the given email and password. """ now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, first_name = first_name, is_staff=is_staff, is_active=False, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, first_name, password=None, **extra_fields): return self._create_user(email, first_name, password, False, False, **extra_fields) def create_superuser(self, email, first_name, password, **extra_fields): return self._create_user(email, first_name, password, True, True, **extra_fields) class CUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=254, unique=True) first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_active = models.BooleanField(_('active'), default=False, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) last_updated = models.DateTimeField(_('last updated'), default=timezone.now) objects = CUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] It creates a new user correctly. But when I try to authenticate the user from shell or from views, the authenticate() function doesn't work for users having is_active=False. >>> from django.contrib.auth import get_user_model, auhtenticate >>> u = … -
Concurrent nested requests in a microservices environment built with Django
I'm developing a microservices architecture with Django in which services communicate each other through RESTful APIs. A request coming from a client is served by a service, which then requires to make a new (nested) HTTP request to another service (as it is shown in this picture) in order to mantain decoupling between services. In this scenario, it may happen that two different requests are fired by the client and served simultaneously by the first service. Then, one of the two nested requests to the second service remains unserved until a 503 error (Service Unavailable) occurs. It seems that concurrency between nested requests is bad handled by the server. RESTful APIs are implemented with Django REST framework and nested requests are made with the Python requests library. Here is an example: from rest_framework.views import APIView import requests class FirstServiceView(APIView): def get(self, request, format=None): # Code... # The nested requests to the second service response = requests.get("http://127.0.0.1:8000/second_service/") # Other code... It's worth noting that this behaviour happens with both the development server of Django and Apache. Furthermore, no concurrency on the database is involved in this case. -
Redis for Channels in Django with Gunicorn and Nginx
How to install and configure Redis, asgi-redis for Django Channels? I have Django1.9 with Gunicorn and Nginx. Help me please. -
is it possible to make a query lookup for given model inheritance?
Below are my models and I am using InheritanceManager of django-model-utils. i decided the field user to be in the subclasses because i need to access the Child subclass via the relation like user.child1_set.all(). class Mother(models.Model): objects = InheritanceManager() class Child1(Mother): user = models.ForiegnKey(User) class Child2(Mother): user = models.ForiegnKey(User) the problem is, when i want to query starting from Mother class, there seems to be no query that makes it. i've tried these codes. Mother.objects.filter(user=SOMEUSER) Mother.objects.filter(child1__user=SOMEUSER) Mother.objects.select_subclasses().filder(user=SOMEUSER) Mother.objects.select_subclasses().filder(child1__user=SOMEUSER) any advice would be appreciated. -
How to not require extended user model fields for a superuser
I have extended the in built user model in django via AbstractUser. However when it cam to deployment and to create a superuser it failed because of having a null entry in some of the additional fields in the extended model. Is there a way to have these fields not required for a superuser but required for a normal user. (I presume this is a typical use case - as I don't need an admin to fill out address, account number etc...) models.py class User(AbstractUser): title = models.CharField(max_length=255, null=True) date_of_birth = models.DateField() phone_number = models.IntegerField(null=True) account_name = models.CharField(max_length=255) account_number = models.IntegerField() house_name_number = models.CharField(max_length=255, verbose_name="house name or number") street_name = models.CharField(max_length=255) town_city = models.CharField(max_length=255) county = models.CharField(max_length=255) postcode = models.CharField(max_length=8) -
Cant find pg_config even after installing Postgres 9.5
I have been trying to debug this for quite a while now (and read lots of related Q/A on StackOverflow) but unable to figure this out. Trying to setup Django on my Mac OS X 10.11.6. I followed the detailed tutorial. This is what I did: 1) Installed Python 3.5.2 (by directly downloading the package from the Python web site and running it). 2) Installed PostGres 9.5 using the fink package (fink install postgresql95) 3) Installed psycopg2 using the fink package (fink install psycopg2-py35). 4) Updated pip. 5) Setup a virtual environment and activated it. 6) After activating the environment, installed Django (via pip). Next, when I tried to setup a sample app in the environment and ran python manage.py migrate, it gave me the error : Error loading psycopg2 module: No module named 'psycopg2' After reading a lot of posts on StackOverflow, it seemed that I have to install psycopg2 again within the virtualenv (and for some reason, I cant use Fink again?). So as suggested on some posts, I tried to install it using: pip install psycopg2 Got this error:Error: pg_config executable not found. I am sure my Fink install of Postgres 9.5 was successful earlier, so I … -
Django: get result of raw SQL query in one line
This works: connection = get_connection() cursor=connection.cursor() cursor.execute('show application_name') application_name_of_connection=cursor.fetchone()[0] But why four lines? Is there no way to get this in one line? -
Django with MySql
I would like to create a small project with a login system that is online and can be accessed for anywhere. I wanted to use Python/Django. I researched and found that Django comes with Sqllite, but that is useless because it is offline. I have searched on and on for tutorials, but I dont see how to set up Django with a SQL login system. All I find is PhPMyAdmin + MySql. -
Django: ascii Traceback from Debug Page (HTML)
I write integration tests, which go through the whole HTTP stack: requests library connects to http server http server routes request to the django application django application processes the request If there is an uncaught exception in the django application I get the HTML debug page, since settings.DEBUG is True. In most cases I like this page, but here want to have a simple ascii traceback which can I can show in our Continuous Application tool (Jenkins). How to get an ascii traceback if I test my application with an url client library? -
Set Django REST serializer field default value from method
In my Order model I have fields for billing infos (street, country, vat, etc). How can I set default values for the OrderSerializer fields, when values comes from another model (CustomUser, where I save default billing infos)? Thank you -
How to enable the project and make it appear in the Google Analytics dashboard
I am trying to enable google analytics in my Django project. I have done the following steps: 1) Got a google analytics API key. To do that I partially followed the instructions from this site: enter link description here 2) Added google analytics in my Django project as described here: `http://www.nomadblue.com/blog/django/google-analytics-tracking-code-into-django-project/ I login in my googleanalytics page (with the gmail credentials which I used to create the apikey) but I have no idea how to add my new created project there. I only see an old project. So the question is how to enable the new project and make it appear in the google analytics dashboard. -
ValueError: The file 'css/style.css' could not be found with whitenoise
I am trying to deploy an app using heroku. But for some reason, the static files are not loaded with whitenoise and there is an internal server error message in the browser : Internal Server Error The server encountered an unexpected internal server error (generated by waitress) In the heroku logs : ValueError: The file 'css/style.css' could not be found with whitenoise.django.GzipManifestStaticFilesStorage object at 0x7f5da0186750 Here are some points. an empty static file (with an empty robots.txt in) is created in the root folder for heroku. python manage.py runserver : everything works fine. no issue. heroku local 500 error. (but the view still shows up) css file path : myhellowebapp/collection/static/css/style.css If I comment out STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage', the error message in the browser disappear and I can see html of the app in the browser, but no css file is attached So it has to do with whitenoise but no I idea how to fix this. setting.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... STATIC_URL = '/static/' STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) settings_production.py : from hellowebapp.settings import * ... STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' wsgi.py : import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hellowebapp.settings_production") from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = get_wsgi_application() … -
Print the value if associated parent table in django
Working on django project, I have an Event table. Every event in this table belongs to a particular user. class Event(models.Model): user_id=models.ForeignKey(User, on_delete=models.CASCADE) event_auth_id=models.CharField(null=True, max_length=225) event_auth_step2_id=models.CharField(null=True, max_length=225) event_title=models.CharField(max_length=225) I am writing a query on Event model and using values() method to find values of specific columns, But i also wants to print that user's email id which is in User model. Query is:- events = Event.objects.all().filter(**filters).values('id', 'event_title', 'category', 'event_start_from', 'event_start_to', 'created', 'modified', 'event_status') How can i print the value of user's email which is in users table. also i want to add a filter to filter users by email id, but want to write query on Event model -
When saving django models that have foreign keys, how to save all at once?
I currently have the following models class Chat(models.Model): id = models.BigAutoField(primary_key=True) subject = models.CharField(max_length=200) last_message = models.OneToOneField(to='Message', on_delete=models.PROTECT, related_name='last_chat') class Message(models.Model): id = models.BigAutoField(primary_key=True) chat = models.ForeignKey(to='Chat', on_delete=models.CASCADE) user = models.ForeignKey(to='accounts.User', on_delete=models.PROTECT) text = models.CharField(max_length=200) date = models.DateTimeField() The problem is, in order to create a new chat room, I will have to insert a new chat object and a new message object. But since they both reference each other, inserting either will cause a ForeignKey constraint error. How do I solve this? Delay the enforcement of foreign keys until after I have saved both -
Tranfer money from one account to multiple accounts as a Scheduled task
I am new to payment integration. My requirement is I need to transfer money from one account to multiple accounts as a scheduled task.The amount to be tranferred will be different for different recipients each time. Is paypal an option? If yes how ? -
Django decorator to restring users to delete or update others entries
My site has users and entries. I want to create a Django decorator to restring users to delete or update others entries. But I have been able to do some. I was thinking something like this class EntryUpdate(generic.UpdateView): model = Entry fields = ['...'] .... @user_passes_test(lambda user: current.user.id == entry.user.id) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(EntryUpdate, self).dispatch(*args, **kwargs) -
Model Multi Parent Mult Child django admin
I have a parent model "Playbook". Each playbook has many related "Activities" I need to show the list_display of "Activities" in django admin for each "playbook". They way I have currently shows all activities for all the playbooks. Not sure how be able to just show the Activities for each playbook in a list_display. Here is what I have: Platform: django v 1.10.x, python 3.5.x Modal.py class TimeStampModel(models.Model): created = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name='Created') updated = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name='Modified on') class Meta: abstract = True class PlayBook(TimeStampModel): name = models.CharField(max_length=200, unique=True) description = models.TextField(blank=True, help_text="Business purpose of the application") owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ('name',) @property def short_description(self): return truncatechars(self.description, 35) def __str__(self): return "{}".format(self.name) class Activity(TimeStampModel): minor = 'MINOR' normal = 'NORMAL' important = 'IMPORTANT' critical = 'CRITICAL' SEVERITY = ( (minor, 'Minor'), (normal, 'Normal'), (important, 'Important'), (critical, 'Critical'), ) low = 'LOW' high = 'HIGH' PRIORITY = ( (low, 'Low'), (normal, 'Normal'), (high, 'High'), ) new = 'New' in_progress = 'In_Progress' needs_info = 'Needs_Info' postponed = 'Postponed' closed = 'Closed' STATUS= ( (new, 'New'), (in_progress, 'In_Progress'), (needs_info, 'Needs_Info'), (postponed, 'Postponed'), (closed, 'Closed'), ) playbook = models.ForeignKey(PlayBook) subject = models.CharField(max_length=200, unique=True) description = models.TextField(blank=True, help_text="Business purpose of … -
Django How to manage static file when you run server?
I put static files under a app directory which is related to the static files. for example, image.jpg is used for templates under exmapleapp. so I locate image.jpg file in a directory /project/exampleapp/static/image.jpg In Debug=True settings, Dajngo finds static files automatically by django.contrib.staticfiles. If you put static files projoject directory /project/static/, you can set STATICFILES_DIRS = []in settings.py or add like urlspatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) in urls.py(if you want to serve static files manually) so far, is nothing problem in development right? but you want to deploy, you need to do collectstatic. I am confused from now. This is what I thought initially. step1 : you work and test your code in local with DEBUG = True in setting. you continously save your code in git repo. step2 : you are ready to deploy your code in server. you clone your repo and set apache server for running django framework properly(Alias static, WSGI Daemon process). you do python manage.py collectstatic to serve static file with apache server. step3 : you keep work in local to improve your code and apply this improvement into your code in server with test. I got confused and got questions. Q1 : if you do …