Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django media files not showing with Debug = False on production
I currently have two kind of files static files and media files.The static files contain my css,js and other static content. The media files contain stuff that the user uploads.The static folder is right next to the media folder.Now on my deployed machine. If I set the DEBUG = True my static files are presented just fine however my media content is never displayed. I get a 404 not found error. My quuestion is how do I display media content in production environment when DEBUG = False. With DEBUG= True everything seems to work fine ? I read the following page and tried these things out. 1-Tried creating a separate folder for static media just like static content. Currently my static content is being managed by the collectstatic command. I am using apache on webfaction.I have a static folder called static_content when I ran ./manage.py collectstatic all of my content in static folder was copied to the static_content folder.I tried creating another static folder called static_media. However when I ran ./manage.py collectstatic the content of my media folder got copied to static_content and not to static_media like it should have. Can anyone tell me why the collectstatic command did not … -
How do I route a template in Django?
I am trying to use Django on a project. I have made many pages and many templates and now, after a while, I resisted the website to add a few more pages. I added a new template and routed it and it worked. I removed the code for a bit then put it back then it just doesn't work at all. Even if I were to add new ones completely, no effect. So, in this case, the slug of the website is ./buy-now/ The page is already made using a CMS plugin and I entered that slug above. This is my views.py @simple('buy-now.html') def buy_now(request): _page = get_object_or_404(Page, slug='buy-now') return { 'page': _page, } And this is my urls.py url(r'^buy-now/$', content_views.buy_now, name='buy_now'), All the code above is based off of other template configs, so they work in terms of how its set up. But for some reason, for this page, it still returns blank. I even tried to link it to a template thats used for another page, still no luck. Is there something wrong? -
Django message API, require success message to disappear
I am using the django message api, to deliver a success message after my form is saved. I use the below line after from.save() messages.success(request, 'Request submitted successfully') but this is not deleting the message, the message stays there even after reload. I want it to appear and perish. Any idea how I can achieve this? Am I in the right path here? -
building Apache with cosign filter and wsgi for django project inside a docker container
Hi I'm trying to build a docker container with apache2 and cosign and to configure it with wsgi for a django project . I have created the following Dockerfile : FROM ubuntu:16.04 RUN apt-get update RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN apt-get -y install postgresql postgresql-contrib pwgen ### install open ssl RUN apt-get update \ && apt-get install -y wget gcc libssl-dev=$OPENSSL_VERSION make openssl ### Build Cosign ### RUN wget "$COSIGN_URL" \ && mkdir -p src/cosign \ && tar -xvf cosign-3.2.0.tar.gz -C src/cosign --strip-components=1 \ && rm cosign-3.2.0.tar.gz \ && cd src/cosign \ && ./configure --enable-apache2=/usr/local/apache2/bin/apxs \ && sed -i 's/remote_ip/client_ip/g' ./filters/apache2/mod_cosign.c \ && make \ && make install \ && cd ../../ \ && rm -r src/cosign \ && mkdir -p /var/cosign/filter \ && chmod 777 /var/cosign/filter ### Start script incorporates config files and sends logs to stdout ### COPY start.sh . RUN chmod +x start.sh CMD /usr/local/apache2/start.sh RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip RUN ln /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 3500 CMD ["apache2ctl", "-D", "FOREGROUND"] most of it its just copy past from … -
django - Import models from legacy databaseI
I already have a database that I would like to use in my new Django project. I used the inspectdb > models.py command to get the models from my old database, but I get the following error: from django.db import models # Unable to inspect table '>' # The error was: (1146, "Table 'colta.>' doesn't exist") # Unable to inspect table 'Grupa/models.py' # The error was: (1146, "Table 'colta.grupa/models.py' doesn't exist") -
Creating a dictionary with list values from a queryset efficiently
Given a set of objects returned from a queryset how can I construct a dictionary with one of the objects attributes as the key and and the object itself as the value? The current code: questions = Questions.objects.all() parent_question = defaultdict(list) section_question = defaultdict(list) for question in questions: parent_question[question.parent_id].append(question) section_question[question.section_id].append(question) Can I improve the efficiency somehow by remove the loop? Using map or something? Or maybe modifying the query? Or do I have to live with this? -
Serving Multiple WSGI Applications As Different Virtual Hosts on Apache
I have an EC2 AWS server on which I would like to host a couple of Django applications. Each of these apps has its own URL. For instance, example1.com example2.com By itself, example1.com works. The problem is getting example2.com to work with it at the same time. When I visit example2.com, I get an error: DisallowedHost at / Invalid HTTP_HOST header: 'example2.com'. You may need to add 'example2.com' to ALLOWED_HOSTS. Request Method: GET Request URL: http://example2.com Django Version: 1.9.13 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: 'example2.com'. You may need to add 'example2.com' to ALLOWED_HOSTS. Exception Location: /var/www/vhosts/example1/example1-env/lib/python3.5/site-packages/django/http/request.py in get_host, line 109 Python Executable: /usr/bin/python3 Python Version: 3.5.1 Python Path: ['/usr/lib64/python3.5', '/usr/lib64/python3.5/plat-linux', '/usr/lib64/python3.5/lib-dynload', '/usr/local/lib64/python3.5/site-packages', '/usr/local/lib/python3.5/site-packages', '/usr/lib64/python3.5/dist-packages', '/usr/lib/python3.5/dist-packages', '/var/www/vhosts/example1/', '/var/www/vhosts/example1/example1-env/lib/python3.5/site-packages'] Server time: Wed, 14 Jun 2017 20:31:27 +0000 As you can see, somehow Apache is trying to use the virtual environment of example1.com when it serves example2.com. How could I correct that? Each one should be served with its own virtualenv. Here is the Apache configuration file: <VirtualHost *:80> # This is name based virtual hosting. So place an appropriate server name # here. Example: django.devsrv.local ServerName example1.com WSGIDaemonProcess example1 python-home=/var/www/vhosts/example1/example1-env WSGIProcessGroup %{GLOBAL} # Insert the full path to the … -
Travis CI is failing for a Django project
Suddenly my Travis CI build is failing for Django project. The commit for which it was successful yesterday is failing now. Any ideas on what might be going on? Here is the link to the failed Travis CI site: https://travis-ci.org/toladata/TolaActivity/jobs/242957738 The command "python manage.py test" works fine locally. -
How do I fix this NoReverseMatch in Django?
I'm trying to make a blog post/facebook wall type app and am getting a NoReverseMatch Error in Django. Here's my views.py from django.shortcuts import render, get_object_or_404, redirect from wall.models import Post from .forms import PostForm def index(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'wall/index.html', {'form': form}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'wall/post_detail.html', {'post': post}) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^post_detail/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), ] post_detail.html {% extends 'blog/base.html' %} {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% endif %} <p>{{ post.text|linebreaksbr }}</p> </div> {% endblock %} The error page says Reverse for 'post_detail' with keyword arguments '{'pk': 5}' not found. 1 pattern(s) tried: ['$post_detail/(?P\d+)/$'] I've looked at this answer already, but none of the suggestions help. My regex and url names are all spelled correctly. How do I fix this error? -
TypeError: as_view() - Django
I got an error. And i have no ideia how to fix it, take a look, this is the error: TypeError: as_view() takes 1 positional argument but 2 were given This as you can see is the code of my "model.py" page. from django.db import models from django.contrib.gis.db import models class RoadsLines(models.Model): gid = models.IntegerField() geom = models.MultiLineStringField() def __str__(self): # __unicode__ on Python 2 return '%s %s' % (self.gid, self.geom) This as you can see is the code of my "views.py" page. from django.shortcuts import render # Create your views here. from django.shortcuts import render from rest_framework import generics from world.models import RoadsLines from world.serializers import RoadsLinesSerializer class ListCreateRoadsLines(generics.ListCreateAPIView): queryset = RoadsLines.objects.all() serializer_class = RoadsLinesSerializer This as you can see is the code of my "urls.py" page. from django.conf.urls import url, include from rest_framework import routers, serializers, viewsets from world import views # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'Roads', views.ListCreateRoadsLines) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api/', include('rest_framework.urls', namespace='rest_framework')) ] What am I doing wrong? Thank you in advance! -
Postgres database destroyed after running test suite on Wercker
I have a Django app using Wercker as CI. I try to integrate the following steps: run unit test suite (manage.py test --keepdb) run manage.py makemigrations --dry-run to ensure no db changes were left out The issue is that despite unit test step passes correctly, next step fails with following error: Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/usr/local/lib/python3.5/site-packages/django/db/backends/base/base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.5/site-packages/psycopg2/__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) psycopg2.OperationalError: FATAL: database "/wercker-pipeline-594182619e72cc00010beb12/postgres" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 109, in handle loader.check_consistent_history(connection) File "/usr/local/lib/python3.5/site-packages/django/db/migrations/loader.py", line 276, in check_consistent_history applied = recorder.applied_migrations() File "/usr/local/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/usr/local/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/usr/local/lib/python3.5/site-packages/django/db/backends/base/base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/usr/local/lib/python3.5/site-packages/django/db/backends/base/base.py", line 204, … -
Django authentication urls.py with namespace
I wanted to manage a separate urls.py with a namespace. conf/ urls.py (1) common/ urls.py (2) (1) is system-wide urls.py which is installed by Django, and I made (2) which has index page and "accounts" authentication pages. (1) urls.py includes common.url with namespace "common" url(r'^', include('common.urls', namespace='common')), (2) urls.py declares as follows: url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^accounts/register/$', UserCreateView.as_view(), name='register'), url(r'^accounts/register/done/$', UserCreateDoneTemplateView.as_view(), name='register_done'), The following urls are correctly reversed by Django. {% url 'common:login' %} {% url 'common:logout' %} {% url 'common:password_change' %} {% url 'common:register' %} However, "common:password_change_done" is not reversed, and I encountered "NoReverseMatch" error. Of course, url declarations are placed in system-wide urls.py (1). I'm just wondering if it's possible to split it into a separate app (2). Thank you. -
How to make django voting website?
I am creating a website in django which only takes the vote of each user. can anyone tell me what is the models.py for that and how can i count the number of votes(clickable just once) and store that in the database ? -
How to use Django with Apache?
Can someone help me and say whats wrong? I need to use Django + Apache. When I try to start Apache it shows me error: The requested operation has failed. I tried to change Listen 80 to different values but it didnt help. Also this error appears after adding next settings to httpd.conf file (without these settings Apache start fine): LoadModule wsgi_module modules/mod_wsgi.so # Virtual hosts Include conf/extra/httpd-vhosts.conf I use: 1) Apache 2.4 (x64) 2) Python 3.5.2 3) Django 1.10.5 4) mod_wsgi‑4.5.15+ap24vc14‑cp35‑cp35m‑win_amd64.whl 5) Windows 8.1 (x64) Maybe I use wrong mod_wsgi? I take mod_wsgi.cp35-win_amd64.pyd file from mod_wsgi‑4.5.15+ap24vc14‑cp35‑cp35m‑win_amd64.whl archive and rename that file to mod_wsgi.so. After that put that file to modules folder of Apache. error.log file looks like this: [Wed Jun 14 21:42:30.381146 2017] [mpm_winnt:notice] [pid 11892:tid 692] AH00455: Apache/2.4.2 (Win64) configured -- resuming normal operations [Wed Jun 14 21:42:30.381146 2017] [mpm_winnt:notice] [pid 11892:tid 692] AH00456: Server built: May 11 2012 20:42:30 [Wed Jun 14 21:42:30.381146 2017] [core:notice] [pid 11892:tid 692] AH00094: Command line: 'C:\\Program Files\\Apache2.4\\bin\\httpd.exe -d C:/Program Files/Apache2.4 -f C:\\Program Files\\Apache2.4\\conf\\httpd.conf -d C:\\Program Files\\Apache2.4\\.' [Wed Jun 14 21:42:30.381146 2017] [mpm_winnt:notice] [pid 11892:tid 692] AH00418: Parent: Created child process 13624 [Wed Jun 14 21:42:30.646739 2017] [mpm_winnt:notice] [pid 13624:tid 328] AH00354: … -
How to add alert popup boxes in django?
I've been going through the django documentation, but so far everything I've tried hasn't worked for me. I'm trying to make it so if the user enters the url to a certain page and they are not already logged in then they are redirected to the login page that gives them a popup error message that says they don't have access to the page until they have logged in. Here is a small snippet of code from the views.py def home(request): if request.session.test_cookie_worked(): return render(request, 'page/home.html') else: return render(request, 'page/login.html') Everything works except for the error message not popping up if they are redirected to the login page. I've looked at other stack overflow questions that people have asked that are similar to this, but those don't seem to work for me either. Any advice? -
Django templates – specifying common template folder returns "[Errno 22] Invalid argument"
Okay, so I tried having a folder with static template elements accessible by all apps with two css files and one html file. In settings.py I went to TEMPLATES' and added:'DIRS': os.path.join(BASE_DIR, 'static_files'),` My template fragment topnav.html looks like this: <!DOCTYPE html> <html> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <head> <link rel="stylesheet" type="text/css" href="main.css"> <link rel="stylesheet" type="text/css" href="w3.css"> <title>EvoLang</title> </head> <!-- Content will go here --> <body> <script src="myScript.js"></script> <!-- Navigation --> <nav class="topnav"> <ul class="topnav"> <li><a href="#">Entrywords <li><a href="#">Sentences </ul> </nav> <!-- / Navigation --> </body> Then, in previously working index.html in my app biblio looks like this: {% extends "topnav.html" %} {# this enables using the top navigation bar #} <p>Lorem ipsum</p> What I get while accessing that page is the following error: [Errno 22] Invalid argument: 'E:\\MyProject\\\\:\\biblio\\index.html' I don't really get what is this \\:\\ part here. I am using Django 1.11.2 with Python 3.6. -
Filtering objects in a drop-down menu by their field (Django/Javascript)
I'm taking up a web development project in Django, and due to my lack of experience with it in the past I'm having trouble understanding what certain lines of code do, let alone accomplish what I need to in Javascript. I also don't have that much javascript experience either, I've been learning. So jumping right into this... I've found a model called BookTitles and that model has a field called book_type. I need help with understanding how I can access this field within a javascript file and then use it for filtering purposes. When the homepage is rendered in views.py, it generates and returns lists called booklist_latin and booklist_greek. Here's what that looks like (not sure if it's really helpful to see, but I wanted to ask if anyone could help me understand some of what's going on here. sorted_latin_books=sorted(BookTitles.objects.all(),key=lambda book: (book.book_type,book.title_of_book)) booklist_latin= [book.title_of_book for book in sorted_latin_books] I'm kinda confused at what the last line is doing. booklist_latin is called in the html file for the homepage within a for loop, {% for each in booklist_latin %}and the value of {{ each }} is just the title_of_book for each book in the booklist. In other words, I know that … -
django s3 storages does not recognise the bucket name
I am using django-s3-storage==0.11.2 and boto3==1.4.4. These are in the settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn') AWS_S3_BUCKET_NAME = "my-bucket-name" AWS_ACCESS_KEY_ID = 'test_id_x' AWS_SECRET_ACCESS_KEY = 'test_id_x+test_id_x' DEFAULT_FILE_STORAGE = "django_s3_storage.storage.S3Storage" STATICFILES_STORAGE = "django_s3_storage.storage.StaticS3Storage" AWS_S3_ADDRESSING_STYLE = "auto" AWS_S3_BUCKET_AUTH_STATIC = False AWS_S3_MAX_AGE_SECONDS_STATIC = 60 * 60 * 24 * 365 # 1 year. AWS_S3_BUCKET_AUTH = False AWS_S3_MAX_AGE_SECONDS = 60 * 60 * 24 * 365 # 1 year. I have also ran these command: manage.py s3_sync_meta django.core.files.storage.default_storage But when I run collectstatic or this command manage.py s3_sync_meta django.contrib.staticfiles.storage.staticfiles_storage I get this error: botocore.exceptions.ParamValidationError: Parameter validation failed: Invalid bucket name "": Bucket name must match the regex "^[a-zA-Z0-9.\-_]{1,255}$" I have already created the bucket, and the bucket name is correct. What am I missing here? -
Django - Update the second list_filter field in real time according to first field?
So I'm trying to improve my django knowledge and I'm working on this personal project in which I have two categories, the main one which is more general and a subcategories filter. An example would be main_category=smartphone, sub_category=samsung_phones. My class in models.py would be: class Products(models.Model): product_name = models.CharField(max_length=20) main_category = models.CharField(max_length=50) sub_category = models.CharField(max_length=50) And my class in admin.py would be: class ProductsAdmin(ImportExportModelAdmin): ... list_filter = ['main_category', 'sub_category'] ... Now what I wanna do is that, in my /admin/ page, I want to change the contents of 'sub_category' filter -in real-time- and according to what I selected in 'main_category'. Is this possible? Because right now it really doesn't do anything other than taking space so having a main_category filter in itself is useless. Django version is 1.9.1 -
How would I be able to store these first names and last names in database automatically?
I’m currently teaching myself Django and I want to know how to store first names and last names in a database in its appropriate column. I’m familiar with the SQL commands. I know how to manually store them in the database with the SQL commands using the code in the models.py file but this time, I want these first names and last names stored in the database upon the user hitting Submit after filling out the text fields so that next time when I manually look up what’s inside my database, I’ll see what the user has submitted. How would I go about starting this? Here's my urls.py file: from django.conf.urls import url from . import views urlpatterns = [ # /music/ url(r'^$', views.index, name='index'), # /music/71 url(r'^(?P<user_id>[0-9]+)/$', views.detail), ] Here's my views.py file: from django.http import HttpResponse from django.template import loader def index(request): template = loader.get_template('music/index.html') return HttpResponse(template.render()) def detail(request, user_id): # Testing out page 2 return HttpResponse("<h2>Page # (testing this out) " + str(user_id) + "</h2>") Here's my index.html file: <!DOCTYPE html> <html lang="en"> <head> <title>The Page</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form action="#"> <div class="form-group"> … -
Does rest framework paginate from cache when the queryset is cached?
I want to cache my whole queryset. But since django rest framework does pagination(I need it) and when it does pagination, I think it needs to do some filtering on cache which hits database. If thats right, caching doesnt make sense here. Any solution for this ? -
How to disable Django's Test Discovery?
This is an unusual situation - most Django users want Django's test runner to find all of their tests. I'm working on a python library with several test suites that are run with different configurations, so I don't want the discovery to find and run tests from the wrong configuration. How do I disable discovery entirely and rely on the pre-1.6 behavior of only running the tests for apps explicitly declared in INSTALLED_APPS? -
Wagtail menu: add or move items
I'm creating website with Wagtail and i'd like to understand menu wagtail-way. I found solutions with templatetags or with menu-items. This is simple and working. But Wagtail solves if i need to add some item (link to external site, link to webpage with filters aso...) and how menu can be rearanged? I'm tried to search Wagtail "doc", but it keeps talking just about admin menu and for simple menu there nothing more than few simple hints about parent and children of the Page. Thanks for any advice or link to doc. -
Django + React + Bluemix
Managed to get Django to serve a React page (routing through urls.py) locally using https://www.fusionbox.com/blog/detail/create-react-app-and-django/624/ . How do I serve django instance with a react app on ibm bluemix on the same domain? -
Storage efficiency: list of references vs list of integers
If I needed to store Django models.Model objects in a list what would take up less space? A list of references to already instantiated model objects or a list of ids of these instances? Perks of storing the references: I can use the instance straight away. Otherwise an additional lookup (or alternatively a query) would be required. Perks of storing ids: ?. Maybe they take up less amount of space? I cannot really tell or test it anyway I can think of.