Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to show image path after saving a form?
I have a simple form with a CharField, ImageField and a TextField. When I enter text, pick an image and save the form like so: def item_new(request): if request.method == "POST": form = ItemForm(request.POST, request.FILES) if form.is_valid(): form.save() a new instance of my model with the image is saved. But in the form on my site it now says "no file selected" in the ImageField, whereas the entered text in the other fields is shown. So, how can I make it show the path of the selected file instead? -
how to redeploy django web app in docker, nginx with ssl without rebuilding or restarting container?
I am wondering if it's possible to redeploy django web app in docker, nginx with ssl without rebuilding or restarting container? I am kind of new to docker, however I feel the pain to use it. Docker looks over engineered, and wasted too much time to build and restart container. Can any one share the light on your experience? what is the good way to make it work. Currently I have the following container running and it works well. $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 74bf4112452a nginx_proxy "/bin/bash /start.sh…" 18 hours ago Up 18 hours 443/tcp, 8001/tcp, 0.0.0.0:11001->11001/tcp nginx_proxy-dev f91c7b12bbc1 myproject "/bin/bash run_mypro…" 18 hours ago Up 18 hours 0.0.0.0:32771->9000/tcp myproject-dev 21dbbb07384d nginx_balancer "nginx -g 'daemon of…" 18 hours ago Up 18 hours nginx_balancer-dev 31a5ee018f57 memcached "docker-entrypoint.s…" 18 hours ago Up 18 hours 11211/tcp my-memcache-dev -
How to fix Django AWS EC2 Gunicorn ExecStart ExecStop end error?
I am trying to point my AWS Route 53 Domain to my EC2 IPv4 Public IP for my Django app, but I'm running into some gunicorn issues. The strange thing is that I am getting gunicorn wsgi bind success, but yet it doesn't work. I've already created a record set on Route 53. Error: gunicorn.service: Service lacks both ExecStart= and ExecStop= setting. Refusing. See the full systemctl_status Error Settings.py: ALLOWED_HOSTS = ['174.129.45.220', 'travelbudapp.com'] Please see FULL code links as .txt files: Full gunicorn.service file Full nginx file: gunicorn_bind success: I tried to make it as convenient as possible. I really need to get this app running a.s.a.p. -
How to run code a single time on django channels server startup?
Django 1.7+ has AppConfig.ready (docs), however it seems to be running multiple times with Django Channels. How can I ensure that the code runs exactly once, even with multiple workers? I'm searching for a solution that works both with the dev server and with daphne. Here is something I want to achieve: from django.apps import AppConfig from channels import Channel class MyAppConfig(AppConfig): name = 'myapp' def ready(self): # if thisIsTheFirstWorker: Channel('mychannel').send({ 'text': 'message to be sent only once', }) -
django in one queryset all and filter methods
I trying display in django app, in view last 5 item and also this items which has is_home set on True. Please hint if this is 'nice' and correct way: My model: class Event(models.Model): title = models.CharField(max_length=500) date = models.DateField() is_home = models.BooleanField(default=False) My query in view: context['event_list'] = Event.objects.filter(Q(Event.objects.all()) | Event.objects.filter(is_home=True))[:5] -
Postgresql or mongoDB for Django
I am willing to work on a project, in which I have a database (xlsx files), and I want to migrate it to a nosql database in order to visulize the data in plots, and then integrate it in a django website using plotly to make the graphs. My question is, is it better to migrate to a nosql database knowing that files will be added daily, or just use a sql one like postgresql? And which is better to do the job, mongoDB or Postgresql ? NB : I ve read an artical about this, and it recommand NOT to use MongoDB in Django and I don't know whether to believe this or not. -
Celery Worker not Inheriting Settings from Django App
I am developing a django app that has to process large spreadsheets that users upload - so naturally I turned to celery and rabbitmq. I successfully setup the environment and the task completes in the background successfully except for one issue: I use an environment variable in a db router class to determine which database to use (i.e. production vs staging vs dev): lass DbRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'auth': return 'auth' elif model._meta.app_label == 'admin': return 'auth' elif model._meta.app_label == 'contenttypes': return 'auth' else: environment = environment = os.environ['BH_ENVIRONMENT_NAME'] if environment == "staging": return 'staging' if environment == "production": return 'production' def db_for_write(self, model, **hints): if model._meta.app_label == 'auth': return 'auth' elif model._meta.app_label == 'admin': return 'auth' elif model._meta.app_label == 'contenttypes': return 'auth' else: ########################################### #This is where django raises the exception# ########################################### environment = os.environ['BH_ENVIRONMENT_NAME'] if environment == "staging": return 'staging' if environment == "production": return 'production' def allow_migrate(self, db, app_label, model_name, **hints): return True which works just fine in the regular django thread; however, when the background task attempts to use the db router I get the following key error (which seems to imply that os.environ dictionary is not available to the worker thread?): … -
Django Admin page error with MySQL
I have some issue with connecting my Django 2.0 with MySql: When I am checking my localhost on xampp server locally, it looks data entered and connected with my project but the below is the error that showing when I want to see my admin page: ProgrammingError at /admin/ (1146, "Table 'scdemployees.django_session' doesn't exist") Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.0.2 Exception Type: ProgrammingError Exception Value: (1146, "Table 'scdemployees.django_session' doesn't exist") Exception Location: C:\Users\Janahi\venv\Django_me\lib\site-packages\MySQLdb\connections.py in query, line 277 Python Executable: C:\Users\Janahi\venv\Django_me\Scripts\python.exe Python Version: 3.6.3 Python Path: ['C:\\Users\\Janahi\\PycharmProjects\\Django_me', 'C:\\Program Files\\JetBrains\\PyCharm 2017.3\\helpers\\pycharm', 'C:\\Users\\Janahi\\PycharmProjects\\Django_me', 'C:\\Users\\Janahi\\venv\\Django_me\\Scripts\\python36.zip', 'C:\\Users\\Janahi\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs', 'C:\\Users\\Janahi\\AppData\\Local\\Programs\\Python\\Python36-32\\lib', 'C:\\Users\\Janahi\\AppData\\Local\\Programs\\Python\\Python36-32', 'C:\\Users\\Janahi\\venv\\Django_me', 'C:\\Users\\Janahi\\venv\\Django_me\\lib\\site-packages', 'C:\\Users\\Janahi\\venv\\Django_me\\lib\\site-packages\\setuptools-28.8.0-py3.6.egg', 'C:\\Users\\Janahi\\venv\\Django_me\\lib\\site-packages\\pip-9.0.1-py3.6.egg'] Server time: Fri, 16 Feb 2018 15:04:28 +0000 -
Adding header with value django cores
According to the django-cores documentation in order to add custom headers you add: CORS_ALLOW_HEADERS = default_headers + ('my-custom-header',) To your settings.py, question is how do you add my-custom-header along with it's value to settings.py. -
Should I go with Django/mongoDB or PHP (Laravel) /mongoDB or any other languages?
I need to create a scalable backed system for my sales team that have more than 50 millions data. Also having multiple heavy (8 million) csv operations (upload). Should I go with Django/mongoDB or PHP (Laravel) /mongoDB or any other languages? -
Django 1.11.9 and PosgreSQL10 on Docker makes duplicated tables
Today I got a weird behaviour. I am not sure this problem comes from AWS EC2 or Django itself. Today AWS shows me significant lack and poor performance. I use PostgreSQL10 on Docker And what should I do with replicated tables? I can not Drop it. I had tried. -
AJAX DJango Get files from multiple file field
I'm doing multiple file upload with AJAX and DJango and I have problem. How to get files from field input and push them to data ? HTML: <form id="add_photos" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file[]" multiple id="files"> <input type="submit" name="submit" value="Submit" /> </form> JS: function formSubmit(e) { e.preventDefault(); $.ajax({ method: 'POST', data: form.serialize(), url: '.', success: function(data) { console.log(data); }, error: function (data) { console.log(data); } }); } -
Ajax POST request from Chrome extension to django fails with 400
I have a Django REST API running on Nginx + Gunicorn on my server (an AWS instance) and I'm trying to call this API from a Chrome extension using Ajax. I can't make it work. The API itself seems to work fine – I can make a similar request with cURL and it works fine. However, when I try to do it from the extension, I'm getting 400 error. There is no authentication at the moment, both the website from which I'm calling and the Django app run on https (at first I thought this might be a problem), I added both of them to permissions in manifest.json. My call (from background.js) looks like this: $.ajax({ type: "POST", crossDomain: true, cache: false, url: 'https://**************/', data: JSON.stringify(collectedData), success: function(data, textStatus, xhr) { collectedData = []; server_response = xhr.status; }, error: function(xhr, textStatus, error) { server_response = xhr.status; }, dataType: "json" }).always(function(){ sendResponse({ status: server_response }); }); I'm running out of ideas. What am I doing wrong? -
400: Bad Request when retrieving Request Token from Twitter API
I'm working on a Django application which retrieves some data from Twitter, and I need to work with requests manually since it's for an exam whose main focus is for us to learn how to work with network protocols such as HTTP. So please don't suggest me to use a wrapper. My issue is that whenever I try to request the initial request token (with a POST request that is referenced in this doc and also here), I receive a 400: Bad Request and I have no clue what could be causing it. It may be that while working with urllib I don't manage to make the POST request as I wanted, even though in my opinion it should be alright. Here's my code to handle the request to "sign in with Twitter": def sign(request): url = 'https://api.twitter.com/oauth/request_token' #I store consumer key, consumer secret and callback url in a txt dir_path = path.dirname(path.realpath(__file__)) with open(path.join(dir_path, 'credentials.txt'), 'r') as TweetCred: creds = TweetCred.read().split(linesep) oauth_consumer_key = creds[0].split()[1] oauth_callback = creds[1].split()[1] consumer_secret = creds[2].split()[1] oauth_nonce = ''.join(SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(32)) #Desperate to understand what could be causing the error, I tried to use an integer timestamp sinceit was integer in … -
Dynamic GET Request with Ajax and Django
I'm fairly new to using Ajax however have been using Django for a while now. I'm wondering how I can submit a form dynamically which will - without refreshing the page - append this new 'parameter' to the URL and return some updated data. For example, if I change a value called maximum price and click 'Apply' then this will add '&max_price=some_new_value' to the URL and return the a Django queryset with the filter of maximum price. I've been able to start like this... $('.filter-ul-opt-change-apply').click(function(){ $.get(...{ ... }) }) although the jQuery documentation specifies that a URL like ajax/test.html be passed as an argument into the get() method, but I'm unsure how this will work with a Django view to retrieve objects. views.py: def generic_view(request): objs = Objects.objects.filter(...parameters from updated url go here...) return render(request, 'generic-view.html', {'objs':objs}) Any ideas on using Django and Ajax for this purpose would be really useful! Thanks! -
Add 'auto_now' DateTimeField to existing Django model
Is it possible to add to existing model auto_now and auto_now_add DateTime fields? class ExistingModel(models.Model): # ... model stuff created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) We can't add this fields without default, but adding the default value gives an error: ./manage.py makemigrations returns: (fields.E160) The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may be present. -
Writing "PATH" in Python instead of "URL"
I just updated my Django from 1.11 to 2.0, and now I want to write my URL according to new feature in Django 2.0, path, Thanks and regards, This is my urls.py in my app, from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$', views.register, name='register'), url(r'^login_user/$', views.login_user, name='login_user'), url(r'^logout_user/$', views.logout_user, name='logout_user'), url(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<song_id>[0-9]+)/favorite/$', views.favorite, name='favorite'), url(r'^songs/(?P<filter_by>[a-zA_Z]+)/$', views.songs, name='songs'), url(r'^create_album/$', views.create_album, name='create_album'), url(r'^(?P<album_id>[0-9]+)/create_song/$', views.create_song, name='create_song'), url(r'^(?P<album_id>[0-9]+)/delete_song/(?P<song_id>[0-9]+)/$', views.delete_song, name='delete_song'), url(r'^(?P<album_id>[0-9]+)/favorite_album/$', views.favorite_album, name='favorite_album'), url(r'^(?P<album_id>[0-9]+)/delete_album/$', views.delete_album, name='delete_album'), ] -
FileNotFoundError Django on Apache(File Upload) urgent
I'm trying to upload files in my development server, but can't make it work.. keep getting FileNotFoundError at /select_text [Errno 2] No such file or directory: '/home/metis/public_html/AGATA\\media\\dados_petroleo.txt' Request Method: POST Request URL: http://agata.pgie.ufrgs.br/select_text Django Version: 2.0.1 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: '/home/metis/public_html/AGATA\\media\\dados_petroleo.txt' Exception Location: /home/metis/public_html/AGATA/textMining/TextMining.py in separete_file_sentences, line 30 Python Executable: /usr/bin/python3 Python Version: 3.4.3 Python Path: ['/home/metis/public_html/AGATA', '/home/metis/public_html/AGATA/agataenv/lib/python3.4', '/home/metis/public_html/AGATA/agataenv/lib/python3.4/plat-x86_64-linux-gnu', '/home/metis/public_html/AGATA/agataenv/lib/python3.4/lib-dynload', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/home/metis/public_html/AGATA/agataenv/lib/python3.4/site-packages'] Server time: Fri, 16 Feb 2018 13:19:48 +0000 Perhaps it's on /home/metis/public_html/AGATA\\media\\dados_petroleo.txt' , that should be /home/metis/public_html/AGATA/media/dados_petroleo.txt , but it's using \\ ...what's going on? settings.py: STATIC_PATH = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' # You may find this is already defined as such. STATIC_ROOT = '/home/metis/public_html/static' STATICFILES_DIRS = ( STATIC_PATH, ) MEDIA_ROOT = '/home/metis/public_html/media' MEDIA_URL = '/media/' please help..I need to make this work asap ;/ -
Django + Celery + Pytest - Pytest.celery.worker not working
I have a project setup with: Django 1.8 Celery 4.1 Pytest with Celery fixtures I´m trying to create a test where I can assert a certain task is consumed by a worker but apparently the worker never consume the task unless I explicitly call it´s start() method: import pytest from exchangesm9.celery_task import app, treat_ticket_callback @pytest.fixture(scope='session') def celery_app(): return app @pytest.fixture(scope='session') def celery_worker_parameters(): return { 'queues': ('treat-ticket-callback', ), } def test_treat_ticket_callback_is_serialized_and_dispatch_to_worker( celery_worker, celery_app): ticket_callback = { 'external_ticket_code': 4098, 'status': { 'id': TICKET_STATUS_ERROR } } ref_num = ticket_callback['external_ticket_code'] task_info = treat_ticket_callback.delay(ticket_callback) At this point the task will keep on state PENDING unless I explicitly invoke worker.start(), which will make the worker consume the task in the current thread, blocking the entire process. The only way to 'unblock' it is using ctrl + c. As celery states: celery_worker - Embed live worker. This fixture starts a Celery worker instance that you can use for integration tests. The worker will be started in a separate thread and will be shutdown as soon as the test returns. So how should I configure the worker to automatically consume my task on the separated thread instead of manually calling start() and blocking my process ? -
error Bad Request (400), when I go to the site on the domain
I started the django project on digitalocean.com. The problem is that on my ip address my site is loaded and there are no problems, but if I go through the domain, the "Bad Request error (400)". Domain bought at godaddy.com. Domain settings are correct in accordance with the hosting tutorial https://www.digitalocean.com/community/tutorials/how-to-point-to-digitalocean-nameservers-from-common-domain-registrars: ns1.digitalocean.com ns2.digitalocean.com ns3.digitalocean.com Configuring nginx: upstream bbb_app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/webapps/bbb/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name example.ru; client_max_body_size 4G; access_log /webapps/bbb/logs/nginx-access.log; error_log /webapps/bbb/logs/nginx-error.log; location /static/ { alias /webapps/bbb/static/; } location /media/ { alias /webapps/bbb/media/; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS, this helps Rack # set the proper protocol for doing redirects: # proxy_set_header X-Forwarded-Proto https; # pass the Host: header from the client right along so redirects # can be set properly within the Rack application proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # … -
How to predict Disease by giving input individually by patient in R, Python, Django , HTML using Naive bays and ID3 Algorithm?
How to predict Disease by giving input individually by patient in R, Python, Django , HTML using Naive bays and ID3 Algorithm? -
Creating a popup form in django
My django application has 4 buttons where each button opens a popup form upon clicking that button. After filling that popup form, my button should have right mark on it so that user can get to know that it is completed. Below these four buttons, i have submit button which posts all these forms details to database. I can make a popup with modal in bootstrap. but i want this button to be clicked or set right mark on button after completing that popup form. I am confused on how to achieve this with django or bootstrap? And also, do i have to create a separate view for every popup form in my django views.py file? and how does that button store form values so that it will post these values upon clicking submit button? -
some uwsgi processes do not reload django application (ansible, nginx, supervisor, uwsgi, django)
Situation: I would like to deploy our Django project's code changes to the stage or production server. For this we have an ansible deployment script, that pulls the django project's code from gitlab, migrates the database, collects the static files, restarts the different servers, etc. Problem: Some uwsgi processes (1 out of 10 on average) do not reload my django application when I deploy via the ansible script. I can reproduce this for example after the static assets change after a code update and the static assets bundle's file name hashes changes. The server then throws a 500 error because uwsgi still tries to load the bundle with the old hash (via https://github.com/ezhome/django-webpack-loader). When I refresh the page of the project in the browser, then the server returns a 500 error in about 10 - 20% of the requests. relevant nginx config location / { {% if nginx_site_basic_auth %} auth_basic "Test Server what.digital"; auth_basic_user_file "{{ project_root}}/nginx_passwdfile"; {% endif %} uwsgi_pass {{ project_name }}_server; uwsgi_read_timeout 1800s; include /etc/nginx/uwsgi_params; } uwsgi config (app.ini) # uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = {{ project_root }} # Django's wsgi file module = {{ project_django_wsgi }} plugins = … -
Unable to run an individual test with Django 1.8
Having followed the advice in these two answers, I'm still unable to run only a single django test in the way it describes. I can run them all, but that takes a long time and makes debugging harder. My project structure looks like this: mainapp/mainapp/users/ ├── __init__.py ├── tests │ ├── __init__.py │ ├── test_views.py └── views.py For example, when the whole test suite is run, one of the failing tests gives this output: FAIL: test_changepassword (mainapp.users.tests.test_views.ChangePasswordTest) But when I try to run that Django TestCase with either the Django... ~/mainapp$ python manage.py test mainapp.users.tests.test_views.ChangePasswordTest File "/usr/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName parent, obj = obj, getattr(obj, part) AttributeError: 'module' object has no attribute 'test_views' or django-nose syntax... ~/mainapp$ python manage.py test mainapp.users.tests.test_views:ChangePasswordTest File "/usr/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName parent, obj = obj, getattr(obj, part) AttributeError: 'module' object has no attribute 'test_views:ChangePasswordTest' When I run this in PyCharmCE debug mode it confirms that the module object has no attributes, but I don't know why. I have django-nose (1.4.5) installed and it's in my INSTALLED_APPS, but I don't know if anything else is required to use it. This works fine down to a certain level. For example this is OK: ~/mainapp$ python … -
dIjango-websocket-redis Module Error on Installation
When I run django server, It says "ModuleNotFoundError: No module named 'ws4redis'". When I try to install ws4redis using the PIP command, I says syntax error. pip install django-websocket-redis Here is the tracebacks of the errors: Collecting django-websocket-redis Using cached django-websocket-redis-0.5.1.tar.gz Exception: Traceback (most recent call last): File "/anaconda3/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/anaconda3/lib/python3.6/site-packages/pip/commands/install.py", line 335, in run wb.build(autobuilding=True) File "/anaconda3/lib/python3.6/site-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/anaconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/anaconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 634, in _prepare_file abstract_dist.prep_for_dist() File "/anaconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 129, in prep_for_dist self.req_to_install.run_egg_info() File "/anaconda3/lib/python3.6/site-packages/pip/req/req_install.py", line 412, in run_egg_info self.setup_py, self.name, File "/anaconda3/lib/python3.6/site-packages/pip/req/req_install.py", line 387, in setup_py import setuptools # noqa File "/Users/ranjan/.local/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg/setuptools/__init__.py", line 2, in <module> from setuptools.extension import Extension, Library File "/Users/ranjan/.local/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg/setuptools/extension.py", line 5, in <module> from setuptools.dist import _get_unpatched File "/Users/ranjan/.local/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg/setuptools/dist.py", line 103 except ValueError, e: ^ SyntaxError: invalid syntax