Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to get Count('foo__bar') inside annotate()
Im trying to get the following line works: artists = models.Artists.objects.all().annotate(tot_votes=Count('votes__work')).order_by('-tot_votes') (i.e. I want simply to annotate the count of all votes corresponding to every artist.) But whenever the above line is executed I get the FieldError error Cannot resolve keyword 'votes' into field. Where class Votes(models.Model): work = models.OneToOneField(Works, models.DO_NOTHING, db_column='work') user = models.OneToOneField(AuthUser, models.DO_NOTHING, db_column='user') and class Works(models.Model): artist = models.ForeignKey(Artists, models.DO_NOTHING, db_column='artist') # other irrelevant fields OR simply the relation between the tables is (Votes --> Works --> Artists) -
Python: datetime.today().date() crashes in Django but runs in terminal
I have the following code in a Django app that keeps crashing: from datetime import * date_today = datetime.today().date() If I run the exact same code in the terminal, everything works and it prints datetime.date(2016, 11, 10) The error I get when the code is run i Django: AttributeError: 'module' object has no attribute 'today' Question: What can I do to make the code run in Django? -
How to process large files via Django in logs visualizer web-app
I want to create a website with Django framework and Python 2.7 to allow users to process their logs files (size might be big ~3Gb) output by machine stored on users computer. Logs contains some variables like speed or temperature and each log has date. It would allow user to create filters to extract specific values from logs and modify existing ones and then it will allow to create interactive charts of retrived values using plotly library. As I have no prior experience in creating this kind of applications and in Django general (just one or two small tutorial projects) I wonder how to create effectively the part concerning uploading files and preprocessing them. I already have a desktop application written in Python 2.7 with Tkinter and matplotlib but it suppose to be used by many people and web-application seems to be a better option as it allows to create more intuitive interface and it will ease the access to this functionality. I tried to find some similar questions on stack and other forums but I couldn't found anything helpful. Could you please advice me on how to solve the problem of uploading logs files to the website and process … -
Add default filter to django admin
I've got a model with boolean fields visible and hidden in using the admin.py I think it's possible to add a default filter to filter by visible=True and hidden=True class ArticleAdmin(admin.ModelAdmin): ... def changelist_view(self, request, extra_context=None): if not request.GET: #No filter #Perform filter to queryset for visible and hidden = True return super(ArticleAdmin,self).changelist_view(request, extra_context=extra_context) -
Do not internationalize/translate URLs
Problem I'm currently trying to upgrade to Django 1.10.3 from Django 1.9.8. Currently my tests are failing however, because for some reason Django is trying to translate/internationalize my URLs when I reverse() them. I've not changed anything when it comes to internationalization and would very much like to turn this "feature" off. Not only is it failing a lot of tests, but there are also some projects which have to refer to the URLs of this website statically. This means the URL on this website are not allowed to change (or I would have to edit them for every translation Django comes up with, which would be a real pain). Error The actual error I'm encountering in my tests is the following: Traceback (most recent call last): File "/tests/unit/views/test_index.py", line 14, in setUp self.url = reverse('indexpage') File "/local/lib/python2.7/site-packages/django/urls/base.py", line 91, in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 346, in _reverse_with_prefix possibilities = self.reverse_dict.getlist(lookup_view) File "/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 243, in reverse_dict return self._reverse_dict[language_code] KeyError: 'nl-nl' It's obvious Django is trying to do something with the language code provided in the settings for this project. Question How can I turn off URL internalization/translation in Django. Or what would be a … -
Django show product detail in POPUP using ajax,jquery
I am new learn in django-ajax . i donot no how to use popup ajax in django view.I create two html files list.html and detail.html.my question is when i open list.html whenever i click on any product to show the product details using popup format using ajax.so please tell what are the changes required in view,jquery,html and ajax .thank in advance. view.py def show_product(request, product_slug, template_name="catalog/product.html"): p = get_object_or_404(Product, slug=product_slug) categories = p.categories.filter(is_active=True) page_title = p.name meta_keywords = p.meta_keywords meta_description = p.meta_description return render_to_response(template_name, locals(),context) def list_product(request): queryset_list = Product.objects.all() #.order_by("-timestamp") paginator = Paginator(queryset_list, 1) # Show 25 contacts per page page_request_var = "page" page = request.GET.get(page_request_var) try: queryset = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. queryset = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. queryset = paginator.page(paginator.num_pages) context = { "object_list": queryset, "name": "List", "page_request_var": page_request_var } return render(request, "catalog/list.html", context) list.html {% extends "base.html" %} {% block content %} <div class="signup"> <div class='col-sm-6 col-sm-offset-3'> <center><h1>{{ name }}</h1></center> {% for obj in object_list %} <div class="caption"> <h3>{{ obj.name }}</h3> <p>{{ obj.content|linebreaks|truncatechars:120 }}</p> <p><a href="{{ obj.get_absolute_url }}" class="btn btn-primary" role="button">View</a></p> </div> <hr/> {% … -
django customepage 404 why does it return '404 ok' response
I've to render a custom 404 template with django. I decided to start on the basic of it: def custom_page_not_found(request): response = render_to_response('404.html', {}, context_instance=RequestContext(request)) response.status_code = 404 return response And I'm pretty curious to know why I can't have a "404 not found". If I don't use the handler404 from urls.py, I will have the blank 404 page with the current status. But not when I want to have a custom template. Does anyone know why? (django 1.7.11) -
Tools used to develop web based management system
Quite a big decision ahead of me and I feel like I don't have much experience so wanna ask around! I have been given a task to develop a platform - basically a management system with roughly following spec (main tasks) Geolocation tagging - heavy use of google maps, communicating with gps, displaying things on the map, calculating distances etc. Some dashboard functionality - numbers updated in real time, maybe a chart or two Ease of generating well structured reports (that's backend though so would imagine would be the same for most frameworks/tools) Very very very user-friendly design I would say that there are no concerns regarding scalability in at least near year so planning host it on either EC2 or Google App engine. My initial idea was to have back-end in GOLang but I feel like that's a long term highly scalable solution where now I need more of a proof of concept so am currently leading towards NodeJS. (I have 0 experience in GOLang, some in Django and loads in Node) I am really really unsure about front end though. I have most experience with Angular but I feel like that's really not a place to implement angular … -
Accessing a model's class attributes in Django migrations
If I have a model like: class Book(models.Model): FORMAT_CHOICE = 1 # ... And then I want to access FORMAT_CHOICE in a migration, what's the best way to do it? If I do this: from __future__ import unicode_literals from django.db import migrations def set_format(apps, schema_editor): Book = apps.get_model('myapp', 'Book') format = Book.FORMAT_CHOICE # ... class Migration(migrations.Migration): dependencies = [ ('myapp', '0026_auto_20161109_1455'), ] operations = [ migrations.RunPython(set_format, reverse_code=migrations.RunPython.noop), ] Then I get an error like: AttributeError: type object 'Book' has no attribute 'FORMAT_CHOICE' I don't understand why this is... my basic python knowledge isn't that strong. I did print(Book) and its representation was <class '__fake__.Book'> so there's something odd about this version of it. I could do from myapp.models import Book instead of using apps.get_model(), but that seems fragile in a migration - is there a way to access FORMAT_CHOICE without doing that? -
Django 1.10 add media url to static image file
After update to Django 1.10 I have a problem with static file images. Now Django add to static file path "media" link... For example before it was "/static/images/avatar.jpeg" now "/media/static/images/avatar.jpeg" Admin Settings STATIC_URL = '/static/' STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(BASE_DIR, 'static'), 'static', ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' -
single database connection throughout the python/django application (following singleton pattern)
The driver to my Database is not supported by the Django ORM. And due to same driver related issues, I am using pyodbc to connect to the database. Right now I am having below class for creating and managing the DB connections: class DBConnection(object): def __init__(self, driver, serve, database, user, password): self.driver = driver self.server = server self.database = database self.user = user self.password = password def __enter__(self): self.dbconn = pyodbc.connect("DRIVER={};".format(self.driver) +\ "SERVER={};".format(self.server) +\ "DATABASE={};".format(self.database) +\ "UID={};".format(self.user) +\ "PWD={};".format(self.password) + \ "CHARSET=UTF8", # "", ansi=True) return self.dbconn def __exit__(self, exc_type, exc_val, exc_tb): self.dbconn.close() But the issue with this approach is that it will create new database connection for each query. What will be the better way to do it following singleton pattern? The way I can think of will hold the reference to the connection if the connection is closed. Something like: def get_database_connection(): conn = DBConnection.connection if not conn: conn = DBConnection.connection = DBConnection.create_connection() return conn What will be the best way to achieve this? Conditions that are needed to be taken care of: In case of multiple requests, I should be using the same connection In case connection is closed, create a new connection If the connection has … -
Django - Dynamic ModelMultipleChoiceField when dropdown changed
I have Django application installed. model.py class Connector(models.Model): connector_id = models.AutoField(primary_key = True) name = models.CharField(max_length=255, null=False,unique=True) class ConnectorMethod(models.Model): id = models.AutoField(primary_key = True) connector = models.ForeignKey('Connector') method = models.ForeignKey('Method') class Instrument(models.Model): instrument_id = models.AutoField(primary_key = True) name = models.CharField(max_length=255, null=False,unique=True) connector = models.ForeignKey('Connector') forms.py In Instrument Admin form, I have a custom field, method = forms.ModelMultipleChoiceField(queryset=Method.objects.all(),widget=forms.CheckboxSelectMultiple) Whenever i changed Connector dropdown field, I want the method dynamically changed based on the mapping in ConnectorMethod. I have been searching for days, there are some solution but there is always with customize html form. I am using default Django admin form. What is the best way to do this? Appreciate your help! -
Slugify name field in django form
I have model which has Meta: unique_together = ['slug', 'person'], person is foreign key field. In my form I don't want to type slug field. I want to populate it from child_name field. I tried as: class ChildForm(SlugCleanMixin, forms.ModelForm): class Meta: model = Child fields = ('child_name','slug','child_birth_date','blood_group') def slug(self): return slugify(self.child_name) But slug field not autopopulated from child_name. I also tried using pre_save in models as: def create_slug(instance, new_slug=None): slug = slugify(instance.child_name) if new_slug is not None: slug = new_slug qs = Child.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, sender=Child) But nothing fulfill my purpose. How could I do that? Any help will be appreciated. -
How to execute a long process in WEB application?
I have a WEB app (Django/Python/JS) that creates a process which takes 20 minutes. This process can't be done faster. Obviously, it is not good to keep a user waiting for 20 minutes on the same WEB page. What is the better way to run this 20 min long process? Do I need a forever running daemon or maybe a cron job or something else? -
How to use a different database for Heroku review apps?
I have a deployment pipeline on Heroku which recently started using review apps. This means I have an app - let's call it CI-APP -- which is being created from the master branch. Every time a pull request is made, a review app is created. We are using Django in our project and so I also added the migrate command to the release phase in the project, so that database migrations can be done automatically. Today, a coworker submitted a pull request which contained some database changes. The problem is that the migration was ran, and since review apps seem to be using the same database as the app they are suppose to merge to, the migration was applied and now my app CI-APP stopped working...since the code base no longer matches the database structure. I searched a lot about how to use completely different databases for the review apps compared to the parent app, but to no avail (there are some resources mentioning how you can copy db contents, but that is not what I need). Any suggestion ? -
having trouble with mysql migration (can't multiply sequence by non-int of type 'tuple')
I am havnig troulble about migrating..I first tried python manage.py migrate qablog and did work. so I tried python manage.py migrate qablog --fake-initial and didn't work.. so I googled again and some people were talking about changing the settings.py so I changed some things like changing USE_TZ to false .. python manage.py makemigrations qablog worked well though...can anyone help me with this? .. python version: 3.4.4 mysql server version: 5.7 django version: 1.10.3 The error log is like below: C:\inetpub\wwwroot\test>python manage.py migrate qablog --fake-initial Operations to perform: Apply all migrations: qablog Running migrations: Applying contenttypes.0001_initial... FAKED Applying auth.0001_initial... OK Applying qablog.0001_initial... OK Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Python34\lib\site-packages\django\core\management\commands\migrate.py ", line 224, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "C:\Python34\lib\site-packages\django\core\management\sql.py", line 53, i n emit_post_migrate_signal **kwargs File "C:\Python34\lib\site-packages\django\dispatch\dispatcher.py", line 191, in send response = receiver(signal=self, sender=sender, **named) File "C:\Python34\lib\site-packages\django\contrib\auth\management\__init__.py ", line 83, in create_permissions Permission.objects.using(using).bulk_create(perms) File "C:\Python34\lib\site-packages\django\db\models\query.py", line 452, in b ulk_create ids = self._batched_insert(objs_without_pk, fields, batch_size) File "C:\Python34\lib\site-packages\django\db\models\query.py", line … -
Django 1.9 - created new app run migrate, tables are not created
ive added a new app and created some models. I have run makemigrations and migrate and all went successfully. However when i open the sqlite table, none of the tables are created. sample from models: from __future__ import unicode_literals from django.db import models from django.conf import settings import string import random import time import os # Create your models here. from service.models import ServiceContacts class Subnets(models.Model): subnet = models.GenericIPAddressField(protocol='IPv4',verbose_name="Subnet",blank=True,null=True) subnet_mask = models.CharField(max_length=4,verbose_name="Subnet Mask",choices=settings.SUBNET_MASK_CHOICES,blank=True) subnet_type = models.CharField(max_length=10 ,verbose_name='Subnet Type',choices=settings.SUBNET_TYPE_CHOICES,blank=True) class Meta: verbose_name = "Site Subnet Data" verbose_name_plural = "Site Subnet Data" class SiteContacts(models.Model): name = models.CharField(max_length=200) title = models.CharField(max_length=200) mobile = models.CharField(max_length=200,blank=True, null=True) ddi = models.CharField(max_length=200,blank=True, null=True) notes = models.TextField(blank=True, null=True) class Meta: verbose_name = "Site Contact Data" verbose_name_plural = "Site Contact Data" sample from inital # -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-11-09 17:32 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import sites.models class Migration(migrations.Migration): initial = True dependencies = [ ('service', '0007_auto_20160701_0931'), ] operations = [ migrations.CreateModel( name='CircuitFiles', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('circuit_file', models.FileField(blank=True, upload_to=sites.models.service_upload_path)), ('file_name', models.CharField(max_length=200, verbose_name='File Name')), ], options={ 'verbose_name': 'Circuit Files', 'verbose_name_plural': 'Circuit Files', }, ), migrations.CreateModel( name='CircuitNotes', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateField()), … -
How to clean multiple file field in django forms?
forms.py class FileForm(forms.Form): file_field = forms.FileField(label='Upload Files',widget=forms.ClearableFileInput(attrs={ 'multiple': True, 'placeholder':'Upload multiple forms', }) ) desc=forms.CharField(label='Description',widget=forms.Textarea(attrs={ 'placeholder':'Enter simple description', 'required':'False', })) def clean_file_field(self): ''' Implement this. :return: ''' Now I want to implement a clean method in the forms. How to get files in a list that will be uploaded in this clean_file_field ? I can get them in views like this request.FILES.getlist('file') But how to get them in views? -
how to check for a value if it exists in a different database table
I have a scenario where I should display an image when a value of one field of a table is present in another table. I'm not sure how this condition can be done. Can anybody help? In html or even in angularjs. For better understanding, my code in html and what I'm trying to do, html: {% if {{vio.pdb_pid}} } {% if is_secure_device == 'true'%} {% verbatim %} <img class="img-rounded" ng-src="{{vio.pdb_pattern_img}}"> {% endverbatim %} My first line in the code.i.e. the if statement is incomplete. the value {{vio.pdb_pid}} should be checked on a table called sivorcdds(the field name in this table is pdb). Precisely, if {{vio.pdb_pid}} exists in pdb.sivorcdds(fieldname.tablename) I should display an image as like in my code. I don't know how to do this. I'm new to coding. Any help would be appreciated. -
Download file from FileField in Django with a html link
I try to create a link that when a user press it, it will download a pdf file from the media folder in django. My FileField is like this: upload_pdf = models.FileField() I try some different methods but all has errors for me, some times it tell me that the file can not be found, or the code is working but the file is corrupted. Below is the view that downloads a corrupt pdf: def DownloadPdf(request): filename = '/home/USER/PycharmProjects/MyProject/media/Invoice_Template.pdf' response = HttpResponse(content_type='application/pdf') fileformat = "pdf" response['Content-Disposition'] = 'attachment; filename=thisismypdf'.format(fileformat) return response So, what i have to do to make it work ? -
Django model field -- populate_from Option for CharField
Just wan't to ask if it is possible to use populate_from Option in a CharField field to prepopulate the field from other fields, just like the example of slug field. class Post(models.Model): ***name***= models.CharField(max_length=50) slug = extension_fields.AutoSlugField(populate_from='***name***', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) Let say, class Employee(models.Model): eid= models.CharField(primary_key = True) lastname = models.CharField(max_length=50) firstname = models.CharField(max_length=50) middlename = models.CharField(max_length=50, null=True) Now I wan't to add a new CharField fullname. I wan't the fullname to be populated from lastname, firstname and middlename fields. fullname = models.CharField(populate_from = "***i don't know what to do here***") Please help... -
SHOP_CURRENCY_LOCALE = 'en_US.UTF-8'
I am trying to include the line SHOP_CURRENCY_LOCALE = 'en_US.UTF-8' inside my settings.py file but it's giving me the following error:- raise ImproperlyConfigured(msg % currency_locale) django.core.exceptions.ImproperlyConfigured: Invalid currency locale specified f or SHOP_CURRENCY_LOCALE: 'en_US.UTF-8'. You'll need to set the locale for your s ystem, or configure the SHOP_CURRENCY_LOCALE setting in your settings module. -
Why gcloud app deploy not uploading project files?
I'm using Google App Engine to host my Django app. I'm using gcloud app deploy command. But it is uploading only aap.yaml file but not rest of the files. What is correct way to deploy? -
sorl-thumbnail not save cache
I used the sorl-thumbnail. When viewed from the modern template, only the path safsafsdais displayed and the thumbnail image is not saved. my wewrwerwerwerweeeeeeeeeeeeeeeeweewrwerwerwe setting asdfsafsadfa -
How to implement sessions in django?
i want to implement login and logout session in my website through which after a set of time the session should expire automatically. And if user logged in then the user could not go back.