Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to import python module into a dictionary?
This is more a Django specific question, let's say I have settings/base.py as below: DATABASES = {...} SECRET_KEY = '1234567' And I would like to import this into my development.py, but as a dictionary, something like: from .base import * as base_dict #wrong syntax here # adjust database connection base_dict['DATABASES'] = {...} # merge to development.py merge_dict_to_settings(base_dict) I tried base.__dict__ but it contains a lot more stuff than I needed. -
Django settings when using pgbouncer
I have a Django website with Postgresql backend, for which I'm utilizing pgbouncer for db connection pooling (transaction mode). The application and the DB reside on separate servers (1 server each). I have installed pgbouncer on the application server. My question is: what should the config be in settings.py? Note that I'm using Unix sockets for connecting to pgbouncer. My current settings.py contains: DATABASE_URL = 'postgres://user1:pass1@host:5432/db1' DATABASES = { 'default': dj_database_url.config(default=DATABASE_URL) } Relevant sections of pgbouncer.ini are: [databases] db1 = host=xx.xxx.xxx.xxx port=5432 dbname=db1 listen_addr = * listen_port = 6432 auth_type = md5 unix_socket_dir = /var/run/postgresql pool_mode = transaction max_client_conn = 200 default_pool_size = 300 userlist.txt contains: "user1" "pass1" Note: I'm using a legacy Django version, where pgbouncer is my best option for db connection pooling. -
No class matches the given query
I tried to create my first simple app but i have a problem on my way. When i go through a link http://127.0.0.1:8000/polls/ i have a next error message: TemplateDoesNotExist at /polls/ /polls/index.html Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 1.10.2 Exception Type: TemplateDoesNotExist Exception Value: /polls/index.html Exception Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/Django-1.10.2-py3.5.egg/django/template/loader.py in get_template, line 25 Python Executable: /Library/Frameworks/Python.framework/Versions/3.5/bin/python3 Python Version: 3.5.2 Python Path: ['/Users/alenasanina/djangoenv/bin/mysite', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/Django-1.10.2-py3.5.egg', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages'] Server time: Tue, 25 Oct 2016 21:48:49 +0300 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: This engine did not provide a list of tried templates. Traceback Switch to copy-and-paste view /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/Django-1.10.2-py3.5.egg/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/Django-1.10.2-py3.5.egg/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/Django-1.10.2-py3.5.egg/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /Users/alenasanina/djangoenv/bin/mysite/polls/views.py in index return render(request, '/polls/index.html', context) ... ▶ Local vars /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/Django-1.10.2-py3.5.egg/django/shortcuts.py in render content = loader.render_to_string(template_name, context, request, using=using) ... ▶ Local vars /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/Django-1.10.2-py3.5.egg/django/template/loader.py in render_to_string template = get_template(template_name, using=using) ... ▶ Local vars /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/Django-1.10.2-py3.5.egg/django/template/loader.py in get_template raise TemplateDoesNotExist(template_name, chain=chain) ... ▶ Local vars Next i go through the link http://127.0.0.1:8000/polls/1 and here is another error: Page not found (404) … -
change timezone in mod_wsgi on openshift
I deployed a django application on openshift and I'm running it in productive mode. When I look at the logs (python.log) in $OPENSHIFT_LOG_DIR I see messages from my django app and the apache server/mod_wsgi. These two sources use different format of their messages - I know I can change the log format of my django application to use the same format as the apache log, but the two sources are also using different time zones. The django application runs in Berlin/Europe time zone whereas the apache log messages uses Eastern Standard time. This makes it uncomfortable to read the logs: 195.195.195.12 - - [25/Oct/2016:15:14:09 -0400] "GET /favicon.ico HTTP/1.1" 404 85 "-" ... 195.195.195.12 - - [25/Oct/2016:15:14:09 -0400] "GET /favicon.ico HTTP/1.1" 404 85 "-" ... [Tue Oct 25 21:14:09 2016] [error] kwargs in CreateView: {'instance': None, 'prefix': ... [Tue Oct 25 21:14:09 2016] [error] ModelForm.__init__ called ... 195.195.195.12 - - [25/Oct/2016:15:14:09 -0400] "GET /publisher/upload HTTP/1.1" 200 2 ... 195.195.195.12 - - [25/Oct/2016:15:14:11 -0400] "GET /static/publisher/css/bootstrap/b ... Is there a way I can make apache/mod_wsgi use Berlin/European time zone? PS: A way to change the format of the apache log format would also be appreciated. -
How to serve a directory of static files at a custom url in django
I'm working on a django app that has static files being served from http://host/static. I have a new folder full of static html/js/css that needs to be accessible at http://host/staff. How can I tell django to serve the /staff files from that url? Using nginx or some other proxy is not an option, and neither is changing the url. -
How to get datetime without Django modifying time?
Django 1.9 / Postgres 9.4 - I have a model datetime field called date_ending. When I get the datetime with my_item.date_ending it gives me date and time that is different than what I see when I access the database directly. I set settings.py: TIME_ZONE = 'UTC' USE_I18N = False USE_L10N = False USE_TZ = False This should get django out of changing timezone stuff, correct? Basically I want Django to not touch timezones at all. Also, this might be something completey different... when I save a model with a datetime field and date field. The date is different thna dthe datetime. datetime_ = datetime.datetime.utcnow() datetime_date_ = datetime_.date() MyModel.objects.create( datetimefield=datetime_, datefield=datetime_date_, ).save() My database: datetimefield | datefield -------------------------------+----------------- 2016-11-04 18:23:18.407671-07 | 2016-11-05 ???? Any help please. Thanks -
How to change to string and remove ' from Django tempalates / context?
I currently have a date that is formatted in unicode: k = u'2015-02-01' I tried to add this to a list and change it into a string: date = [] date.append(str(k)) Then I want to pass this as a Django context to my template. However, the date is showing up with the following: '2015-02-01' How do I just rid of $#39; and replace it with a double quote (")? Thanks much. -
Heroku open doesn't work. "ValueError: The file 'css/style.css' could not be found"
I am having trouble with heroku deployment. When I open the app in the browser, it's throwing me an error message that says: Internal Server Error The server encountered an unexpected internal server error (generated by waitress) How can I fix this? Below is the heroku logs error message. As you can see at the end, it's showing me that heroku couldn't find the css.file. Never experinenced this issue in local environment. Thank you for your time. (venv) Ryujis-MacBook-Pro:ryujihellowebapp ryujimorita$ heroku logs 2016-10-25T18:40:40.739865+00:00 app[web.1]: hashed_name = self.stored_name(clean_name) 2016-10-25T18:40:40.739866+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/storage.py", line 280, in stored_name 2016-10-25T18:40:40.739868+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/storage.py", line 94, in hashed_name 2016-10-25T18:40:40.739868+00:00 app[web.1]: (clean_name, self)) 2016-10-25T18:40:40.739867+00:00 app[web.1]: cache_name = self.clean_name(self.hashed_name(name)) 2016-10-25T18:40:40.739870+00:00 app[web.1]: ValueError: The file 'css/style.css' could not be found with . 2016-10-25T18:49:16.277858+00:00 heroku[router]: at=info method=GET path="/" host=ryujihellowebapp.herokuapp.com request_id=b7fa0f0e-33f5-4a20-a13d-272441b50c37 fwd="173.55.124.51" dyno=web.1 connect=1ms service=91ms status=500 bytes=269 2016-10-25T18:49:16.280970+00:00 app[web.1]: ERROR:django.request:Internal Server Error: / 2016-10-25T18:49:16.280980+00:00 app[web.1]: Traceback (most recent call last): 2016-10-25T18:49:16.280982+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response 2016-10-25T18:49:16.280986+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2016-10-25T18:49:16.280987+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response 2016-10-25T18:49:16.280989+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2016-10-25T18:49:16.280989+00:00 app[web.1]: File "/app/collection/views.py", line 18, in index 2016-10-25T18:49:16.280991+00:00 app[web.1]: 'things': things, 2016-10-25T18:49:16.280992+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/shortcuts.py", line 67, in render 2016-10-25T18:49:16.280993+00:00 … -
Django/DjangoTables2/Matplotlib - Displaying an MPLD3 graph and a Django Tables in a Django template?
I'm fairly new to Django, so bear with me please. I have made two different "apps": One that makes an MPLD3 graph and one that makes a DjangoTable. My original intention was to get both on the same page using a template. However, I do not know how to make it so that both are displayed on the same webpage. In my MPLD3 urls.py, I call a method called "display", which returns an HTTP response. In my DjangoTable urls.py, I call a method called "makeTable", which returns the following line of code: render(request, 'template.html', {'HEK_Observations': models.HEK_Observations.objects.filter(noaaNmbr=noaaNmbr)}) I'm confused because my understanding is that every webpage created calls a single methods to be run. I don't know how to call two methods in urls.py to create a single webpage that displayed both. Can somebody please explain to me the best way to accomplish this? For reference, here is the condensed version of my views.py for my Django Table: from django.shortcuts import render from interactive_table import models def makeTable(request): return render(request, 'template.html', {'HEK_Observations': models.HEK_Observations.objects.filter(noaaNmbr=noaaNmbr)}) Here is the condensed version of my views.py for my MPLD3 graph: Here is my urls.py for my Django Table: from django.conf.urls import url from . import views … -
load css and js file when load a div using ajax Django
Hi everyone I am using Django CMS in my Site, I create a template for a page and now using ajax to load a index.html in a section of this template... Everything work fine ... but my index html call a style.css file and hpc.js file, that when I load by ajax I don't see its. I use this to load file in my index.html {% addtoblock "css" %} <link rel="stylesheet" type="text/css" href="{% static 'health/css/stylehealth.css' %}" /> {% endaddtoblock %} and this for my js.file {% addtoblock "js" %} <script src="{% static 'health/js/health.js' %}"></script> {% endaddtoblock %} my index.html {% load cms_tags menu_tags sekizai_tags %} {% load static %} {% block title %}{% page_attribute "page_title" %}{% endblock title %} {% block content %} {% placeholder "content" %} {% addtoblock "css" %} <link rel="stylesheet" type="text/css" href="{% static 'health/css/stylehealth.css' %}" /> {% endaddtoblock %} <div class="selector_healthApp"> <div class="selector_area"> <div class="row"> <form action="#"> {% for list in new_object_list %} <div class="col-xs-3"> <select class="form-control" id="item_project"> <option>{{ 'Select Categoty' }}</option> {% for item_list in list.select_opc %} <option value="{{ list.url }}">{{ item_list }}</option> {% endfor %} </select> </div> <div class="col-xs-3"> <input type="text" class="form-control" id="start_rank" value="{{ list.start }}" placeholder="Start Rank"> </div> <div class="col-xs-3"> <input type="text" class="form-control" id="display_count" … -
How to get admin inline name?
I have 2 inlines with the same model. class UsersInlineAdmin(GenericTabularInline): model = CTSportsToCriterias class TeamsInlineAdmin(GenericTabularInline): model = CTSportsToCriterias class CTSportsToCriterias(models.Model): user_use = models.BooleanField(verbose_name=_('is available to users?'), default=False) team_use = models.BooleanField(verbose_name=_('is available to teams?'), default=False) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() criteria_group = models.ForeignKey(CriteriaGroups, verbose_name=_('criteria group')) When I remove an item from one inline, django automatically removes this item from another inline, because according to the Django docs, the code: def save_formset(self, request, form, formset, change): for obj in formset.deleted_objects: ... provides model's object. Because in my case the model can have some options (user_use\ team_use), is it possible to get inline names in save_formset in order to do something like: if (inline_name == 'UsersInlineAdmin' and not obj.team_use) or \ (inline_name == 'TeamsInlineAdmin' and not obj.user_use): obj.delete() ? -
How to make django admin page looks better
I'm new to Django and i'm trying to add a ready template to my django admin page, the default page doesn't look good to me. I've tried some ready templates, but none worked, such as bootstrap. any help is appreciated. -
Django: How to filter users by latest update status in Twiitter-like application?
My question is simple: in a Django app, I have a table Users and a table StatusUpdates. In the StatusUpdates table, I have a column user which is a foreign key pointing back to Users. How can I do a search expressing something like: users.filter(latest_status_update.text__contains='Hello') -
Configure DDS with scrapy-splash
LS, I have installed Django-Dynamic-Scraper. And i would like to render Javascript via Splash. Therefor i have installed scrapy-splash and installed the docker splash image. The image below shows that the docker container can be reached. Splash docker container Nevertheless when i test it via DDS it returns the following error: 2016-10-25 17:06:00 [scrapy] INFO: Spider opened 2016-10-25 17:06:00 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2016-10-25 17:06:00 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023 2016-10-25 17:06:05 [scrapy] DEBUG: Crawled (200) <POST http://192.168.0.150:8050/render.html> (referer: None) 2016-10-25 17:06:06 [root] ERROR: No base objects found! 2016-10-25 17:06:06 [scrapy] INFO: Closing spider (finished) 2016-10-25 17:06:06 [scrapy] INFO: Dumping Scrapy stats: when executing: scrapy crawl my_spider -a id=1 I have configured the DDS admin page and checked the checkbox to render the javascript: Admin configuration I have followed the configuration from scrapy-splash: # ---------------------------------------------------------------------- # SPLASH SETTINGS # https://github.com/scrapy-plugins/scrapy-splash#configuration # -------------------------------------------------------------------- SPLASH_URL = 'http://192.168.0.150:8050/' DSCRAPER_SPLASH_ARGS = {'wait': 3} DOWNLOADER_MIDDLEWARES = { 'scrapy_splash.SplashCookiesMiddleware': 723, 'scrapy_splash.SplashMiddleware': 725, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, } # This middleware is needed to support cache_args feature; # it allows to save disk space by not storing duplicate Splash arguments # multiple times in a disk request … -
How can I create an API for my web app and the mobile version of that web app in python?
I'm new to the API concept.I have a doubt about the API. I created a web app in Python-django framework.I need to create an API for this web application.I need to use this same app in mobile as mobile app.How can I possible this? Can I create seperate API for the mobile app also? I searched this in google. but i can't find a correct answer.Please help me... -
django include template with cycled variable
I have a list of tasks with headers for task type groups. I'm trying to move the task row (last <tr>) into its own template: {% for task in tasks %} {% ifchanged task.task_type %} <tr> <td colspan="5"><br><h3>{{ task.task_type }}</h3></td> </tr> {% endifchanged %} <tr class="{% cycle 'active' '' as rowcolor %}"> ... </tr> {% endfor %} What I'm trying to do is replace the last <tr> with {% include '_row.html' with rowcolor="{% cycle 'active' '' %}" %} But it appears that {% %} can't be nested. Using {{ }} in the rowcolor value didn't work either. Is there some way to do this? -
Unable to post a cross origin request in Django website.
Even after installing CORS middle ware and enabling Cross Origin Requests also. I am unable to make a post request by using Javascript. const csrf = Cookies.get('csrftoken'); return { 'X-CSRFToken' : csrf, 'Access-Control-Allow-Origin':"*" "Access-Control-Allow-Headers":"Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"}; And also in Django app CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( '127.0.0.1', ) CORS_ALLOW_HEADERS = ( 'x-requested-with', 'content-type', 'accept', 'origin', 'authorization', 'x-csrftoken', 'x-api-key' ) And also after adding CORS Middleware, MIDDLEWARE_CLASSES = ('corsheaders.middleware.CorsMiddleware') -
How should I implement corporate accounts on the web-site?
I have already ready WEBsite with user authentication. I need to implement corporate accounts functional, so that users of this account can go to the link corporate_account_name.main_domain.com and saw the same site as in main_domain.com only this version especially for them. How to do it and where to dig? (or at least a list of technologies, frameworks): One code for all subdomains? Create separate database for each subdomain? At the same time you need to access data from main_domain to all subdomains and vice versa (subdomain -> main_domain). It is likely that the code may need to update the long migration of the database data. It is necessary that in this case all the subdomains not froze until the updated one of the bases. The server on apache. This restart apache every time you create a business account is not possible. Corporate accounts creates on the web interface main_domain.com (automatically), like a standard user registration. Do not manually! It is desirable for django. -
Django Rest Framework ViewSets: Include arbitrary context content in Response
How does one initialize the Response() with additional arbitrary content across all ViewSet methods, without overriding each method individually? Use Case: I would like to include arbitrary content (in this case a Form object along with the serialized results in a Rest Framework ViewSet Response. I know that if I override an individual ViewSet method (such as list) this is easy enough: def list(): serializer = FooSerializer() context = { 'form': BarForm(), 'data': serializer.data } return Response(context) I also know that I can populate the serializer with additional context using the get_serializer_context() method here class FooSerializer(serializers.ModelSerializer): ... def get_serialzier_context(self): context = {'form': BarForm()} return context And that does indeed get passed to the serializer I also know that I can override the to_representation() method on the Serializer class, and use my arbitrary context to further manipulate serialized data at the instance level, but that's not what I want. I have also explored the use of the get_renderer_context() method as described here, but that hasn't borne fruit yet. I have even looked to the rest_framework/pagination.py code, as it injects 'previous', 'next', and 'count' attributes into the context: def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) … -
ImportError: No module named 'bootstrapform'
Traceback (most recent call last): File "/home/etudiant/git/leasing/leasing/manage.py", line 10, in execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/init.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/init.py", line 312, in execute django.setup() File "/usr/local/lib/python3.5/dist-packages/django/init.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/usr/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 956, in _find_and_load_unlocked ImportError: No module named 'bootstrapform'* -
Django Aggregation in View
I would like to show the result of the query from the database on my html view. When I run my raw sql aggregate query in the Django shell, I get the result I'm looking for. My views.py and I also have the model imported def officehome(request): """Renders the office home page.""" assert isinstance(request, HttpRequest) ordersrecieved = FbsOrderT.objects.count() return render( request, 'app/officehome.html', {"ordersrecieved": ordersrecieved} ) this is in the html view <ul class="list-group"> <li class="list-group-item"> <h5 class="list-group-item-heading">Orders Received <span {ordersrecieved}</span></h5> </li> Would angular routing be a problem and not knowing when to execute the query. -
Twitter api requests after social-auth Django
I am working on simple django project to show list of followers of logged in user. I have 'Log in with Twitter' button on my page. It works correctly, user is logged in and after auth it redirect to page with 'Welcome John Doe'. I'd like to add more things to this landing page (like number of followers and followers IDs/ more info using twitter API). 'Welcome John Doe. Followers count:4. Followers screen names: abc, microsoft,john21,bill21 Right now i am just showing logged user full name. Question: How can i quickly use logged user auth token and key to send API requests to get follower ids? Or what is the easiest way to send and receive info from API using already logged in user? Only way i did Twitter api handling before was using this code: import twitter api = twitter.Api(consumer_key='consumer_key', consumer_secret='consumer_secret', access_token_key='access_token', access_token_secret='access_token_secret') but right now i don't know how extract consumer key and consumer_secret since he's authorised. Is there any way to do it? -
Webpack: Loading Codesplit Chunks from S3 Using Django Storage
I am using django storages to serve my static files from s3, and am in the process of moving them all into a webpack bundle. This works well with django-webpack-loader which doesn't care where django finds the bundle. My problem is that when I start to define split points using require.ensure, the bundle attempts to download the chunk using a relative path, instead of the s3 bucket, because webpack's codesplitting feature is agnostic to django storage. Is there a way to inject custom logic for fetching the chunks on demand? I'm not above hard coding my s3 bundle address into the config file, but nothing I've tried so far has worked. -
Django error 'tuple' object has no attribute 'get'
Here is my very first app with Django. I keep getting the error "'tuple' object has no attribute 'get'" Here is my view: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<h1>Get most recent music for your listening pleasure</h1>"), -
Django Rest Framework ModelSerializers - Handling create and update
I have some models in my Django database. Each model is created or updated through the DRF API. As a result, I have serializers (for every model) that handle the create, update and partial_update on the models. A main part of the handling includes the following action: def handle(): if created: model.owner = request.user model.other_fields = other fields model.save() else: model.other_fields = other fields model.save() Additionally, I need to create log entries whenever a model is saved, with request.user. Log.objects.create(user=request.user, model=model, created=timezone.now()) I cannot use signals to create log entries, as the post_save signal does not have the request object. How should I handle this? Should I create a custom signal and send it every time I create or update a model? Should I call a function in serializer's create and update to log the model?