Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
prefetch_related in Django for database with multiple schemas
There is a Django project that uses a postgresql database with multiple schemas (global, public): CREATE USER corporate LOGIN PASSWORD 'secret'; GRANT postgresql TO corporate; ALTER ROLE corporate SET search_path TO global, public; and with the user corporate it contents to the database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'localhost', 'NAME': 'development', 'USER': 'corporate', 'PASSWORD': 'secret', } } There are also two models: Passenger (from global scheme) class Passenger(models.Model): name = models.CharField() email = models.CharField() and Restriction (from public scheme) class Restriction(models.Model): type = models.CharField() amount = models.IntegerField() passenger = models.ForeignKey( 'passengers.Passenger', blank=True, null=True, related_name='restrictions', ) In a list view I want to show a list of passengers with their restrictions class PassengersListView(ListView): model = Passenger context_object_name = 'passengers' def get_queryset(self): queryset = super(PassengersListView, self).get_queryset() return queryset.filter( company_id=self.request.user.company_id ).prefetch_related('restrictions') and use prefetch_related('restrictions') to get restrictions for all the passengers from the list. But when I render the list in a template {% for passenger in employees_list %} {% with restriction=passenger.restrictions.first %} <tr> <td>{{ passenger.get_full_name }}</td> <td>{{ restriction.amount }}</td> </tr> {% endwith %} {% endfor %} django-debug-toolbar shows that it makes one query to get passengers SELECT id, name, email FROM passengers then another query to get restrictions for … -
How to display unique_together error message to user
Most of the questions I have come across that have to do with unique_together had to do with overriding the message. I am uploading excel files and importing the data into the db. I want to display an error message to the user when the data being imported is a duplicate. I haven't been able to find a way to display that message on a template even though it shows on the console. models.py class UserData(models.Model): GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female'), ) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) age = models.IntegerField() gender = models.CharField(default='Male', choices=GENDER_CHOICES, max_length=6) address = models.CharField(max_length=200) class Meta: verbose_name_plural = 'User Data' unique_together = (('first_name', 'last_name', 'age', 'gender', 'address',),) def __str__(self): return self.fullname() def fullname(self): return self.first_name + self.last_name the view def save_to_db(request): if request.method == "POST": form = Importer(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] import_data.delay(file) file_name = request.FILES['file'].name new_log = Log(action='file_upload', message=file_name) new_log.save() return HttpResponseRedirect(reverse('app:list')) else: return HttpResponseBadRequest() else: form = Importer() return render_to_response('Exstore/upload_form.html', {'form': form}, context_instance=RequestContext(request)) PS: Customizing the error message is not a problem since there are answers like this -
Server-side implementation of instagram-like tags
I'm looking for some pythonic way to implement instagram-like tags functionality. Let's suppose my Tag Model is: class Tag(models.Model): slug = models.SlugField(max_length=120, unique=True) products = models.ManyToManyField(Product) def get_absolute_url(self): return reverse("tags:detail", kwargs={"slug": self.slug}) And Comment Model is: class Comment(models.Model): text = models.TextField(max_length=350) user = models.ForeignKey(settings.AUTH_USER_MODEL) product = models.ForeignKey(Product) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) What's the best way to implement addition of links inside CharField so that the message code of comment "Some sort of cool stackoverflow comment" would look like this: <p> Some sort of <a href="{% url "tags:detail" kwargs={"slug": "cool"} %}">#cool</a> <a href="{% url "tags:detail" kwargs={"slug": "stackoverflow"} %}">#stackoverflow</a> comment </p> -
I have a issue which is that I use TabularInline django 1.7 does not let me save
enter image description here enter image description here I hope you can help me , I have a problem which is that I use TabularInline django 1.7 does not let me save shows me everything perfectly to give to keep me throws an error this is problem that I utlizando another database other than the default and exepcion throws me that the table does not exist in the database -
Django: Autogenerate Click To Tweet link
So I have this form where I have a field where the user can input his tweet text and submit it. It will go into the DB but thats it. The thing though is that I want to have an additional button where it can generate the click to tweet link and an additional field where it will display the link that just created. In my helpers folder, I have in my __init__.py the following method that will autogenerate the link: def autogenerate_click_to_tweet_if_needed(production): """ # We check if the click to tweet associated with this production # needs to be auto-generated. We only do this if it is NULL or empty # so that if user entered it manually it prevales. :param production: """ if not production: return # 1. We check if the production meets the requirements for a click to tweet. # If it does not we delete all click to tweet associated with the production. # Criteria is to be Published. meets_criteria = production.status() == 'Published' if not meets_criteria: ClickToTweetProductionTweet.objects.filter(production=production).delete() return # 2. We get the first and only click to tweet for this production. click_to_tweet = ClickToTweetProductionTweet.objects.filter(production=production).first() # If we have a valid text in the … -
Django queryset "using()" method for specifying database doesn't work on related_name queries
I've noticed something strange in Django that I haven't been able figure out. Let's say I have a Django application (I'm using 1.7) with two models like so: class Bookstore(models.Model): name = models.CharField(max_length=50) class Book(models.Model): title = models.CharField(max_length=100) store = models.ForeignKey(Bookstore, on_delete=models.PROTECT, related_name='books') And then let's say I have two databases storing the data, perhaps a master-replica setup -- let's say the master is denoted as default in my settings file and the replica is replica. If I do the following query, I get an exception saying "the current database router prevents this relation": store = Bookstore.objects.using('default').get(id=1) first_book = store.books.using('replica').all().order_by('id')[0] However, the following, which should be the same query, works just fine: store = Bookstore.objects.using('default').get(id=1) first_book = Book.objects.using('replica').filter(store=store).order_by('id')[0] What's going on here? Is there anyway to use the related_name lookup like the first example but have it work properly? Thanks! -
How to setup email translation with Django Allauth
I am trying to setup translations for emails with django-allauth. I have rewritten my templates, translated my .po files and complied them. The html translations work fine but for some reason just the emails don't get translated. I have properly configured translations following the django tutorial https://docs.djangoproject.com/en/1.10/topics/i18n/translation/#how-django-discovers-language-preference The related question doesn't help: How does email translation work with django allauth? Package versions: Django==1.10 django-allauth==0.27.0 -
djangocms-installer SystemCheckError: System check identified some issues
I'm trying to install Django CMS using djangocms-installer==0.8.11. I'm using virtualenv, I've created a enviroment and I've installed the installer using pip install djangocms-installer. If I run djangocms -p /my/path my_cms, I have the next error after answer the questions: Database configuration (in URL format) [default sqlite://localhost/project.db]: django CMS version (choices: 2.4, 3.0, 3.1, 3.2, 3.3, stable, rc, develop) [default stable]: Django version (choices: 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, stable) [default stable]: Activate Django I18N / L10N setting; this is automatically activated if more than language is provided (choices: yes, no) [default yes]: Install and configure reversion support (choices: yes, no) [default yes]: Languages to enable. Option can be provided multiple times, or as a comma separated list. Only language codes supported by Django can be used here: es Optional default time zone [default America/Bogota]: Activate Django timezone support (choices: yes, no) [default yes]: Activate CMS permission management (choices: yes, no) [default yes]: Use Twitter Bootstrap Theme (choices: yes, no) [default no]: yes Use custom template set [default no]: Load a starting page with examples after installation (english language only). Choose "no" if you use a custom template set. (choices: yes, no) [default no]: Creating the project Please wait … -
how to store computed value of method on class
Hi i have a class which goes like this: class SendReport(object): def __init__(self, frequency = None, datalist = None): self.frequency = frequency self.datalist = [] def send_report(self): mailers = self.get_mailer() for mail in mailers: file_path = self.create_attachment(mail) self.send_email(mail, file_path) mail.last_run = datetime.now() mail.save() def create_attachment(self, mail): self.get_query_data(mail.id) @transaction.atomic def get_query_data(self, mailer_id): queries = self.get_queries(mailer_id) cursor = connections['rconn'].cursor() for q in queries: counts = cursor.execute(q) if counts > 0: data, columns = dictfetchall(cursor) self.datalist.append((columns, data)) return self.datalist get_query_data() is responsible for getting data from db. Now i am using this class from function like this: def sending_report(): frequencies = ['4', 'daily', 'weekly'] for frequency in frequencies: report = SendReport(frequency) report.send_report() this exposes one drawback of class, though the data is same for each frequency,we still continue to reevaluate it. this tempts me store the the data retrieved from get_query_data, and there is constraint that once this for loop of "frequency in frequencies" is over we delete the stored data, how can we achieve such a system, one idea is to create a singleton class, thus the data stored in self.datalist variable of class SendReport() can be reused. How can i optimize this code. -
How to pass PymagingImage object to context and render in django template
I am generating a QR code image from the text. I am able to generate the image but I am unable to display it on template. Here is the code. from django.shortcuts import render from django.conf import settings from django.http import HttpResponse import qrcode from qrcode.image.pure import PymagingImage def generate_qr_code(request): context = {} context["project_name"] = settings.MY_PROJECT_NAME if request.method == 'POST': try: data = request.POST["data"] context["data"] = data img = qrcode.make(data, image_factory=PymagingImage) #what to do here ? except Exception as e: context["errMsg"] = repr(e) return render(request, 'tools/qr_code.html',context) I looked for solutions provided on SO but they are explaining on how to return just an image with HttpResponse. As you can see I am using same template to submit the text and then display the result. And same view to process the GET and POST requests. I know there is a solution - by first saving image in some directory and then display in html. But this also didn't worked for me. Although it would be good if we can somehow pass via context. -
How do I use cgiscripts to run opencv python functions directly on a django webpage?
I've been looking for a way to directly execute python functions in and I came across cgiscripts but reading through it it only goes into detail about retrieving information from the python function. My first question is is it possible to use cgi scripts for a python function that uses opencv to play a video and process it in Django? If it can, what is the best way to do it so that I can display the video directly on a Django webpage? Thanks in advance. Couple of notes: I already know how to get the python function to execute via a button click so I have some knowledge of the process of calling a python function. -
django: is it possible to keep a model field updated with a model method?
So basically I have a model Equipment that has foreign key calibration. I would like to have a field in Equipment as 'latest_calibrated_date' which get the 'cal_date' from the newest created calibration. Here is what I have now: def latest_calibration_date(self): return Calibration.objects.filter(cal_asset__id = self.id).order_by('-id')[0].cal_date However, for the purpose of some other apps, I would like to make this not a method but a field. So I am thinking about use a latest_calibration_date = models.DateField() and update it every time a new Calibration is added. How could I do this? -
Ubuntu , Apache2 , Django ) Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings'
I'm trying to set up my django(1.8) application with AWS EC2 having Ubuntu 14.04 , Apache2 , python 3.4. When I run 'sudo service apache2 start' , the page keeps re-loading and the same error message is stacking at '/var/log/apache2/error.log'. The error message is [Fri Aug 26 2016] [mpm_event:notice] [pid n:tid m] AH00489: Apache/2.4.7 (Ubuntu) mod_wsgi/4.5.5 Python/3.4.3 configured -- resuming normal operations [Fri Aug 26 2016] [core:notice] [pid n:tid m] AH00094: Command line: '/usr/sbin/apache2' Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings' My configuration is below : I added one line: 'Include /etc/apache2/httpd.conf' at the bottom of '/etc/apache2/apache2.conf'. '/etc/apache2/httpd.conf' : WSGIScriptAlias / /home/ubuntu/project/project/project/wsgi.py WSGIDaemonProcess project python-path=/home/ubuntu/project/project WSGIProcessGroup project WSGIPythonHome /usr/bin/python3.4 <Directory /home/ubuntu/project/project/project> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /home/ubuntu/project/project/deploy_to_server/ <Directory /home/ubuntu/project/project/deploy_to_server> Require all granted </Directory> I think I did it all done without something wrong. But it keeps logging with the same error. Is there anything I'm missing? I did change mod_wsgi/3.x Python/2.7 configured --> mod_wsgi/4.5.5 Python/3.4.3 configured for synchronizing the python version ALREADY -
Migrations on Through Model Django Many to Manyo Field
I have a model used in a ManyToManyField that I want to change. User Teacher - ManytoManyField through TeacherRelation TeacherRelation NewModel I want to change the foreign key of the TeacherRelation so it uses NewModel instead of Teacher . I already have data That I dont want to loose on the db, so I would like to know what's the best way to make this kind of migrations. Im concerned about issues like: - Will I have to delete the previous entries on the db that used the other foreign key? - Is there a way to find all the previous entries and replace them with the correct new primary key? I think I'll have to write a script for that... But where and when should I place it and run it? Thanks for the help. -
foreign keys for specific primary key django forms
I have class Company, Driver and Car class Company(models.Model): title = models.CharField(max_length=256) ... Class Car(models.Model): ... company = ForeignKey('Company') class Driver(models.Model): ... company = ForeignKey('Company') company_car = OneToOneField('Car') Also I have GenericView for Create and Update driver, and generic form. I need form where when user select the company, company_car dropdown consist only Foreign Keys car objects for this company. I know about object_set feature and that`s trick possible with AJAX. But I have no idea how it realize -
Use CharField as a string
I want to create a model where I just put in two fields and the rest is generated with API requests, the generation I've got but I can't get the CharField in a usable string format. So on field is: name = models.CharField(max_length=250, default='default') And I want to run it through: name = self.name.replace(' ', '+') movieData = (json.loads(str(urllib2.urlopen('http://www.omdbapi.com/?t=' + name + '&y=&plot=short&r=json').read(),'utf-8'))) movieYear = movieData.get('Year') Saving movieYear as a field. Thanks in advanced. -
DRF JSON-API - Error when using include option for Compound Objects
I'm trying to use the include option of Django REST Framework JSON API, to sideload related objects in my serializer, as described in this example. The only difference to the example is that i'm using SerializerMethodResourceRelatedField, instead of ResourceRelatedField. But i'm getting the error 'QuerySet' object has no attribute 'aluno' These are my serializers (I took out some other fields to make it more readable): class AlunoSerializer(serializers.ModelSerializer): cadernos_pendentes = SerializerMethodResourceRelatedField(source='get_cadernos_pendentes', model=Caderno, many=True, read_only=True) included_serializers = { 'cadernos_pendentes': CadernoSerializer, } class Meta: model = Aluno fields = ('id', 'cadernos_pendentes') def get_cadernos_pendentes(self, obj): return obj.cadernos_pendentes class CadernoSerializer(serializers.ModelSerializer): class Meta: model = Caderno fields = ('id', 'aluno') And my models (also simplified): class Caderno(models.Model): aluno = models.ForeignKey('Aluno', related_name='cadernos') data_realizado = models.DateField(null=True) class Aluno(models.Model): nome = models.CharField(max_length=256) @property def cadernos_pendentes(self): return self.cadernos.filter(data_realizado=None).order_by('id')[:5] The problem only occurs when the client sends the 'include' param in the query. I tried using ResourceRelatedField, instead of SerializerMethodResourceRelatedField, but it seems to have problems working with properties on the model. It gives me the error 'property' object has no attribute 'parent' So I don't know what to do to make it work. Any help is appreciated. I can also give you the tracebacks, if needed, didn't do it already … -
django unit test for ModelChoiceField form with CheckboxSelectMultiple widget
I have a form class TypesForm(forms.Form): .... types = forms.ModelChoiceField( label='Types', queryset=models.Type.objects.all(), widget=forms.CheckboxSelectMultiple) ... How do I write a unit test for this form, when I want to test multiple boxes selected? For one field check works following: form = forms.TypesForm({'types': 1}) self.assertTrue(form.is_valid()) But anything I tried to set two selected checkboxes, it results in errors: {'types': [u'Select a valid choice. That choice is not one of the available choices.']} I tried, but these does not work. E.g. : form = forms.TypesForm({'types': [1, 2]}) form = forms.TypesForm({'types': (1, 2)}) and other options.. For forms.ModelForm the list [1, 2] works, so there needs to be a way. -
celery with redis - how many connection does it open?
I am new to celery/redis, tried a basic setup with django + redis. I've created a simple function which write to file with @shared_task, it works. What I don't understand, why in the redis console, even after the task is performed - I still see 14 clients connected. Does celery not close its connections? Can that be a problem if there will be too many connections to redis? I'm afraid cause I need to put that in production environment and I haven't test that enough -
ImproperlyConfigured at **The included urlconf ****does not appear to have any patterns in it
I am working on a django project and facing an issue. The name of my main project is testproject. In settings.py I have : ROOT_URLCONF = 'testproject.urls' There are two apps in the project too. One is example, other is new. This is the urls.py of example: from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from example import views urlpatterns = [ url('example/$', views.Example.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) This is the urls.py of new: from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from new import views urlpatterns = [ url('new/$', views.New.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) On hitting url "127.0.0.1:8000/example" I am getting the error: ImproperlyConfigured at /example/ The included urlconf '<module 'name.urls' from '/Users/testproject/name/urls.pyc'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. But I don't see any circular imports here. I'm stuck. Please help me. -
AWS ElasticBeanstalk update without modifing Django wsgi.conf
I have a django app deployed in AWS EB using autoscaling. This app uses Django Rest with Token Authentication. In order for this to work, I have to add the following lines in etc/httpd/conf.d/wsgi.conf file: RewriteEngine on RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] WSGIPassAuthorization On The problem is: when AWS do an autoscale or ElasticBeanstalk environment upgrade, the wsgi.conf file is updated and the custom settings are deleted. How can I avoid that? Thanks in advance -
Python encode an image in base 64 after a html upload
I have an input for images upload in my page. When you click on "send image" the post request is received in my back-end. I don't, and I don't want to, save the image. What I do, from the back, is: I send the image to an API which will return me the image's tags and then I will display the tags and the image itself, that has been uploaded, in my html page. if request.method == "POST": form = ImageForm(request.POST, request.FILES) if form.is_valid(): imageUploaded = request.FILES['image_file'] try: c = Client(cId, sId) c.get_token() tags = c.image_lookup(imageUploaded) urlImage = base64.b64encode(imageUploaded.read()) context.update({ 'image_path': urlImage, 'tags': tags.json, 'btn_visible': True, }) except ValueError as e: logging.info(e) context.update({ 'btn_visible': False, 'error_message': 'A problem occured, we will fix it as soon as possible. We apologise for the inconvenience.' }) in my HTML: <img id="cv-image" src="data:image/png;base64,{{ image_path }}"> But, my problem is that my image_path stay desperately empty. What's the problem? -
Can't publish pages in Django-cms
I've got a Django/Django-cms(v3) and when I try to publish my pages I'm getting this error: ValueError at /pt/admin/cms/page/10/pt/publish/ The database backend does not accept 0 as a value for AutoField. Request Method: POST Request URL: http://54.194.60.230/pt/admin/cms/page/10/pt/publish/ Django Version: 1.9.9 Python Executable: /usr/bin/python Python Version: 2.7.9 Python Path: ['/', '/usr/local/bin', '/home/project', '/', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Sex, 26 Ago 2016 10:36:06 +0000 Installed Applications: ('djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.session (...) Seems like is trying to add a 0 in a AutoField type of column but I can't find where this is happening and why. Do you ever had a similar problem? Thank you :) -
how to include JSON in POST request
Good day, I am trying to write a unit test using a mock HTTP client. My web endpoint code (that I am trying to test) looks similar to this: from django.views.decorators.csrf import csrf_exempt from wifast.smbsite.views.api.v0.utils import json_request @csrf_exempt @json_request() def new_customer(request): print 'debug printing request:' from pprint import pprint pprint(vars(request)) data = request.json # request should have a json object associated... business_id = data['business_id'] # ..which should contain these email = data['email'] source = 'webform' Here is the test code that creates the mock request: from django.conf import settings from django.test import Client, TestCase class MockWidgetClient(Client): DEFAULT_USERAGENT = ( 'Mozilla/5.0 (Windows NT 6.2; WOW64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/30.0.1599.17 Safari/537.36' ) def __init__(self, *args, **kwargs): """Set the router associated with the portal.""" if 'HTTP_USER_AGENT' not in kwargs: kwargs['HTTP_USER_AGENT'] = self.DEFAULT_USERAGENT super(MockWidgetClient, self).__init__(*args, **kwargs) def post(self, endpoint, email, business_id): obj = { "business_id" : '{}'.format(business_id), "email" : '{}'.format(email), "name" : 'James Bond', "city" : 'Toronto', "state" : 'Ontario', "country" : 'Canada', } req = { "key" : "value" } result = super(MockWidgetClient, self).post(endpoint, data=req, json=obj) return result class TestWidget(TestCase): def test_widget_customer(self): mock_client = MockWidgetClient() response = mock_client.post('/api/webform/','Fake@gmail.com','1234') As you can see this is a mock client that attempts to … -
Django imagekit resize without cropping
I am using django-imagekit. Right now I have this model: class Photo(models.Model): user = models.ForeignKey(User) image_original = models.ImageField(upload_to=get_upload_file_name, blank=True) image_470 = ImageSpecField(source='image_original', processors=[Resize(470, 470)], format='JPEG', options={'quality': 60}) This is working. But the problem is that the images are being cropped (470x470). However, what I need is to set the maximum height to be 470, or else maximum width to be 470. How can I get this behavior without cropping the image? Thank you.