Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mongoengine: create a model and set the fields to recieve the collection in django
Here is the MongoDB-Collection Hello, i want to create a model for my collection named "evaluation". In the picture you can see the schema of the collection. My models.py looks like this but it doesn't work. Can someone explain why it doesn't work? Or how it works well? from __future__ import unicode_literals from django.db import models from mongoengine import * class Evaluation(Document): true false = ListField() the neutral accuracy = FloatField() timestamp = StringField() false neutral count = IntField() true neutral count = IntField() false negativ count = IntField() neutral false = ListField() the total accuracy = FloatField() the negativ accuracy = FloatField() false positiv count = IntField() negativ false = ListField() true negativ count = IntField() the positiv accuracy = FloatField() true positiv count = IntField() -
Django rest framework - saving serializer with many to many relationship
I have django model for a place, that place has type many to many field. when im trying to create a new place through the serializers everything is working but the type field doesnt saved. it stays empty. what is the proper way to save that field ? Thank you ! -
How to parse this JSON in django?
I am sending data in the below format $.ajax({ url: "http://localhost:8000/loginrest/", data: JSON.stringify({'user':'admin','password':'zyz'}), processData: false, type: 'POST', error: function(xhr, error){ console.debug(xhr); console.debug(error); }, success: function(data){ alert(data); } }); corresponding django code: class LoginView(APIView): def get(self, request, format=None): return Response({'detail': "GET Response"}) def post(self, request, format=None): try: data = request.DATA except ParseError as error: return Response( 'Invalid JSON - {0}'.format(error.detail), status=status.HTTP_400_BAD_REQUEST ) print(data) print(request.POST) try: print(QueryDict(request.body).get('user')) except: print("error") in terminal <QueryDict: {u'{"user":"admin","password":"zyz"}': [u'']}> <QueryDict: {u'{"user":"admin","password":"zyz"}': [u'']}> error My question is there any simple way parsing this bypassing substringing or am i doing anything wrong when sending the JSON in ajax? -
Mongodb: multidocument write without intermediate state
I have sharded mongodb, and I need to perform a number of operations on the collections from my Django application. Read a record. Do some processing in code. Do writes to two collections. All this operations has to be atomic as a whole. AFAIK, mongo doesn't have a RDBMS-like transactions, atomicity of documents isn't enough for the case, and two-phase commit provides only rollback functionality without guarantees for intermediate state. I could acquire lock for the threads in the python code, like in synchronized in Java, but in the future I will probably have more than one instance of the Django app. Can I maybe acquire write locks for the collections used from the pymongo somehow? Or is using .lock file somewhere in the distributed filesystem my only choice here? There's also a possibility of extracting service into a separate process, and add a message queue between Django and the service. But it feels like a lot of work to do such thing, and a possible bottleneck in the future. -
Django queries extremely slow, prefetch_related and select_related do not improve performance
My REST API that I've made using Django Rest Framework is extremely slow when it comes to fetching a lot of items at once. A request of 200 tracks takes around 1-2 seconds, now if I remove my media references being serialized, it takes around 200-300ms which is a lot better. This is what my serializers look like: Track serializer: class TrackSerializer(BaseSerializer): id = serpy.Field(attr='pk') user_id = serpy.Field(attr='user.pk') username = serpy.Field(attr='user.username') slug = serpy.Field() title = serpy.Field() description = serpy.Field() type = serpy.MethodField() genre = serpy.Field() date_created = serpy.Field() date_modified = serpy.Field() media = serpy.MethodField() duration = serpy.MethodField() stats = serpy.MethodField() by_current_user = serpy.MethodField() user = ProfileSerializer(attr='user.profile') # Booleans and settings downloadable = serpy.Field() explicit = serpy.Field() visibility = serpy.MethodField('get_visibility') def setup_eager_loading(queryset): queryset = queryset.select_related( 'user', ) queryset = queryset.prefetch_related( 'plays', 'comments', 'favorites' ) return queryset def get_type(self, obj): return { 'display': obj.get_type_display(), 'key': obj.type, } def get_media(self, obj): return serialize_media_assets(obj) def get_duration(self, obj): return { 'display': obj.duration_display, 'seconds': obj.duration, } def get_stats(self, obj): return { 'plays': obj.plays.count(), 'favorites': obj.favorites.count(), 'comments': obj.comments.count(), } def get_by_current_user(self, obj): user = self.context['request'].user favorited = False if not user.is_anonymous(): favorited = obj.favorites.filter(user=user).exists() return { 'favorited': favorited } My media reference serializer looks like this: β¦ -
Unicode-objects must be encoded before hashing
I want to use gravatar on django: import hashlib import urllib from django import template from django.utils.safestring import mark_safe register = template.Library() # return only the URL of the gravatar # TEMPLATE USE: {{ email|gravatar_url:150 }} @register.filter def gravatar_url(email, size=40): default = "https://example.com/static/images/defaultavatar.jpg" return "https://www.gravatar.com/avatar/%s?%s" % ( hashlib.md5(email.lower()).hexdigest(), urllib.urlencode({'d': default, 's': str(size)})) # return an image tag with the gravatar # TEMPLATE USE: {{ email|gravatar:150 }} @register.filter def gravatar(email, size=40): url = gravatar_url(email, size) return mark_safe('<img src="%s" height="%d" width="%d">' % (url, size, size)) I am using this link: Django gravatar I put this code in a file called 'grav_tag' and load with: {% load grav_tag %} im my template: {{ user.email|gravatar:150 }} but I get this error Unicode-objects must be encoded before hashing -
How do you create dropdown boxes for forms in django?
I was trying to create a dropdown box in django but there is very little helpful documentation. I know it has something to do with ChoiceFields but I can't seem to get it to work. Can anyone post an example that I could work off? -
Can we use span relationship formats when creating an object
Why does span relationship query work with get and not with create is there a way I can make it work ? Some background: Currently I am doing something like qm = questionModel.object.get(question=quest) answer = modelInterviewAnswer.objects.create(patient=patientobj,question=qm ) Now I know something like this already works modelInterviewAnswer.objects.get(patient=patientobj,question__question=quest ) My question is why does something like this only works with get and not with create modelInterviewAnswer.objects.create(patient=patientobj,question__question=quest ) -
Virtualenv sees global django installation
I've created a virtualenv on Windows with virtualenvwrapper-win and Python 3.5.2. I haven't used --no-site-packages option (couldn't find how to use it with virtualenvwrapper-win). If it is required, why isn't it the default option? Now I have uninstalled the global installation of Python 3.5.2 and installed Python 3.6.0. When I activate my virtual environment, and run "python --version" I get "python 3.5.2". But when I try to run "python manage.py runserver" or "pip freeze" I get errors like this one: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "C:\Users\Ray\Envs\lwc\lib\site-packages\django\__init__.py", line 3, in <module> from django.utils.version import get_version File "C:\Users\Ray\Envs\lwc\lib\site-packages\django\utils\version.py", line 3, in <module> import datetime ImportError: No module named 'datetime' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> import django File "C:\Users\Ray\Envs\lwc\lib\site-packages\django\__init__.py", line 3, in <module> from django.utils.version import get_version File "C:\Users\Ray\Envs\lwc\lib\site-packages\django\utils\version.py", line 3, in <module> import datetime ImportError: No module named 'datetime' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure β¦ -
Django Update object only when foreign key object will change
I want to update my object's min and max price when Item's foreign key object(Currency) will be updated. In this situation it updates after every refresh of page. my views.py for item in object_list: if item.currency.id == 2: new_min_price = item.min_price * (dollar_rate.value) new_max_price = item.max_price * (dollar_rate.value) item.min_price = new_min_price item.max_price = new_max_price item.save() -
Django 1.10 - Plug new app into django
I have a trouble with plugging recently created app called pages into a django project. My pages app.py from django.apps import AppConfig class PagesConfig(AppConfig): name = 'pages' My settings.py, installed apps: INSTALLED_APPS = [ 'pages.apps.PagesConfig' # pages.apps.pages fails too 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ImportError: No module named 'pages.apps.PagesConfigdjango'; 'pages.apps' is not a package Does anyonw knows what is wrong there? I did everything according the docs, but django still cannot to plug my app. Any insights appreciated. -
Django potential critical section
I have this situation in a Django REST Application: I have a delete View: def delete(self, request, pk, lid=None, *args, **kwargs): user_info = self.get_object(pk) if user_info: location = Location.objects.filter(loc_id=lid).first() location.users.remove(user_info) if location.users.count() is 0: //delete location return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_404_NOT_FOUND) I think that in this code there is a potential critical section: flow - 1: Check count location user -> count is 0 flow - 2: Add new user (user2) into location user (by other view) flow - 1: Remove the location because location user is 0 (but this is not correct because flow-2 has added a new user_info). Is possible in Djnago to have this section (check value and delete operation) location = Location.objects.filter(loc_id=lid).first() location.users.remove(user_info) if location.users.count() is 0: //delete location atomically? -
How to detect circular imports using stacktrace in Django?
When I run server, Django raises ImportError: cannot import name events. I suppose it's because of some circular import which I can't find. Is it possible to figure it out and repair using stacktrace? I tried to find which imports causes problems and eliminate them but it did not help. Everytime I do this, it raises another import error. I'm really helpless. THE STACKTRACE: (from PyCharm debugger) Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace instance at 0x044A3760> Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm 2016.3.2\helpers\pydev\_pydev_bundle\pydev_monkey.py", line 594, in __call__ return self.original_func(*self.args, **self.kwargs) File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\utils\autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\core\management\commands\runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\utils\autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\utils\autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\Milano\Desktop\Projekty\venvs\sfl_venv\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:/Users/Milano/Desktop/Projekty/FS Dropbox/Dropbox/SolutionsForLanguages\mainapp\models.py", line 10, in <module> from languagesapp.models import Language File "C:/Users/Milano/Desktop/Projekty/FS Dropbox/Dropbox/SolutionsForLanguages\languagesapp\models.py", line 6, in <module> from ordersapp.models import Price File "C:/Users/Milano/Desktop/Projekty/FS Dropbox/Dropbox/SolutionsForLanguages\ordersapp\models.py", line 15, in <module> from SolutionsForLanguages.events import EventHandler File "C:/Users/Milano/Desktop/Projekty/FS Dropbox/Dropbox/SolutionsForLanguages\SolutionsForLanguages\events.py", line 1, in <module> from SolutionsForLanguages import email File "C:/Users/Milano/Desktop/Projekty/FS β¦ -
Don't fail if log files are unavailable
I have a Django application deployed to some server. Due to some mysterious reason, the permissions on one of the log files changes and Django can no longer write to it. The result is that Django refuses to start up, and uWSGI returns 'internal server errors' all the time. How can I tell the Python RotatingFileHandler not to fail if it can't write to a log file? Best case would be to try another file or path, but a good enough fallback would be to simply not log to this particular file. -
Completing uWSGI/Nginx setup for Django site
So a few months ago I setup a django blog on an Ubuntu server with Digital Ocean using this tutorial digitalocean[ dot] com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04 the only problem was this was done as a brand new blog and I wanted to put my own one that was on my local computer there but I tried to do this by just uploading files via ssh to copy over the old ones and ended up making a mess and had to scrap it. I just started again on a new server and have done the basic setup along with cloning my own django blog onto the server from Github as well as installing postgresql and now Im following this: uwsgi-docs.readthedocs[ dot ]io/en/latest/tutorials/Django_and_nginx.html So far I have completed the following successfully: installed uwsgi run the test.py 'hello world' file successfully with: uwsgi --http :8000 --wsgi-file test.py test run the django site on the sever with: python manage.py runserver my_ip_here:8000 the above appears to be working as I can see the bare basics of my site but not css etc) done a test run of the site with: uwsgi --http :8000 --module mysite.wsgi run collect static which seems to have been successful installed nginx and I β¦ -
Importing Custom Python Module
I am Trying To make code more useful, by Making Custom Module for reusability. Module Imported and working with Print("Hello"); Actual code Giving this error. Here Is My Code Tree View |__ Base.py βββ Helpers β βββ FirefoxImporter β βββ FirefoxImporter.py β βββ __init__.py FirefoxImporter.py def ImportFirefoxMac(): caps = DesiredCapabilities.FIREFOX caps["marionette"] = True caps["binary"] = "/Applications/Firefox.app/Contents/MacOS/firefox-bin" geckodriver="../GeckoDriver/geckodriver" driver = webdriver.Firefox(capabilities=caps, executable_path="../GeckoDriver/geckodriver") Base.py #calling Selenium Installed By PIP from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from Helpers.FirefoxImporter import FirefoxImporter #Calling Def From Import File FirefoxImporter.ImportFirefoxMac() driver.get("http://www.google.com") Import Really working fine with def ImportFirefoxMac(): print("Hello") What's Going on ? -
Multiple image upload in Django admin for a gallery
I have spent a lot of time trying different ways to upload multiple images in Django admin but I have failed miserably. I have tried django-multiupload-admin which I didn't manage to make it work and inlines is not what I am looking for. I just want to select several images all at once, upload them under one category and them display them into a mansory gallery. I am willing to pay someone to help me find a simple way. Please help! -
How to connect Torodb and Django?
Does anyone know how to connect Torodb and Django? I have been reading about it and it seems like a good idea, but it is not very popular and because that there are not many of the "how to..." related with Torodb -
Django cms 3.4.1 admin dlogo
I want to change django admin logo. I'm using django cms 3.4.1. I tried to find logos in: cms/templates/cms/ /media/cms/images/cms_toolbar.png All I found was favicon.jpg in myproject/static/django_cms_style/img. I deleted it, but doesnt work. I tried with css too. I hide one logo, but logo in admin page and login page, they are still there. div.cms .cms-toolbar-item-logo a:before { display: none; } -
Django Error: Reverse for 'blog_detail_url' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['blog/(?P<id>\\d+)$']
On my blog, I am trying to create a URL pager system where I can link to the previous and next post by the ID of the Post model. Right now, every time I try to go to a blog web page I get this error: NoReverseMatch at /blog/2 Reverse for 'blog_detail_url' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['blog/(?P<id>\\d+)$'] views.py: def blog_detail(request, id): # post request from the url return render(request, "BlogHome/pages/post.html") post = Post.objects.get(id) # Next Post try: Next_Post_id = (post.id + 1) Next_Post = Post.objects.get(id=Next_Post_id) except ObjectDoesNotExist: Next_Post = None # Previous Post try: Previous_Post_id = (post.id - 1) Previous_Post = Post.objects.get(id=Previous_Post_id) except ObjectDoesNotExist: Previous_Post = None context = {'post': post, 'Next_Post': Next_Post, 'Previous_Post': Previous_Post} return render(request, "BlogHome/pages/post.html", context) urls.py: urlpatterns = [ url(r'^$', views.blog_list), url(r'^(?P<id>\d+)$', views.blog_detail, name='blog_detail_url'), ] post.html: {% extends "BlogHome/includes/WELL.html" %} {% block content %} <script> document.title = "Pike Dzurny | {{post.title}}" </script> <div class="container-fluid text-center"> <center> <div class="well" id="WellPost"> <div class="container-fluid"> <h2 align="center" id="TitleText">{{post.title}}</h2> <h3 align="center" id="BodyText">{{ post.date|date:"m-d"}}</h3> <h3 align="left">{{ post.body|safe }}</h3> {% if Next_Post is defined and Previous_Post is defined %} <ul class="pager"> <li class="previous"><a href="{% url 'blog:blog_detail_url' Post.id %}"><span aria-hidden="true">&larr;</span> Older</a></li> <li class="next "><a href="{% url β¦ -
Docker container won't run through a "CommandError:"
I am trying to follow docker example "Quickstart: Compose and Django"" found on docker docs. I get an error that I can't solve. this is the error: CommandError: /usr/src/app/manage.py already exists, overlaying a project or app into an existing directory won't replace conflicting files I followed the example and create Dockerfile, docker-compose.yml, requirements.txt as stated in the example. I am using Docker mac client the latest version. I also have compose installed like indicated in the first line of the tutorial docs. I have uninstalled boo2docker and virtualbox. Also my machine do not have django installed. I tried nginx container and it is running ok. here is a Docker ps -a docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES bb5a66249286 dockerdjango_web "django-admin.py star" 2 days ago Exited (0) 2 days ago dockerdjango_web_run_1 85ea80f8b26b postgres "/docker-entrypoint.s" 2 days ago Exited (0) 2 days ago dockerdjango_db_1 ab7fd45523cd nginx "nginx -g 'daemon off" 2 days ago Exited (0) 2 days ago webserver b940a184d395 django "bash -c 'pip install" 2 days ago Exited (0) 2 days ago some-django-app I have looked everywhere and can't find the solution to this problem! I appreciate any help. -
How to get django-debug-toolbar to show query location in template
I'm new to using django_debug_toolbar and I can't figure out how to get the SQL panel to go into my templates to show where the queries are originating. Instead, any query originating from a template just indicates the view's render method as the source of the query. For example: SELECT "quest_category"."id", "quest_category"."title", "quest_category"."icon", "quest_category"."active" FROM "quest_category" WHERE "quest_category"."id" = '8' Duplicated 53 times. 0.935909254879955% 0.11 Connection: default /home/me/Developer/myproject/src/quests/views.py in quest_list(164) return render(request, "quests/quests.html", context) What I'm trying to get is what's demonstrated in this (~15s) clip of using the django-debug-toolbar. How can I turn this capability on? -
Debugging silent failure in Gunicorn/NGINX/Django
I'm running a Django project with Gunicorn. I'm using Nginx as a reverse proxy. For the most part, everything works fine, but there's one Django view that causes Gunicorn to fail silently. Details of the problem are below, but first, here's the Django view that's causing the problem: def jobs_all(request): if not request.user.is_superuser: raise Http404 jobs = Job.objects.all().order_by('-date_created') return render(request, 'monitor/jobs_all.html', { 'jobs': jobs, }) If I change 'jobs': jobs, to 'jobs': [],, it works. So I gather that the problem involves passing those QuerySet results to the template. The error that displays in the browser is Nginx's 502 Bad Gateway error. My Nginx error log reads: 2017/01/22 05:17:25 [error] 22#0: *26 upstream prematurely closed connection while reading response header from upstream, client: 12.34.56.78, server: www.example.com, request: "GET /monitor/jobs/all/ HTTP/1.1", upstream: "http://127.0.0.1:8000/monitor/jobs/all/", host: "www.example.com", referrer: "https://www.example.com/monitor/" OK, so it looks like the request Gunicorn is timing out or closing somehow. But I don't see how. The error occurs within a few seconds, which shouldn't be a problem under my Nginx and Gunicorn configuration. I don't see any other error messages. Here is my command to start Gunicorn: $ /usr/local/bin/gunicorn -b 127.0.0.1:8000 --keep-alive 43200 -w 4 --log-level=DEBUG mydjangoproject.wsgi --timeout=43200 (In production, β¦ -
zinnia exception: TypeError: view must be a callable or a list/tuple in the case of include()
I'm using zinnia with django 1.10. When I follow the tutorial http://django-blog-zinnia.readthedocs.io/en/develop/getting-started/install.html and run the sample codes, it throws exceptions like this: enter image description here TypeError: view must be a callable or a list/tuple in the case of include(). In source code: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index$', webIndex_index), url(r'^$', weIndex_redirect), # zinnia urls url(r'^weblog/', zinia_urls), url(r'^comments/', django_comments_urls), ] Through Django URLs error: view must be a callable or a list/tuple in the case of include() , I found that it is because Django 1.10 no longer allows you to specify views as a string (e.g. 'myapp.views.home') in your URL patterns. But in zinnia, there are such codes: urlpatterns = [ url(_(r'^feeds/'), include('zinnia.urls.feeds')), url(_(r'^tags/'), include('zinnia.urls.tags')), url(_(r'^authors/'), include('zinnia.urls.authors')), url(_(r'^categories/'), include('zinnia.urls.categories')), url(_(r'^search/'), include('zinnia.urls.search')), url(_(r'^random/'), include('zinnia.urls.random')), url(_(r'^sitemap/'), include('zinnia.urls.sitemap')), url(_(r'^trackback/'), include('zinnia.urls.trackback')), url(_(r'^comments/'), include('zinnia.urls.comments')), url(r'^', include('zinnia.urls.entries')), url(r'^', include('zinnia.urls.archives')), url(r'^', include('zinnia.urls.shortlink')), url(r'^', include('zinnia.urls.quick_entry')), url(r'^', include('zinnia.urls.capabilities')), ] If I want to continue to use zinnia, should I lower my Django version? or there are some other ways to solve this problems? -
Django not creating test database on remote host
I'm working on migrating to a staging site where I want to run my functional tests. The tests are working great on the local box, but once posted to the staging site, the test runner does not create a test_ database. I'm not sure from the docs if it is supposed to? I don't find any mention of running tests against a remote host. My functional tests require a fresh database to complete correctly. I'm running the tests local using the --liveserver= parameter pointed at the staging server. Using Django 1.10.5 with MySQL on the remote host and SQLite locally. Here is the databases section of my remote settings file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'suggport', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'HOST': 'localhost', 'TEST': { 'NAME': 'test_suggport', } } } When I run the test runner it says: Creating test database for alias 'default'... But I see no evidence that it is actually doing that. Is the test runner supposed to be able to set up a test database on the remote server? How does the remote server know that it is running under test, or does it know? How do others handle this situation? Any help much β¦