Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make spaces and indentation insignificant in Django blocktrans?
Image the following blocktrans in some Django template: {% blocktrans %} Some Text {% endblocktrans %} After some changes in the templates, you might like to indent the block: <div> {% blocktrans %} Some Text {% endblocktrans %} </div> This is going to change your message in the translation files, and mark them as fuzzy. While technically, it is the same message (only the indentation is different). The whole process of "unfuzzyfying" those messages is tedious and error-prone. What I tried so far: Using trans as much as possible - doesn't always work Keeping the initial indentation of blocktrans statements - hard to maintain Tried to find more information in documentation and other resources Is there a way to make the indentation in blocktrans insignificant? -
django+celery+rabbitmq encode error and sig-kill
I'm now doing a little project which uses celery to turn csv and xlsx files into postgresql table. The code below works fine without celery(except large files),but after using celery it produce some errors and bugs. I've looked for similar questions in StackOverFlow but don't have any idea how to do and why. Hope you guys can help me with it,thanks. First error is as follows: csv-1 csv-2 I think it has something to do with my encoding part, but I tried to open it with utf-8-sig and big-5, not working.(It works fine without celery) ` # -*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib import messages from django.conf import settings from django.db import connection from django.views.decorators.csrf import csrf_exempt from celery import Celery from celery import task import json import csv import sys import random import psycopg2 import xlrd import openpyxl as pyxl from .models import Document from .forms import DocumentForm app = Celery( 'tasks', broker='amqp://guest:guest@localhost:5672//', backend='rpc://' ) CELERY_RESULT_BACKEND = 'rpc://' CELERY_RESULT_PERSISTENT = False @app.task() def csvwritein(doc):# Transform csv to table doc = doc conn = psycopg2.connect("dbname='apidb' user='api' host='localhost' password='eric40502' port='5432'") readcur = conn.cursor() readcur.execute("select exists(select … -
Django form is blank after submit
I have a simple form in django's template: <div class="container"> <form action="{% url 'reporter:new_report' %}" method="post" novalidate>{% csrf_token %} {{ report_form.as_p }} <button type="submit" value="submit" class="btn btn-primary">Generuj raport</button> </form> </div> but when I want submit it it send blank fields to my form and I don't know why. This is my views.py: def report_create(request, template_name='reporter/created.html'): if request.POST: report_form = ReportForm(request.POST or None, prefix="report_form") print(report_form["report_name"].value()) #This is blank but I filled it if report_form.is_valid(): report= report_form.save(commit=False) report.save() return render(request, template_name, {}) return redirect('reporter:empty_form') forms.py: class ReportForm(forms.ModelForm): class Meta: model = Report fields = ['report_name', 'create_date', 'additional_findings', 'additional_recommendations', 'report_type'] and models.py: class Report(models.Model): report_name = models.CharField(max_length=100, blank=True) create_date = models.DateField('date of creation', blank=True) additional_findings = models.TextField(max_length=10000, blank=True) additional_recommendations = models.TextField(max_length=10000, blank=True) FULL_REPORT = 'FULL REPORT' NOT_FULL_REPORT = 'NOT FULL REPORT' REPORT_TYPE = ( (FULL_REPORT, 'Full report'), (NOT_FULL_REPORT, 'Not full report') ) report_type = models.CharField(max_length=100, choices=REPORT_TYPE, default=FULL_REPORT, blank=True) I learn Django, I do everything like in tutorials, but I cannot understand why this form is still blank when I want submit it. -
Django: Raw SQL with connection.cursor()
I am a complete newbie to Django. I need to perform the following query and use img.img_loc to populate a list of images in a template: SELECT img.img_loc, author.surname, author.given_name, author.email FROM image_full AS img LEFT JOIN author_contact_zzz AS author ON img.pmcid = author.pmcid WHERE img.pmcid = 545600 GROUP BY img.img_loc, author.email; I read the documentations here: https://docs.djangoproject.com/en/1.10/topics/db/sql/ However, I do not understand where the function: def my_custom_sql(self): that they are talking about in the last section is supposed to go to (views.py ?) and what is 'self' in that case, since my view is not defined as a class. Thanks! -
More explicit message on deletion in Django admin
I have declared in Django admin.py an oeuvre class with a types ManyToManyField to an TypeOeuvre class. class Oeuvre(models.Model): titre = models.CharField(max_length=510) types = models.ManyToManyField('TypeOeuvre', blank=True, verbose_name="Type(s) de l'œuvre") class Meta: ordering = ['titre'] def __unicode__(self): return "{0} [{1}]".format(self.titre[:200], self.id) class TypeOeuvre(models.Model): intitule = models.CharField(max_length=100, verbose_name='Intitulé') commentaire = models.CharField(max_length=255, verbose_name='Commentaire', blank=True) class Meta: ordering = ['intitule'] verbose_name = "Type d'œuvre" verbose_name_plural = "Types d'œuvres" def __unicode__(self): return self.intitule However, when I try to delete a TypeOeuvre object in Django Admin for which relations to one oeuvre exists, the "Are you sure?" warnings do not explicitly mention the name of the oeuvre: Oeuvre-typeoeuvre relationship: Oeuvre_types object Are you sure? message warning Is there a way to display the name of the oeuvres linked to the type ? Thanks, -
Customising django ImageField markup in template
I have a form which allows you to upload an image, but I want to know if it is possible to customise the markup that Django generates. In the model it is created as an ImageField: logo = models.ImageField(blank=True, null=True) In the template I am creating an 'upload' form field using {{ form.logo }} This is the markup that gets generated: Currently: <a href="/media/dog.jpg">dog.jpg</a> <input id="logo-clear_id" name="logo-clear" type="checkbox"> <label for="logo-clear_id">Clear</label> <br>Change: <input id="id_logo" name="logo" type="file"> I want to know if I can change that markup by drilling down further, so that I can for example nest the checkbox to clear the image within its label. I also would like to use my own markup to separate the option to clear the form field from the option to upload a new one. However, I can't find any documentation on how to do this. I've tried outputting {{ logo.logo-clear }} directly but this throws an error. -
What is the use of gettext when django explicitly translates from .po and .mo files?
While I study Internationalisation and Localisation in Django, I am told to install gettext application in my windows. But I can see that the translation is done by the django with the translation strings that we type in .po files. So I can visualise the process that when user selects a particular language, django pulls their language particular strings from .po files in which WE translated the default language. I cannot understand where gettext is used in this process ? in the beginning I thought gettext is used to translate by itself, but it does not. -
Django, many duplicated queries in my TabularInline
This is the part of my models.py: class Media(TimeStampedModel): name = models.CharField(max_length=20) class Topic(TimeStampedModel): medias = models.ManyToManyField(Media, through='TopicAndMedia') class TopicAndMedia(models.Model): topic = models.ForeignKey(Topic) media = models.ForeignKey(Media) order = models.IntegerField(default=0) This is the part of my admin.py: class TopicAndMediaInline(admin.TabularInline): model = TopicAndMedia class TopicAdmin(admin.ModelAdmin): inlines = (TopicAndMediaInline, ) ... When I visit the TOPIC admin site, it's too slow. Here is the snapshot of the django-debug-tool There are many duplicated time-cost queries like select * from 'topics_media'. How can i solve this problem? -
Is it possible to show cleaned value on invalid form in django?
Suppose I have a simple login form with email and password fields. User enter email 'TEST@EXAMPLE.COM' And leaved password empty. I clean email to be lower-cased. Form is invalid and user is shown form again. How to show email lower-cased, i.e. test@example.com? -
Django Celery crash behavior
I'm not good at celery so I need opinions Is it possible in Celery where the task is chasing for example I have a task that is supposed to run for every 2 minutes so the last task is 10:52 which means the next task should run in 10:54 however it crashed in the 10:53 mark and restored at 10:57 Is it possible that my celery node will catch up and still send the supposed to be sent task on 10:54 and 10:56? Or are there any workarounds? Like immediate restore after crash? -
Django: distutils errors when installing requirements.txt
I am trying to setup my app in a fresh computer but I am having trouble installing the requirements.txt file. It fails when trying to install this package in particular: django-generic-m2m==0.2.2 I tried running pip install django-generic-m2m==0.2.2 and indeed I got the same error message, which is an exception thrown by the convert_path(pathname) method in the utils.py file from distutils. I really don't know what do to. These are not my files, so how can I even figure out how to fix the scripts? Has anybody had this problem in the past? Any suggestions? -
Why learn Python(Django) or JavaScript(node.js) [on hold]
I've been wanting to learn a new language beside java for a long time now specially python for making websites using django, but now I came a cross something called node.js framework for javascrtipt and I heard that you can make lots of stuff with it and not just websites. I am not familiar with python and javascript but I want to make websites and web application, and now I'm confused on which should I choose python(Django) or javaScript(node.js), I've been wanting to learn python for a long time but now that I heard about node.js, I'm very confused because they say node.js is good at realtime processes and its fast and you can implement a chat system very easily. So what are the advantages and disadvantages of both languages an framework? what else can you do with python or javaScript? -
Is there any standard way to access models.py that follows EAV -CR pattern to store metadata?
To aceess Django models, generally DJango ORM methods such as get(),filter() are used. But Can Django ORM methods diretly used to access models in EAV-CR pattern? I think I need to write similar method to do so, but Im anot sure. If not, then is there any standard way or best practice to access models.py that follows EAV -CR pattern to store metadata? Do I need to elaborate more? Your response is appriciated. -
django inlineformset_factory MultiValueDictKeyError on update
I have inlineformset_factory form, that is working good with creating new records but while updating it facing some MultiValueDictKeyError issue I have also attached the id as hidden field in the form, forms.py class Menu(forms.ModelForm): .... .... class MenuPriceForm(forms.ModelForm): min_person = forms.CharField(widget=forms.TextInput(attrs={'placeholder': _('Minimum Person'), 'required': True})) max_person = forms.CharField(widget=forms.TextInput(attrs={'placeholder': _('Maximum Person'), 'required': True})) price = forms.CharField(widget=forms.TextInput(attrs={'placeholder': _('Price per person'), 'required': True})) class Meta: model = MenuPrice exclude = ('menu','price_per_person') def __init__(self,*args,**kwargs): super(MenuPriceForm,self).__init__(*args,**kwargs) for name, field in self.fields.iteritems(): field.widget.attrs.update({'class': 'form-control'}) MenuPriceFormSet = inlineformset_factory(Menu, MenuPrice, form=MenuPriceForm, extra=1, can_delete=True) views.py my post method def post(self, request, *args, **kwargs): self.slug =kwargs.get('slug', None) if self.slug: self.object = Menu.objects.get(slug=self.slug) menu_price_formset = MenuPriceFormSet(request.POST, instance=self.object) else: ... #for few records, this block works fine Check the image for form rendering also. Can any one guess why unable to update it -
How to use sentry logging with multiple raven config
Can I define multiple RAVEN_CONFIGs in my Django settings with different dsn values for them and then configure somehow so that when I get errors from files in one Django app, they get logged in one Sentry store and other Django app in another Sentry store? -
Why python requests delete logout empty cookie?
I'm using python requests in a django application to proxy http requests. every thing is allright but when I want to handle a logout proxy requests module delete empty cookie which is sended from server. the set-cookie header is like this: Set-Cookie: sessionid=; expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/ but response Cookiejar is empty. How can I get this set-cookie header from response? -
How to change default root directory in apache2 from /var/www/ to /home/ubuntu/project/
I have configured apache2 to run my django application on ubuntu server but I'm facing issue while uploading images at my desired directory, it goes into /var/www/ directory. I have edited '000-default.conf' file in apache2 with the directory I want the webserver to take as root directory for my application as bellow. DocumentRoot /home/ubuntu/project/ <Directory /home/ubuntu/project/> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> and /etc/apache2/apache2.conf <Directory /home/ubuntu/project/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> After this change I have restarted the web server. Still when my django application uploads any images it goes in /var/www/ directory. I don't understand why its happening even if I have changed the apache root directory from /var/www/ to /home/ubuntu/project/ Please suggest ... -
Python Django change value based on selectbox index changed
I have a table that fetches data from a python django database the first column is a select box with products names i want the value of price column to change based on product selection how do i achieve that <table> {% for item in items %} <tr> <select name="sel0" id="selectbox" onchange=""> {% for product in products %} <option value="{{ product.id }}" id="optionval">{{product.name}}</option> {% endfor %} </select> <td>price</td> <td>Quantity</td> <td>Total</td> </tr> {% endfor%} </table> -
Putting data into database using Django
I'm trying to put users data into database. I just started to learn Django and did write this code below. I don't get any error messages but still my data doesn't seem to be placed in database. Can someone please point me what did I missed? Thanks! models.py class CreateUser(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100) password = models.CharField(max_length=50) email = models.EmailField(max_length=100) def __str__(self): return self.username forms.py class RegistrationForm(forms.Form): email = forms.EmailField(required=True) first_name = forms.TextInput() last_name = forms.TextInput() username = forms.TextInput() password = forms.TextInput() views.py def data(request): if request.method =="POST": form = RegistrationForm(request.POST) if form.is_valid(): username = request.POST.get('username', '') first_name = request.POST.get('first_name', '') last_name = request.POST.get('last_name', '') email = request.POST.get('email', '') password = request.POST.get('password', '') data_obj = CreateUser(username=username, first_name=first_name, last_name=last_name, email=email, password=password) #Get data into the CreateUser model data_obj.save() return HttpResponseRedirect('register_god') else: form = RegistrationForm() return render(request, 'chatapp/index.html', {'form':form}) index.html <form action="{% url 'register_god' %}" method="post"> {% csrf_token %} <p>Username</p><input type="text" name="username"/> <p>First name</p><input type="text" name="first_name"/> <p>Last name</p><input type="text" name="last_name"/> <p>Email</p><input type="text" name="email"/> <p>Password</p><input type="text" name="Password"/> <input type="submit" value="submit"/> </form> </body> -
Why do I get a "SSL error: called a function you should not call" with Django
I have a Python 3.5/Django 1.10 app served by Apache/mod_wsgi over SSL. It is connected to a Postgres database and is running on a server at AlwaysData It works fine most of time but I have some errors that I don't understand. (SSL error: called a function you should not call) It seems to occur while querying the database. # django/db/backends/utils.py line 64 return self.cursor.execute(sql, params) Why does it happen? How to fix this problem in my Django project. Note : This question looks similar but I don't manage the OpenSSL layer directly so it is not very helpful. -
How to POST a data to URL using django?
I get this error while running it in my django server fetch_url() takes exactly 3 arguments (1 given) here is my view.py import urllib import requests # Tries to open the url with the params through the method specified def fetch_url(url, params, method,request): params = urllib.urlencode(params) if request.method=="GET": f = urllib.urlopen(url+"?"+params) else: # Usually a POST f = urllib.urlopen(url, params) return (f.read(), f.code) url = "http://testingserver.solutions/addulafsdste/api/sersdfdfvices/camsdfpaign" method = "POST" params = {"user_id": "2"} # Fetch the content and response code [content, response_code] = fetch_url(url, params, method, request) # Check if the server responded with a success code (200) if (response_code == 200): print content else: print response_code -
Python: Compound functions inside class
I am trying to replicate something similar to model queries in Django. # database.py class ModelFactory(object): def __init__(self, table): self.table = table def fields(self, *args): str_columns = '' for count, arg in enumerate(args): if count == 0: str_columns += arg else: str_columns += ', %s' % arg self.str_columns = str_columns def wheres(self, **kwargs): str_wheres = '' for count, (key, value) in enumerate(kwargs): if count == 0: str_wheres += 'WHERE %s = %s' % (key, value) else: str_wheres += ' AND %s = %s' % (key, value) self.str_wheres = str_wheres My idea is to use it as follows: from database import ModelFactory myInstance = ModelFactory('myTable') myQuery = myInstance.fields('column1', 'column2').wheres(column1 = 5) I am not sure if I need a new class or function inside ModelFactory class that would take the results from 'fields' and 'wheres' to compile a SQL string to query? Like the following line: cur.execute('SELECT column1, column2 from myTable WHERE column1 = 5') I am also not sure if calling class.function1.function2 is correct? Django has the 'objects' word, e.g. Instance.objects.filter().exclude() -
Django : uploading too slow
I have a Django App running in Compute Engine(GCE) and my problem is that everytime I upload a not so large file like 1MB, the upload time is more than a minute. Is this normal? or I have mis-configuration somewhere in my code like maybe in Nginx. I tested uploading 2 image files (1.2MB and 2.4MB) in my local and in the production site. 1.2MB Local : 2 -3 seconds Live : 50-60 seconds 2.4 MB Local : 5-6 seconds Live : 1.5 - 2 minutes nginx config server { listen 80; server_name example.com www.example.com; return 301 https://www.example.com$request_uri; } server { listen 443 ssl; server_name example.com www.example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers 'ECDHE-RSA-AES256-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-EDH-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:RSA-RSA-AES256-SHA:AES128-GCM-AES128:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA'; location / { include uwsgi_params; uwsgi_pass unix:/sock/path/application.sock; uwsgi_read_timeout 600; } location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /project/static_path/static/; } location /media { alias /project/static_path/static/uploads; } location ~ /.well-known{ allow all; } } uwsgi config [uwsgi] project_path = /project/path/ chdir = %(project_path) home = /environment/path/ module = root.wsgi:application master = true processes = 5 socket = %(project_path)application.sock chmod-socket = 666 vacuum = true uid = current_user gid = www-data die-on-term = true logto = /var/log/uwsgi/app/%n.log Thanks! -
Uncaught Error: [$injector:modulerr]
here is header.html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <!-- Angular Includes --> <script type="text/javascript" src="{% static 'js/myHeader.module.js' %}"></script> <body ng-app="myHeader"> <div ng-controller="HeaderController"> <h1>{{message}}</h1> </div> </body> here is myHeader.module.js var myHeader = angular.module('myHeader', []); myHeader.controller('HeaderController' , ['$scope', function($scope){ $scope.message = "hello"; }]) i am trying to use the above module file but it throws me the error Failed to instantiate module myHeader due to: Error: [$injector:nomod] http://errors.angularjs.org/1.5.6/$injector/nomod?p0=myHe... at Error (native) at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:6:412 at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:25:235 at b (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:24:282) at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:25:20 at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:39:374 at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:7:355) at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:39:222) at db (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:43:246) at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:21:19 and also it is not able to include the js file...it says 404 not found though it is placed in the corresponding folder what can be the reason and how can i get over with it? -
Running a python commands from a python script in a python (Django) shell. Django
I'm working with Django and I'd created two database. Everything seems to work fine, but then I had to edit one of the two and add a column.. From that moment the db wouldn't work anymore, so I exported in a text file the first database and thinking "now I recreate the two db and run a python script to refill the first one". The problem is that whene I try to run the script I get errors, because I can't run the command like bash using os.system, and I don't really know any other way... So, here's my code: import os def func (): try: FILE=open ("./languagedb.txt", "r") except IOError: print 'Can\'t open db file' exit (1) for line in FILE: if (line.startswith('INSERT')): values=line[43:-1] language=values[1:3] values=values[6:] field="" fieldBool=True i=0 while fieldBool: try: c=values[i] except: print '' if c != '\'': field=field+str(c) i=i+1 else: fieldBool=False values=values [(i+3):] text="" textBool=True i=0 while textBool: try: c=values[i] except: print '' if c != '\'': text=text+str(c) i=i+1 else: textBool=False comand="Language.objects.create(language=\""+language+"\", text=\""+text+"\", campo=\""+field+"\")" os.system(comand) This is the way I call the shell: python manage.py shell and the commands I give it: import django from languageMods.models import * import mymigration #The name fo the file containing …