Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RawPostDataException: You cannot access body after reading from request's data stream
I am hosting a site on Google Cloud and I got everything to work beautifully and then all of the sudden I start getting this error.. 01:16:22.222 Internal Server Error: /api/v1/auth/login/ (/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/exception.py:124) Traceback (most recent call last): File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 474, in dispatch response = self.handle_exception(exc) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 434, in handle_exception self.raise_uncaught_exception(exc) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 471, in dispatch response = handler(request, *args, **kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/authentication/views.py", line 42, in post data = json.loads(request.body) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/request.py", line 359, in __getattribute__ return getattr(self._request, attr) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/http/request.py", line 263, in body raise RawPostDataException("You cannot access body after reading from request's data stream") RawPostDataException: You cannot access body after reading from request's data stream I have no clue what this means, and endless googling has not solved my case in anyway.. Here's the code that is probably relevant: views.py class LoginView(views.APIView): def post(self, request, format=None): data … -
django - resizing horizontal filter for group admin page
I'm trying to resize the horitontal filter for default group admin page because it is too small. Here is what I've tried: admin.py: class GroupAdmin(admin.ModelAdmin): filter_horizontal = ('permissions',) class Media: js = ('js/group_admin.js',) admin.site.unregister(Group) admin.site.register(Group, GroupAdmin) group_admin.js: $(function() { $("#id_permissions_from").css("height", 600); $("#id_permissions_from").css("overflow", "scroll"); $("#id_permissions_to").css("height", 600); $("#id_permissions_to").css("overflow", "scroll"); }) It's not resizing and is not showing any javascript error. If I run the javascript above in the console it works fine; so there must be something wrong with the order of javascripts getting loaded. I'm using django 1.8. Any ideas? -
Submenu refuses to open on click. Why?
I'm trying to have a left side navigation bar where by default categories are listed and upon clicking on a category, the subcategories are shown under it (in a sort of expanding sub-menu). I'm working in Django and relevant portions of my code are below. When I include the JS code, none of the links on the page work and when I exclude it, all the subcategories for all categories are shown by default. I need only categories to be shown by default and upon clicking on any, the respective subcategories be shown. What am I missing here? JS CODE: at the bottom of the page, loaded after the footer: {% block theme_script %} <script src="{% static "pinax/js/theme.js" %}"></script> <script> $(function(){ $(".nav-collapse88").hide(); $(".nav-collapse89 a").click(function(e){ e.preventDefault(); $(".nav-collapse88", $(this).parent()).slideToggle(); }); }) </script> {% endblock %} My HTML: <ul class="catindexlist catlistcat nav-collapse89"> {% for category in catindexlisted %} <div class="catindexlistitem"><li class="category-name" style="font-weight:600;padding-right:20px;"><a href="">{{category.name}}</a></li></div> <div class="nav-collapse88"> <ul style="padding:0px;"> {% for forum in category|forumindexlistbycat %} <div class="catlistforum"><li style="padding-right:10px;"><a href="{{ forum.get_absolute_url }}">{{forum.name}}</a></li></div> {% endfor %} </ul> </div> {% endfor %} </ul> All who answer will win a magical Pony! Thanks, -
Django does session.flush() expire the database session entry?
According to the Django documentation here request.session.flush() Deletes the current session data from the session and deletes the session cookie. (django.contrib.auth.logout() function calls it) But does it also automatically expire the session entry inside the database table? Because if it doesnt, I think that might cause an unnecessary build up of non-usable but non-expired sessions inside the table. -
PYTHONPATH - pyvenv & django
I created a virtual environment using pyvenv at ~/Developer/environments/eg. I printed out the sys.path and I'm concerned as to why the lib folder for the environment is listed after the global lib folder. Shouldn't pyvenv be putting it before it so that it doesn't touch the global one? >>> import sys >>> print(*sys.path,sep='\n') # this one makes sense because the 1st eg is the pyvenv, the second eg is the django workspace /Users/myself/Developer/environments/eg/eg /usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python35.zip /usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5 /usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin /usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload # shouldn't this one be above the previous ones? /Users/myself/Developer/environments/eg/lib/python3.5/site-packages If I'm importing an app or package, why would I trust it to find my environment package before the global one if it's listed after? -
How to read values from a redirect url in Django Python
http://127.0.0.1:8084/Happy/studen/#access_token=eyJhbGciOiJIUzI1 I have a recirect url like this which redirects to a handler in my django app and it works fine . The issue um facing was to read values appearing after # in the particular url . How may I read those values in the corresponding handler? I Have tried both of these ways n = request.get_full_path() k = resolve(request.path_info).url_name But it wont give me the values after # Is there a specific way to do this in django? -
NoReverseMatch Reverse for 'profile_user' with arguments '()' and keyword arguments '{}' not found.
Views.py @login_required def profile_edit(request): profile, created = UserProfile.objects.get_or_create(user=request.user) form = UserProfileForm(request.POST or None, request.FILES or None, instance=profile) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('profile_user') context = { "title": 'Edit Profile', "form":form, } return render(request, 'profiles/userprofile_form.html', context) main url there is no name space given and profile url is as follows. url(r'^profile/(?P[\w.@+-]+)$', profile_view, name='profile_user'), Could anybody help to solve this please? -
Is it possible to submit a form with angular and with html
I need to authenticate my django app as well as the angular app that is used within it. The service backend uses django rest framework OAuth. I have tried sharing session variables but they seem to be different sessions. It seems the only way is to create a login form that kicks off an angular ng-submit in addition to regular form submit which will authenticate the django app. Are there any examples of this available? Is this even a good idea? -
SETUP A CLOUD WITH DJANGO
So ,I am planning to create a dropbox like server using Django . Currently it is for my project purpose,if it goes well I might monetize it.Since I am new to Django,I needed help as in are there any libraries which make life easier,or any existing GIT code which shows how to do this.And also security considerations for file transfer,storing passwords in DB will be of great help. Any general idea or methodology to go about(such as where to store data,how to store,security) will very helpful .Also wanted to know do buy a domain or some space or host it on my laptop iteself? Im kinda lost here but need to get something up in two months. Thanks in advance. -
Django dumpdata uses the display value of a field where choices is set instead of the smallintfield key
I have an abstract object which is defined as Person object. I have several descendants. On one descendant Staff, I have a smallintfield (designation) that has a choices set to a tuple defined as: DESIGNATION_CHOICES = ( (MEDTECH, 'Medical Technologist'), (PATHOLOGIST, 'Pathologist'), ) Where MEDTECH and PATHOLOGIST are numeric constants. When I do a ./manage.py dumpdata on the app, the designation field will get the value 'Medical Technologist' instead of the key value MEDTECH. Does anyone have any idea how I can resolve this? -
How to configure Visual Studio Code to debug Django app in a virtualenv?
I would like to have possibility to do a debugging of Django application in Visual Studio Code. I have a virtualenv, made a change in launch.json file that look like this: { "name": "Django", "type": "python", "request": "launch", "stopOnEntry": true, "pythonPath": "${workspaceRoot}/.venv/bin/python2.7", "program": "${workspaceRoot}/mysite/manage.py", "args": [ "runserver" ], "debugOptions": [ "WaitOnAbnormalExit", "WaitOnNormalExit", "DjangoDebugging", "RedirectOutput" ] }, put several break points in the code and run it. Unfortunately, the execution is not stopped on the line with break points. I tried the same without virtualenv and everything worked perfectly. Please, point out what I am doing wrong here. -
How to add change-related and add-related widgets on the right of Grappelli autocomplete widget in Django admin?
The default widget for the ForeignKey model field looks like a <select> html element with change-related (a pencil) and add-related (a plus sign) buttons on the right. How can I instead use Grappelli autocomplete widget and still have a pencil and a plus sign on the right of the widget? -
Server rendering in python/ruby/php then attach react.js in client
I'd like to try react.js. Most examples seem to suggest server api + reactjs rendering or server rendering via node/reactjs + reactjs rendering on client I'd like to have two templates, one server and one client because I think maintaining node+reactjs on server is a hassle and cause performance degrade. If I render html on server with jinja2 (or whatever server template language other than reactjs), would it be possible to attach reactjs component to the rendered html? Doesn't react add special id and key attributes to divs that are hard to create with jinja2 (or any template language) ? -
Gunicorn, no module named 'myproject
I'm installing a previously built website on a new server. I'm not the original developer. I've used Gunicorn + nginx in the past to keep the app alive (basically following this tutorial), but am having problems with it here. I source venv/bin/activate, then ./manage.py runserver 0.0.0.0:8000 works well and everything is running as expected. I shut it down and run gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application, and get the following: [2016-09-13 01:11:47 +0000] [15259] [INFO] Starting gunicorn 19.6.0 [2016-09-13 01:11:47 +0000] [15259] [INFO] Listening at: http://0.0.0.0:8000 (15259) [2016-09-13 01:11:47 +0000] [15259] [INFO] Using worker: sync [2016-09-13 01:11:47 +0000] [15262] [INFO] Booting worker with pid: 15262 [2016-09-13 01:11:47 +0000] [15262] [ERROR] Exception in worker process Traceback (most recent call last): File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi self.wsgi = self.app.wsgi() File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app __import__(module) ImportError: No module named 'myproject.wsgi' [2016-09-13 01:11:47 +0000] [15262] [INFO] Worker exiting (pid: 15262) [2016-09-13 01:11:47 +0000] [15259] [INFO] Shutting down: Master [2016-09-13 01:11:47 +0000] [15259] [INFO] Reason: … -
How to translate docker-compose.yml to Dockerrun.aws.json for Django
I am following the instructions at https://docs.docker.com/compose/django/ to get a basic dockerized django app going. I am able to run it locally without a problem but I am having trouble to deploy it to AWS using Elastic Beanstalk. After reading here, I figured that I need to translate docker-compose.yml into Dockerrun.aws.json for it to work. The original docker-compose.yml is version: '2' services: db: image: postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db and here is what I translated so far { "AWSEBDockerrunVersion": 2, "volumes": [ { "name": "db" }, { "name": "web" } ], "containerDefinitions": [ { "name": "db", "image": "postgres", "essential": true, "memory": 256, "mountPoints": [ { "sourceVolume": "db" "containerPath": "/var/app/current/db" } ] }, { "name": "web", "image": "web", "essential": true, "memory": 256, "mountPoints": [ { "sourceVolume": "web" "containerPath": "/var/app/current/web" } ], "portMappings": [ { "hostPort": 8000, "containerPort": 8000 } ], "links": [ "db" ], "command": "python manage.py runserver 0.0.0.0:8000" } ] } but it's not working. What am I doing wrong? -
how to get session or cookie value set in django, php, ruby in angular?
I am trying to get a session and/or cookie value I set in django (although I don't see this being different across other languages like php or ruby). I am trying to get this value with the following angular: var app = angular.module('edgeFeed', ['ngCookies']); app.controller('FeedController', function($http, $cookieStore) { self = this; console.log(sessionStorage.getItem('session_name')); console.log($cookieStore.get('cookie_name')); In the console I get the output: null undefined How can I get the session or cookie value in angular? -
How can I select all two-row couples that match on a field in django?
I'm working with latest Django version and fail at creating a join filter, selecting two primary keys of the same table, using value equality on a field in that model. I have a table called Model, and it contains a field called Data. Each Model is associated with a File, similar to the following: class Model(models.Model): file = models.ForeignKey(File, related_name='models') data = models.TextField() I would like to implement a function that receives two File.ids: source_file and target_file. The function should return a list of two-tuples of two Model.ids: source_model and target_model. The first Model.id should be related to the first file (source_file) and the second Model.id should be related to the second file (target_file). The two Model objects are required to have the same value in Model.data. If there's a source_id without a target_id or vice-versa, they should be omitted from the returned list. For exmple, lets say I have the following Model table: | id | file_id | data | |----|---------|------| | 10 | 1 | a | | 11 | 2 | a | | 12 | 3 | a | | 13 | 1 | b | | 14 | 2 | c | | 15 | … -
Django: 400 Error with Debug=False and ALLOWED_HOSTS=["*"]
I'm trying to run a relatively simple Django server on python 3.5.3 on an Ubuntu DigitalOcean droplet. I'm using a Gunicorn server with nginx. The server runs fine when DEBUG=True in settings.py. But when I set it to False, I get a 400 error when trying to visit the page. I tried setting ALLOWED_HOSTS to ['*'], but I still get the same error. I've looked on a lot of forums and many questions on SO but none of the solutions have worked. -
Equivalent of manage.py <app_name> -h
I have multiple apps in my django project that all have management commands. Several of these apps start with a,b or c and therefor are listed before the main django management commands when running manage.py -h. I've been running manage.py -h | less to get a pager of of all commands. However, I'd really like to be able to run `manage.py -h. Is this possible? -
Default instance for Django model
My questionis: is there anyway to create a default instance for class Language? Like this : class Language(models. default_instance = Language(name="unknown") name = models.CharField(max_length=100) so class Student can use this: class Student(models.Model): name = models.CharField(max_length=50) language = models.ForeignKey(Language, default = Language.default_instance.pk ) Thank you! -
Django-channels fails on Travis-CI
So I'm trying to write some code that uses django-channels and test it on Travis-CI, but it keeps fail on Travis and only there. I've checked the pip list on my local install and on Travis-CI and both are using Django-channels 0.17.2. But for some reason, I can't import anything on Travis and it makes debugging a pain. Here is the traceback: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/opt/python/2.7.9/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/haystack/__init__.py", line 57, in <module> signal_processor_class = loading.import_class(signal_processor_path) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/haystack/utils/loading.py", line 32, in import_class module_itself = importlib.import_module(module_path) File "/opt/python/2.7.9/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/travis/build/aristotle-mdr/aristotle-metadata-registry/aristotle_mdr/channels/signals.py", line 4, in <module> from haystack_channels.signals import ChannelsRealTimeAsyncSignalProcessor File "/home/travis/virtualenv/python2.7.9/src/django-haystack-channels/haystack_channels/signals.py", line 8, in <module> from channels.generic import BaseConsumer ImportError: No module named generic The code itself that is failing is just a simple import: from django.apps import apps from django.db import models from channels.generic import BaseConsumer # ---- Rest of module snipped ---- … -
Setting up a result backend (rpc) with Celery in Django
I am attempting to get a result backend working on my local machine for a project I'm working on but I am running into an issue. Currently I am trying to create a queue system in order for my lab to create cases. This is to prevent duplicate sequence numbers from being used. I am already using Celery for our printing so I figured I would create a new Celery queue and use that to handle the case. The front-end also needs to get the results of the case creations to display the case number that was created. http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html#rabbitmq I was following the above tutorial on getting my Celery configured. Below is the source: celeryconfig.py: from kombu import Queue CELERY_DEFAULT_QUEUE = 'celery' CELERY_DEFAULT_EXCHANGE = 'celery' CELERY_DEFAULT_EXCHANGE_TYPE = 'direct' CELERY_RESULT_BACKEND = 'rpc://' CELERY_RESULT_PERSISTENT = False CELERY_QUEUES = ( Queue('celery', routing_key="celery"), Queue('case_creation', routing_key='create.#') ) CELERY_ROUTES = { 'case.tasks.create_case': { 'queue': 'case_creation', 'routing_key': 'create.1' }, 'print.tasks.connect_and_serve': { 'queue': 'celery', 'routing_key': 'celery' } } celery.py: import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings.local') app = Celery('proj', broker='amqp://guest@localhost//') app.config_from_object('proj.celeryconfig') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) tasks.py: import celery from django.db import IntegrityError from case.case_create import CaseCreate @celery.task(bind=True) def create_case(self, data, user, ip): try: acc = … -
Django - Failed to load resource: the server responded with a status of 403 (Forbidden)
I'm fairly new to django and I've been having some problems with pictures not showing up, they are simply links of images but for some reason i get an error Failed to load resource: the server responded with a status of 403 (Forbidden). If i try to open the links of the images seperately (they're in the browsers cache now), when i reload the page they show, but if i empty the cache again they go back to not shpowing. index.html <ul class="list"> {% for movie in all_movies %} <li> <img src="{{ movie.poster }}" alt="" class="cover" /> <a href="{% url 'detail' movie.id %}"><p class="title">{{ movie.title }}</p></a> {% for genre in movie.genre.all %} <p class="genre">{{ genre.genre }} | </p> {% endfor %} </li> {% endfor %} </ul> views.py def index(request): all_movies = Movie.objects.all() all_genres = Genre.objects.all() our_pick = Movie.objects.get(pk=8) context = { 'all_movies': all_movies, 'all_genres': all_genres, 'our_pick': our_pick } return render(request, 'movies/index.html', context) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<movie_id>[0-9]+)/$', views.detail, name='detail'), ] I found someone with a slightly similar problem Failed to load resource: the server responded with a status of 403 (Forbidden) django framework but even tho i logged out, i'm still having the same problem. any help … -
Djangocms_blog confusion about post creating
I met a lot of difficulties to start Djangocms-blog, I follow exactly indications from online docs as in excerpt below : start your blog you need to use AppHooks from django CMS to add the blog to a django CMS page; this step is not required when using Auto setup: 1- Create a new django CMS page 2 - Go to Advanced settings and select Blog from the Application selector and create an Application configuration; 3- Eventually customise the Application instance name; 4- Publish the page 5- Restart the project instance to properly load blog urls. as below After adding the apphook to the page you cannot change the Instance Namspace field for the defined AppHokConfig; if you want to change it, create a new one with the correct namespace, go in the CMS page Advanced settings and switch to the new Application configuration Add and edit blog by creating them in the admin or using the toolbar, and the use the django CMS frontend editor to edit the blog content: Create a new blog entry in django admin backend or from the toolbar Click on “view on site” button to view the post detail page Edit the post via … -
Django psql full text search not matching un-stemmed word
I'm running Django 1.10.1 against Postgres 9.4. My staging server and dev environments have psql servers at version 9.4.9 and production is an RDS instance at 9.4.7. It seems like my SearchVectorField is not storing the search configuration given in production, though it is in staging and dev, and it seems to be either a version thing (unlikely, given the version difference and that it also worked on 9.3 in staging/dev) or the fact that production is on RDS instead of local on the server. I'm using a custom configuration for full-text search which looks like this: Token | Dictionaries -----------------+----------------------- asciihword | english_stem asciiword | english_stem email | simple file | simple float | simple host | simple hword | unaccent,english_stem hword_asciipart | english_stem hword_numpart | simple hword_part | unaccent,english_stem int | simple numhword | simple numword | simple sfloat | simple uint | simple url | simple url_path | simple version | simple word | unaccent,english_stem Unaccent is installed in both environments, and works in both environments. I'm storing the search data in a django.contrib.postgres.search.SearchVectorField on my Writer model. That column is updated with the following search vector: (SearchVector('first_name', 'last_name', 'display_name', config='unaccent', weight='A') + SearchVector('raw_search_data', config='unaccent', weight='B')) And, …