Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I delete DB (sqlite3) in Django 1.9 to start from scratch?
I made a spelling error in my model and now one of my columns is misspelled. I'd like to drop all tables in the database, fix the error in the model.py, and recreate the database with the correct spelling in model. I've tried to use the suggestions in the this article but the table still exists after I follow the commands outlined there. Anyone have a quick way to do this? -
Django dev server won't serve media
I'm working on a Django POC that will display and play MP4 videos that I have in a directory on my local machine (eventually a production server). The page currently displays the video controller for each video, but the videos aren't loaded and won't play. The video source that is attempted is: http://127.0.0.1:8000/media/mp4FileName.mp4 settings.py MEDIA_ROOT = '/Users/myUser/Documents/temp/mp4/' MEDIA_URL = '/media/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] main urls.py: from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^dash/', include('dash.urls')), url(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py target_directory = "/Users/myUser/Documents/temp/mp4/" def get_file_list(directory, file_type): # TODO: docstring return [f for f in os.listdir(directory) if f.endswith(file_type)] def index(request): video_file_list = get_file_list(target_directory, ".mp4") template = loader.get_template('dash/index.html') context = { 'video_file_list': video_file_list, } return HttpResponse(template.render(context, request)) index.html: {% load static %} {% if video_file_list %} {% for file in video_file_list %} <div class=""> <br> <video controls> <source src="{{ MEDIA_URL }}{{ file }}" type="video/mp4"> </video> <br> </div> {% endfor %} {% else %} <p>No videos are available.</p> {% endif %} Thanks in advance! -
Django - collectstatic 'ImproperlyConfigured' traceback when deploying to Heroku
I'm learning to use Django and am trying to deploy a project on Heroku. When I try to deploy the project through the command window I get the following traceback when it runs python manage.py collectstatic Improperly Configured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. My settings for heroku are: if os.getcwd() == '/app': import dj_database_url DATABASES = { 'default': dj_database_url.config(default='postgres://localhost') } SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = [*] # Static set configuration BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'staticfiles' STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'), ) I'm new to django and I'd appreciate any help, thanks. -
How to use Django template tags in angular template
I'm using Django 1.9.8 and angular 1.5.8. I have a Django template named song.html that has an angular component, which uses its own template. When I try to use any Django template tags like {% csrf_token %} inside my angular component's template (named my-component.template.html) it is not rendered and the exact markup tag is displayed. <!-- song.html --> {% block content %} <head> .... </head> <html ng-app="myApp"> <!-- some html.... --> <my-component></my-component> </html> {% endblock %} Here is the template for my-component <!-- my-component.template.html --> <div id = "my_div"> <!-- some html --> </div> <form action = "" method = "post> {% csrf_token %} <!-- ....remaining form contents --> </form> Django is not creating the hidden form input and the exact {% csrf_token %} tag appears on my form. However, when I move the form from the angular template to the Django template, the csrf_token properly generates. So basically Django will create the csrf hidden input on the Django template, but not the angular template. How can I use Django markup inside of my angular template? I apologize if this has been asked, but I'm not quite sure how to word it. I have created a workaround by setting a … -
Mysql error when run Python Django migrate using eclipse
I just finished to make new project and create superuser. When I coded models.py and run migrate using eclipse, it throws error message and there is nothing in my Django admin. Here is the error message. System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.10/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. Finished "C:\Users\ds\workspace\board\manage.py migrate" execution. This is my models.py from __future__ import unicode_literals from django.db import models from unittest.util import _MAX_LENGTH from pip.cmdoptions import editable from django.template.defaultfilters import default from datetime import datetime # Create your models here. class User(models.Model): id = models.CharField(_MAX_LENGTH=10) password = models.CharField(_MAX_LENGTH=10) join_date = models.DateTimeField(editable=False, default=datetime.now()) class todo(models.Model): user = models.ForeignKey('id') title = models.TextField content = models.TextField date = models.DateField(editable=False, default=datetime.now()) -
Heroku “Error R14 (Memory quota exceeded)” via Django AJAX Request
So, I know there were previous questions asked about this, but I think my situation may be a bit different since I am using Django filters on a large data set. I have a table with about 35,000 rows worth of products, and the issue is that when my site makes an AJAX call using an infinite scroll layout, the request usually returns a 503 error (sometimes it works after a long time). Any ideas how to optimize my code? Or do I need to upgrade my Heroku configurations? My configuration: Python 3.5.0 Django 1.10.5 Heroku PostgreSQL 9.6.1 ($9 Hobby plan) Heroku ($7 Hobby Basic plan) Waitress (server) 1.0.2 views.py class InfiniteResultsView(LoginRequiredMixin, View): def get(self, request): search_filters['status'] = Product.ACTIVE if search_terms: search_filters['title__icontains'] = search_terms if search_categories_slugs: for s in search_categories_slugs: q_objects |= Q(category__slug=s) products = Product.objects.filter(q_objects, **search_filters).select_related() products = paginate(queryset=products, page=page, amount=6, force_cutoff=True, force_shuffle=True) return render(request, '_includes/_products.html', {'products': products}) Heroku LOG 2017-02-09T06:44:43.277422+00:00 heroku[web.1]: Process running mem=648M(126.5%) 2017-02-09T06:44:43.277526+00:00 heroku[web.1]: Error R14 (Memory quota exceeded) -
Compare Django TimeField into timezone aware datetime; compare naive time with timezone.now()
I am using time zone aware objects throughout my app, except where I have a TimeField to represent a generic, daily time of day: start_time = models.TimeField() However, at certain points, I need to compare the current time: timezone.now() to the start_time, using the server's timezone, to see if the time has past on any given day. How can I convert start_time to a timezone aware datetime object that can be compared to timezone.now() ? I am using USE_TZ = True -
Django: adding two serializers together?
How is it possible to add a serializer within another serializer? Here's what I mean: I have a UserProfile model as such: class UserProfile(models.Model): user = models.OneToOneField(User) photo = models.URLField(max_length=128) I have posts which are from the user: class Posts(models.Model): # ... post fields I want to serialize my UserProfile with the user and photo, as well as the posts from that user. Here's the result I'm aiming for: { "user": <User fields serialized>, "photo": "www.example.com/path/to/file", "posts": "[{"from_user": "me", "message": "post message} , {"from_user": "me", "message": "post message2"}, ... etc]," } In my views.py I first gather the posts which come from that User: user = User.objects.get(pk=1) user_profile = UserProfile.objects.get(user=user) user_profile_serializer = UserProfileSerializer(user_profile) posts = Posts.objects.get_posts_from_user(user) post_serializer = PostsSerializer(posts, many=True) # somehow append my post_serializer into my user_profile_serializer? Here is my PostsSerializer.py: class PostsSerializer(serializers.ModelSerializer): class Meta: model = Posts fields = ('__all__') Here is my UserSerializer.py: class PostsSerializer(serializers.ModelSerializer): # somehow filter the results depending on User posts_serializer = PostsSerializer(many=True) class Meta: model = Posts fields = ('__all__') I've tried serializing the user profile, and because I added a serializer variable inside my UserProfileSerializer, I assumed it would add the field of posts automatically. It just shows the User Profiler serialized, … -
Python - Using the django that is installed in the virtualenv
I've installed Django 1.8 in the virtualenv and I'm trying to use the static files from it. For Example, if I want to edit the header color of the admin base.html, It keeps using the django global file (1.7) even though I'm working with my virtualenv on. Doesn't my STATIC_URL = '/static/' use the django that is currently running in my virtualenv? Sorry for the bad English -
Using Django to make a stateful connection
I'm trying to use Django in the following way. I have a command line utility that runs on the backend, lets call it foo. I want foo to run when at least one person is on a django page foo.com/kungfoo. I also need to kill the script, when they leave the web page. Which is possible through Javascript. However, how do I determine if multiple people are viewing the page at the same time. Ideally, I don't want foo to be killed if another person is on the page. The only way I can think of to do this is to have Javascript push an I'm still here status to Django every minute or so. Then run a Python script through celery every minute, and check if Django has got an I'm still here. If foo is running, then kill foo. Is there a better way to do this? I know this question is broad, so I'll make it a little more specific. Is there a way for Django to count the number of people viewing a web page and run a script if that number is 0. -
Django ID based dynamic URL with base64
I'm working on a django application that takes an ID based dynamic URL, but rather than having the URL be straight up the ID, as it is right now: url(r'^history/(?P[0-9]+)/$', views.history) I would like the URL to be the base64 encoded version of the object's ID, and i couldn't find a lot about encoding Django URLs. -
django-filter different models in 1 view
I am currently working in a database application in django. I want to add a advanced filter functionality to a page using django-filter, but I found an issue in my approach and I hope you could help me. Lets say I have to linked models (Organism and Lipid), and I would like to be able to filter organisms with field values of the Organism model (easy) and also with fields of the Lipid model. I tried creating 2 filters (OrganismFilter and LipidFilter) and then combine them in the view and and pass it as context to the template. It is (kind of) working... The problem is that it only filters Organisms that have the first Lipid.... even before submiting the filter request, it only shows the first record. The models: class Organism(models.Model): species_name = models.CharField(max_length=200, help_text="Species Name") strain_name = models.CharField(max_length=200, help_text="Strain Name") lipids = models.ManyToManyField('Lipid',blank=True) def __str__(self): return('{}'.format(self.species_name)) class Lipid(models.Model): common_name = models.CharField(max_length=100,blank=True) category = models.CharField(max_length=100,blank=True) main_class = models.CharField(max_length=100,blank=True) def __str__(self): return('{}'.format(self.common_name)) The filters: class OrganismFilter(django_filters.FilterSet): model = Organism species_name = django_filters.CharFilter(lookup_expr='icontains') strain_name = django_filters.CharFilter(lookup_expr='icontains') class Meta(): model = Organism fields = [ 'species_name','strain_name'] class LipidFilter(django_filters.FilterSet): Model = Lipid common_name = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Lipid fields = ['category','common_name','main_class'] … -
Django EB using S3 storage -- collectstatic fail
I've been trying to get this set up for about a week without a success so I'm desperate for some help here. I followed the tutorial on this site: https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ to set up my django app and trying to deploy on EB but it keeps failing when it hits collectstatic command. Here's what I have so far.. Error Traceback Traceback (most recent call last): File "/opt/python/current/app/manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle collected = self.collect() File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect handler(path, prefixed_path, storage) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 337, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 255, in delete_file if self.storage.exists(prefixed_path): File "/opt/python/run/venv/local/lib/python3.4/site-packages/storages/backends/s3boto.py", line 454, in exists return k.exists() File "/opt/python/run/venv/local/lib/python3.4/site-packages/boto/s3/key.py", line 539, in exists return bool(self.bucket.lookup(self.name, headers=headers)) File "/opt/python/run/venv/local/lib/python3.4/site-packages/boto/s3/bucket.py", line 143, in lookup return self.get_key(key_name, headers=headers) File "/opt/python/run/venv/local/lib/python3.4/site-packages/boto/s3/bucket.py", line 193, in get_key key, resp = self._get_key_internal(key_name, headers, query_args_l) File "/opt/python/run/venv/local/lib/python3.4/site-packages/boto/s3/bucket.py", line 231, in _get_key_internal response.status, response.reason, '') boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request settings.py AWS_ACCESS_KEY_ID=os.environ.get('AWS_ACCESS_KEY_ID',None) AWS_SECRET_KEY=os.environ.get('AWS_SECRET_KEY',None) AWS_SECRET_ACCESS_KEY=os.environ.get('AWS_SECRET_KEY', None) AWS_STORAGE_BUCKET_NAME = '<my … -
Nginx not updating django website
I have created a django project that is served using uWSGI and Nginx on Ubuntu 16.04 and I have configured uWSGI and Nginx but when I makemigrations and migrate, the models do not show up in the admin page when I go to my IP address. However, when I run the python manage.py runserver command and go to the IP address:port number, the website works like it is suppose to. I followed the tutorial here: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04 My setting file has all the correct information along with the urls, but when trying to access the site via nginx, its almost as if there is nothing there, besides an empty django project. I have restarted the tutorial thinking I may have missed something along the way, but that was not the issue. Any help is appreciated! Here is my nginx configuration file: server { listen 80; server_name I.P address; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/project; } location /media/ { root /home/user/project; } location / { include uwsgi_params; uwsgi_pass unix:/home/user/project/project.sock; } } Is there something wrong with this file or do I need to add more configurations to make it work? Thank You! -
Group by weeks, months, days
I would like to group querysets by a date interval according to a datetime attribute of the model. I want to show average values from the model on a day-to-day, week-by-week and month-by-month basis. E.g. Week commencing 01/01/2017 - average distance: 30 Week commencing 08/01/2017 - average distance: 40 ... Can this be achieved with the standard Django queryset API? -
Django registration template not being updated
I have modified this template templates/registration/registration_form.html it is shown in the debug bar that it is the one being rendered. Also the content is the same that is being displayed and no other matches its content. The issue is that when I modify this template it is not being updated in the application. I'm using runserver to locally run the server, and when I modify other template it is rendered as expected (except the login form). -
MissingSchema at url
I'm trying to access a web service in Django using requests.get but I'm having a MissingSchema at api's url, searchin = 'something' myurl = 'api.webservice.com/search?name='+searchin+'&APIID=abcd' r = requests.get(myurl) -
Django signals, when deleting, post_save and pre_save are called
I have the following code: @receiver(pre_save, sender=Video) def video_pre_save(sender, instance, **kwargs): instance.length = get_video_length(instance.video_file) @receiver(post_save, sender=Video) def video_post_save(sender, instance, **kwargs): from video.manager.manager_course import ManagerCourse instance.course.length = ManagerCourse(instance.course).calculate_course_length() instance.course.save() @receiver(post_delete, sender=Video) def video_post_delete(sender, instance, **kwargs): instance.course.length -= get_video_length(instance.video_file) instance.course.save() instance.video_file.delete() When I'm deleting a video from the admin panel, video_post_delete is called, then video_pre_save is called and after that video_post_save is called and the object is not deleted. If I press the delete button again on the same video, just video_post_delete is called and the object is deleted. I try to use pre_delete instead of post_delete the object was deleted but the save methods where called. Why pre_save and post_save are called when I try to make a delete? -
django 1.8 how to retrieve image file path from the database when using upload_to
I have an image file in my django model. I'm trying to retrieve the path of the image while I've forced the output directory using upload_to but it is not returning the correct path. def signatures_path(instance, filename): return 'signatures/{}/{}'\ .format(instance.id, filename) class Designation(models.Model): designation = models.TextField() user = models.OneToOneField(User) signature = models.ImageField(upload_to=signatures_path,\ blank=True, null=True, default=None, validators=[validate_png]) Designation.objects.filter(user__username=username).values_list('signature', flat=True) [u'sig'jpg'] x = Designation.objects.get(user__username=username) print x.signature.path /home/me/myapp/myapp/media/sig.jpg but I expect it to be: /home/me/myapp/myapp/media/signature/None/sig.jpg How to retrieve the correct path? Note that there is a "None" directory in the path which does not seem to be stored anywhere. -
Django .filter only shows first object
I am currently working in a database application in django. I want to add a advanced filter functionality to a page using django-filter, but I found an issue in my approach and I hope you could help me. To illustrate my point, Organism.objects.all().filter(lipids=Lipid.objects.all()) is only returning the Organism object that has the first Lipid object, instead of all the Organism objects.... More detail: Let's say my models are: Models: class Organism(models.Model): species_name = models.CharField(max_length=200, help_text="Species Name") strain_name = models.CharField(max_length=200, help_text="Strain Name") lipids = models.ManyToManyField('Lipid',blank=True) def __str__(self): return('{}'.format(self.species_name)) class Lipid(models.Model): common_name = models.CharField(max_length=100,blank=True) category = models.CharField(max_length=100,blank=True) main_class = models.CharField(max_length=100,blank=True) def __str__(self): return('{}'.format(self.common_name)) In the django-shell: In [1]: from catalog.models import * In [2]: o = Organism.objects.all() In [3]: l = Lipid.objects.all() In [4]: o Out[4]: <QuerySet [<Organism: speceies_name_001>, <Organism: speceies_name_002>, <Organism: speceies_name_003>, <Organism: speceies_name_004>]> In [5]: l Out[5]: <QuerySet [<Lipid: common_name_001>, <Lipid: common_name_002>, <Lipid: common_name_003>, <Lipid: common_name_004>]> In [6]: o.filter(lipids=l) Out[6]: <QuerySet [<Organism: speceies_name_001>]> I expect to see all the organisms in out[6], because I am not filtering anything! I am sure this is a basic thing I am missing, but can't figure it out! -
do I really have to use signals when importing models from views in Django
so I'm using Django in my views.py I have from . import models also in my urls.py I have from . import views Python is complaining RuntimeError at / Model class myapp.models.ModelName doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. even though it's already in INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.MyappConfig', ] is there seriously no other way to import models from views.py to be used from urls.py without doing all the tedious stuff mentioned here: RemovedInDjango19Warning: Model doesn't declare an explicit app_label -
How to join two tables in django to make GeoJson
In Django, I have two models: class Ssm_El_Ml_Pl_Blocks(models.Model): lease_id = models.CharField(max_length=150, primary_key=True) license = models.CharField(max_length=50, blank=True, null=True) district = models.CharField(max_length=50, blank=True, null=True) mineral = models.CharField(max_length=50, blank=True, null=True) status = models.CharField(max_length=50, blank=True, null=True) geom = models.MultiPolygonField(blank=True, null=True) class Ssm_El_Ml_Pl_Leases(models.Model): lease_id = models.OneToOneField(Ssm_El_Ml_Pl_Blocks, db_column= 'lease_id', primary_key= True) mineral = models.CharField(max_length=254, blank=True, null=True) acreage = models.DecimalField(max_digits=1000, decimal_places=10, blank=True, null=True) location = models.CharField(max_length=254, blank=True, null=True) lessee = models.CharField(max_length=254, blank=True, null=True) address = models.CharField(max_length=254, blank=True, null=True) grant_date = models.DateField(blank=True, null=True) expiry_date = models.DateField(blank=True, null=True) I need to join the data from these two tables and make a geoJson. I have tried lot of queries Like select_related() etc but i cannot able to join these tables. Here is the Sql which fulfill my requirements. SELECT t1.lease_id, t1.license, t1.district, t1.status, t2.acreage, t2.location, t2.lessee, t2.address, t2.grant_date, t2.expiry_date, t1.geom from pm_ssm_el_ml_pl_blocks t1 inner join pm_ssm_el_ml_pl_leases t2 on t1.lease_id = t2.lease_id I tried the following methods Method 1: lease_geom = Ssm_El_Ml_Pl_Blocks.objects.filter(license=lic) leases = Ssm_El_Ml_Pl_Leases.objects.filter(lease_id__in=lease_geom).select_related().order_by('lease_id') leases = serialize('geojson', leases, geometry_field='geom') Method 2: leases = Ssm_El_Ml_Pl_Leases.objects.filter(license=lic).select_related() lease_geom = Ssm_El_Ml_Pl_Blocks.objects.filter(lease_id__in=leases).select_related().order_by('lease_id') leases = serialize('geojson', leases, geometry_field='geom' Any help would be highly appreciated. -
Custom serializer for dynamic chart data
I am using DRF with chart.js library in the front-end. I would like to send calculated values from my REST API to be plotted onto graphs. Initialising the graph requires simple array to be passed as a parameter. I have created a ViewSet with a custom function already. The data will not relate to a specific model. I was thinking to use objects.values_list() method from Django's queryset API but I'm not sure how to serialize this. How can I send data from DRF so that it can be used in the graphs? -
django/javascript populating table on the fly
I have a huge database with multiple tables. Essentially I want the table I have to populate on the fly based on what the user clicks from a menu that is populated from the same database. I'm new to django and don't really know how to go about doing this. Right now all the information I need is being passed to the page when it renders and because of that my page is loading extremely slowly. Basically I have a function that is called when something from the menu is clicked that loops through everything I have passed to the page to populate the table accordingly. To give you a better picture, let's say I have a table of stores and another table of the monthly revenue in my database. The table on the webpage will display the latest 5 data points (ie, the date (month and year), the revenue, and the store name). How do I populate the table based on the selection from the menu? My menu is populated as follows: {% for a, storeList in stores.items %} <div class="overview"> <div><b>{{a}}</b></div> {% for s in storeList %} <div id = "{{s.storename}}" onclick="changeSiteInfo(this.id);"{{s.storename}}</div> {% endfor %} </div> {% endfor … -
pip freeze shows appdirs, packaging, pyparsing, six installed
I created virtualenv, installed in it Django with pip install django==1.9.8 after that pip freeze produces appdirs==1.4.0 Django==1.9.8 packaging==16.8 pyparsing==2.1.10 six==1.10.0 Where all these packages are from? How to get rid of them? I use Ubuntu 16.04,Python 2.7.12, virtualenv version 15 on my home and Windows 7, WinPython 2.7.10 at work. Tried to figure it out but for me the problem looks like appear from nowhere.