Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does Django execute all the python files in its project directory?
I'm not sure what the best way of phrasing this question, but I am noticing that if I have say this file in the project directory: a.py class A: pass print("hello") The print statement gets called. What is happening and what is triggering it? Is this part of the class indexing that needs to be done or how is this working? -
Which type of field should I take for likes model in django, Foreign key or ManyToManyField
class Like(models.Model): user = models.ForeignKey(User) picture = models.ForeignKey(Picture) created = models.DateTimeField(auto_now_add=True) Or class Like(models.Model): user = models.ManyToManyField(User) picture = models.ManyToManyField(Picture) created = models.DateTimeField(auto_now_add=True) And please explain why in either case -
Using Google BigQuery as a backend for Django
I am considering using Google BigQuery as a back-end for Django but cannot be certain if this is possible, and if it is, what settings would apply. Currently, my Django application uses Postgresql, and the code in settings.py is as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } Ideally, I'd like to setup a database connection to Google BigQuery through settings.py and then use views and models as usual. -
Sphinx: runtime error django 1.9
Currently I'm using Django 1.9 and Django Rest Framework. I'm attempting to use Sphinx and it's autodoc functions, but I'm hitting an error on make html. The models.py does not import. myapp/ manage.py index.rst myapp/ __init__.py settings.py users/ models.py source/ modules.rst users.rst settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'myapp', 'users', ) and the error I get is: WARNING: /home/sestrella/Devel/leroi-angular/source/customers.rst:10: (WARNING/2) autodoc: failed to import module u'users.models'; the following exception was raised: Traceback (most recent call last): File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/sphinx/ext/autodoc.py", line 657, in import_object __import__(self.modname) File "/home/me/Devel/myapp/users/models.py", line 3, in <module> from django.contrib.auth.models import User, Group File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/contrib/auth/models.py", line 6, in <module> from django.contrib.contenttypes.models import ContentType File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 161, in <module> class ContentType(models.Model): File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/db/models/base.py", line 112, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. /home/me/Devel/myapp/source/modules.rst:4: WARNING: toctree contains reference to nonexisting document u'source/ users' modules.rst myapp ============= .. toctree:: :maxdepth: 4 users and users.rst users ================ Modules ---------- users.models ---------------------- .. automodule:: users.models :members: :undoc-members: :show-inheritance: Why does the users.models fail to import? I do use the ContentType model in my users.models as a generic relation. -
django form wizard with file upload multiple not working
I am currently digging into django form wizards and I am trying to upload multiple images. Unfortunately, the BaseStorage provided by django form wizard does not handle multiple files. It always assumes a dictionary to be passed. There is a fix posted here: https://github.com/django/django-formtools/issues/98?_pjax=%23js-repo-pjax-container The problem is now, that the posted code breaks in the render_done step of the form wizard when the form_obj is reevaluated. FileFields do not validate when the file is turned from dict to a list. Can anybody point me in the correct direction on how to fix this? How do generic views deal with this issue? Or don't they have this issue at all? -
Django blocktrans with variable
I have a template, in which I want to translate a string. {% blocktrans with "www.mywebsite.com" as website_name %}footer-slogan{{ website_name }}{% endblocktrans %} I've generated my po file, in which I've translated the string as follow : msgid "footer-slogan %(website_name)s" msgstr "This is a test %(website_name)s" On my generated html file, I get this untranslated element : footer-slogan www.mywebsite.com If I remove the variable from the translated string, it works : msgid "footer-slogan %(website_name)s" msgstr "This is a test" I've even tried to remove the variable from the source translation but keeping the variable in the translated string, the issue is the same : template.html {% blocktrans with "www.mywebsite.com" as website_name %}footer-slogan{% endblocktrans %} django.po msgid "footer-slogan" msgstr "This is a test %(website_name)s" I'd prefer to be able to set the variable only on the translated string. What I'm doing wrong on the translated string? -
Django load static in development directly from static folder (Not from apps)
I use django for the backend, in the frontend I use vue.js, so 99% of my CSS it's handled by vue.js, however I need a simple base.css for some customization in the landingpage and few things like this. Normally in django I would put the file inside app/static/app/base.css then do collectstatic and get it under static/app/ for production. I would like to avoid to keep it under an app as it's just a file. I'm trying adding a folder under my main "static" folder. But it seems in development django in not fetching it at all, it fetches directly and only static files from apps. How can I tell django to fetch it directly from the static main folder as it would do in production? i.e. I want to add a folder called main in my root (where manage.py is) and use only that to store my static files for both production and development, without passing through the single apps. -
Javascipt Library to use drag and drop functionalities
I am new to learning HTML, CSS and Javascript. I really need help with the following more from how to approach the problem. I am looking out for a library that can help me with the drop and drag functionality to create the flow into my system like something similar to http://interactjs.io/ . Are there any better libraries as well that help me define the connections? Once I have designed a process for the connections, I want to create the execute routine to process the calculations in the sequential order using python. What would be the best way to store the order of the calculations that I should store in the system? Should I store in the database or create a linked list for every object? -
nginx won't response to some ports
my problem is that I can not add another port to my existing nginx config! I have disabled the firewall on the ubuntu server with this command: sudo service ufw stop in sites-available I have this file named file.conf: server { listen 80; server_name example.com example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/project; } location /files/ { root /home/user/download/; } } server{ listen 8080; server_name example.com www.example.com; location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/project.sock; } } server{ listen 8001; server_name example.com www.example.com; location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/project.sock; } } I had the 8080 part earlier and this worked in past and now! but 8001 is not working! I disabled the firewall so it shouldn't be it! I also ran this command: sudo netstat -napl | grep 8001 which returned this: tcp 0 0 0.0.0.0:8001 0.0.0.0:* LISTEN 3475/nginx -g daemo thanks for your help and support -
How to create a django project in ubuntu
I'm following a tutorial on Django and I'm suppose to create a folder in Ubuntu in terminal $ django-admin startproject mysite This above line shows "Cannot find installed version of python-django or python3-django." After installing all the required stuffs. -
Rendering django tag in HTML not working
Hi guys I am trying to make my HTML work but it seems that I do not get something. My HTML is the following: {% extends 'base.html' %} {% block body %} <div class="container"> <div class="jumbotron"> <h2>Welcome to your Project {{ project.name }} Detail page</h2> </div> {% if not project.team_id and project.team_id.members.count() == 0 %} <div class="invite-teammembers"> <div class="jumbotron"> <div class="jumbo-text"> <h3>The team {{ project.team_id }} has beed created, we now need to add TeamMembers</h3> </div> <div class="jumbo-button"> <a href="{% url 'registration:team_register3' %}" class="btn btn-success" role="button"><span class="glyphicon glyphicon-plus"></span> Add Team Members</a> </div> </div> </div> {% elif project.team_id == None %} <div class="invite-team"> <div class="jumbotron"> <div class="jumbo-text"> <h3>Your project has been created, It is time to link a team or create a new for your project</h3> </div> <div class="jumbo-button"> <a href="{% url 'website:link_team'%}" class="btn btn-default" role="button"><span class="glyphicon glyphicon-link"></span> Link an existing team</a> <a href="{% url 'website:add_team' %}" class="btn btn-success" role="button"><span class="glyphicon glyphicon-plus"></span> Create a new team</a> </div> </div> {% else project.team_id.members.count() > 0 %} <h1>Youhouu</h1> {% endif %} </div> </div> {% endblock%} my HTML is not rendering like it is supposed to be I get : Could not parse the remainder: '()' from 'project.team_id.members .count()' the thing is using the shell … -
How to add click event on django-chatit chart
I have created a chart using django-chartit library. Once the chart it shown, I want a click action on my chart, upon which chart get enlarge. How can I do this. Moreover: it there any tutorial available to customize django-chartit charts? -
Celery can't autodiscover tasks
I can't figure out why Celery doesn't autodiscover tasks in Django apps (app called engine). The only discovered task is debug_task inside celery.py Celery v: v4.1.0 stilio/settings.py: ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', 'stilio_auth', 'engine', 'django_extensions' ] ... stilio/__init__.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] stilio/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stilio.settings') app = Celery('stilio') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) engine/tasks.py: from datetime import timedelta from celery.app import shared_task from celery.task import periodic_task, task from utils import SpiderSupervisor @shared_task def tasks(): return @periodic_task(run_every=timedelta(minutes=1)) def ping_spider(): SpiderSupervisor().check() Do you have any ideas where is the problem? -
Django ERROR (EXTERNAL IP): Internal Server Error: /u/1/
I'm having the following issue, but I suspect that it is a configuration issue. The DJANGO app I'm using is open source (from GitHub). The serving components are DJANGO, NGINX and GUNICORN. Clicking on a user-profile page of the site produces the following web page error (all other site links appear fine -- no issues): Internal Error! Sorry about that. A detailed error report has been generated and has been sent to the managers. If the problem persists please contact the site owners. Underneath the covers, it looks like an error email is also constructed with the following subject: [Django] ERROR (EXTERNAL IP): Internal Server Error: /u/1/ Again, I haven't run into any other site link that produce this issue (but I am just starting with this). Looking at the logs, here is more information (where I substituted in example.com and 93.184.216.34 for the actual host/domain name and IP address), Both the host/domain name and it's IP address are specified in NGINX as well as in ALLOWED_HOSTS (live.deploy settings file). gunicorn uses a UNIX DOMAIN SOCKET to communicate with NGINX. MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Subject: [Django] ERROR (EXTERNAL IP): Internal Server Error: /u/1/ From: noreply@lvh.me To: admin@lvh.me … -
Django squash or eliminate migrations on production
I have an app on production. It has 251 migrations that take too much time when I run the tests, it is making development really slow. I need to do something about this and I'd like an advice. Is it recommendable to squash the 251 migrations? what if I erase then and then just fake initial? of course, I can't lose or change the database, it is on production. Thanks a lot for your help. -
Gunicorn does not work when try to launch Django application
I am following this tutorial, until up to this part. start.sh #!/bin/bash # Start Gunicorn processes echo Starting Gunicorn. exec gunicorn helloworld.wsgi:application \ --bind 0.0.0.0:8000 \ --workers 3 My directories is like this. awesome_app -awesome_app --__init__.py --celery.py --settings.py --urls.py --wsgi.py -awesome_app_to_do_list --a lot of stuffs here -manage.py -start.sh Here is the content of my wsgi.py. """ WSGI config for airport project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "airport.settings") application = get_wsgi_application() I adapted the launch code to this. #!/bin/bash # Start Gunicorn processes echo starting gunicorn exec gunicorn awesome_app.wsgi:application \ --bind 0.0.0.0:8080 \ --workers 3 After I make it executable and run the script from the root of the project awesome_app and not from awesome_app/awesome_app. I received this error, ImportError: No module named 'myproject'. I have looked at this SO discussion, but the error is still there. What should I do? -
Django - Oracle, How to connect to readonly db with user/pass provided for the User
I need to connect Django with a read-only Oracle database. The user and password to connect to that db is going to be provided by the User in a web form. Any hint to do that? Thanks is advance. -
Django filter based in joined table
I have two tables: class Client(models.Model): name = models.TextField() lastname = models.TextField() class Meta: managed = False db_table = 'client' class Clientreport(models.Model): id_client_home = models.ForeignKey('Client', models.DO_NOTHING, db_column='id_client_home', related_name='home_id_client_home') id_client_reported = models.ForeignKey('Client', models.DO_NOTHING, db_column='id_client_reported', related_name='client_id_client_home') class Meta: managed = False db_table = 'clientreport' And I'm trying to build a query similar to this: SELECT cr.*, cl.id, cl.name, cl.lastname FROM Clientreport cr INNER JOIN Client cl ON cr.id_client_reported = cl.id WHERE (LOWER(cl.name) LIKE LOWER('%jo%') OR LOWER(cl.lastname) LIKE LOWER('%jo%') ) I tried using: SQL queries But, now I'm trying to do it using django. How I can access to a joined model using django??? -
AttributeError: 'StatisticsSubmitView' object has no attribute 'request'
class StatisticsIndexView(StaffRestrictedMixin, TemplateView): model = Statistics() template_name = 'loanwolf/statistics/index.html' form_class = StatisticsBaseForm() def get_context_data(self, **kwargs): context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ ... 'statisticaltools': StatisticsSubmitView(), }) return context class StatisticsSubmitView(StatisticsIndexView): ... I would like to access the request (self.request) from StatisticsIndexView inside StatisticsSubmitView. I made the mistake of trying self.request.GET[...] inside StatisticsSubmitView. How could I do such thing? -
How to filter BooleanField in template in Django?
I am preparing a image gallery for my website using Django . I have basically a Gallery Model Foreign Key in my Image Model. I have a BooleanField in my Image model to make a cover photo. What I need is to get True value for the one in between images. {% for gallery in gallery_list %} <div class="grid-item {{ choices | random }}"> <a href="#" data-background="{{gallery.images}}#howtofilter?#" data-rel="lightcase:gal" title="Image Caption"></a> </div> {% endfor %} I checked the documents for custom filters trying to solve but I could not figure out. Can you help me ? Thanks -
django admin filter forein key model when creating
I have 2 models, one is fk of another. I want when creating model filter fk on username creating. I know how to do this in sql, but don't understand how to do in django. I thought about api, am I right? Or I can do it in models or admin interface? class Post_links( models.Model): post_id = ParentalKey('Post') username_can_see=models.CharField(max_length=30, default='') class Post( models.Model): some_link =models.CharField(max_length=50, default='') now on creating new post when I ll check links I want to see only the links can see current user. How can I write this& -
Django view adding parameter to response does not serialize correctly
I am following this tutorial, I tried to add a simple database call to return the number of Snippet objects. Python runs the server fine but says: System check identified 1 issue (0 silenced). Whhat is wrong with the line of code I added? @api_view(['GET']) def api_root(request, format=None): return Response({ 'users': reverse('user-list', request=request, format=format), 'snippets': reverse('snippet-list', request=request, format=format), #My example of db query 'num_snippets': len(Snippet.objects.all()) }) -
Running Python directly is much faster compared to when Django runs python
So I have a SQL query that takes really long to load using Django, 10000 rows takes about 30 seconds. If I run the exact same code directly using python it does this in 2 seconds. For some reason, the loop I built takes really long to execute when Django runs the code, does anyone know why that is? Can I do something to increase the performance and get rid of this inconvenience? -
Django form Data Retaliate and Display
I am getting this type of data in my template file , from forms.py . Now I want to get only data of sql_name field which is u'ag_pres . So how I can get this data ? kindly before down vote let me know what I am doing wrong ? <type 'list'>: [{'sql_name': u'ag_pres', 'type': 'string', 'name': u'Ag Pres', 'map_order': 0}, {'sql_name': u'abc', 'type': 'string', 'name': u'ABC', 'map_order': 0}] -
dump CSV file from Django query to Github
We want to automate a process through django admin where, whenever a user makes a change to a record (or adds/deletes a record), a CSV file is created and then dumped into a Github repository with a commit message specified by the person who made the change. Creating the csv file from a queryset is easy enough... But how would we go about then getting that csv file to a folder that is git initialized so that we can commit it to a repository? Any ideas would be great. Essentially we're looking for a way of tracking specific changes to the database. With CSV files in github, we can really easily follow the changes, and we want to leverage that. cheers