Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
html file not extending
I extended the base file and the directory is correct and Iam still getting normal style. {% extends "music/base.html" %} {% block body %} {% load staticfiles %} <img src="{% static 'music/image/Robot-PNG-File.png' %}" class="rounded-circle" alt="face" style='max-height:200px'><br> <h2>{{album.album_title}}</h2> <h3>{{album.artist}}</h3> <ul> {% for songs in album.song_set.all%} <li>{{songs.song_title}}- {{songs.file_type}}</li> {% endfor %}<br> </ul> {% endblock %} -
Django Messages working only after manual page refresh when I try display error about existing user
In my Django project I want to use Django Message ( from django.contrib import messages) to display error when user or email exist. Unfortunately my views not working. HTML: {% for message in messages %} <p>{{ message }}</p> {% endfor %} views.py: def account_signup(request): if request.method == 'POST': nick = request.POST['nick'] email = request.POST['email'] password = request.POST['password'] user_model = get_user_model() if user_model.objects.filter(username__iexact=nick).exists(): messages.warning(request, 'Please correct the error below.') return render(request, "account/account_signup.html", context={'is_taken_email': email, 'messages': messages}) if user_model.objects.filter(email__iexact=email).exists(): messages.warning(request, 'Please correct the error below.') return render(request, "account/account_signup.html", context={'is_taken_email': email, 'messages': messages}) user = User.objects.create_user(username=nick, email=email, password=password) user.save() return HttpResponse(status=202) else: """Return template with sign up page.""" return render(request, "account/account_signup.html") I cant find a reason. Thanks in advance! -
Set id for None object
I have model for my comments: class Comment(models.Model): body = models.CharField(max_length=255, verbose_name="comment") message = models.ForeignKey(Message, on_delete=models.CASCADE, related_name="comments", verbose_name="message") author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="author") parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', verbose_name='parent', default=None) posted = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="posted") edited = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name="edited") def __str__(self): return self.body def get_create_url(self): return reverse('wall:add-comment', kwargs={'id': self.message.id, 'pk': self.parent.id}) def get_update_url(self): return reverse('wall:edit-comment', kwargs={'id': self.id}) I understand that my question is probably stupid, but I need to get an id for parent.id if parent is None. Help pls -
ajax + django, form with success url
I'm working on posting django form wrapped in modal using ajax. It seems that i got it working, but I'd like to ask about one thing. When I get my form and then post it I expect getting back to previous view and reloading it in order to display all operations with the newest one included. Below you can see how it looks like under the hood: [16 / Feb / 2018 12:22:52] "GET /expenses/new_operation/ HTTP/1.1" 200 1135 [16 / Feb / 2018 12:23:01] "POST /expenses/new_operation/ HTTP/1.1" 200 21 [16 / Feb / 2018 12:23:01] "GET /expenses/manage_operations/?csrfmiddlewaretoken=0wiGRic6QGlqSyVIv36f02bQ4CeJk81WfN9waSoiVrSaPPnLx1HbS0YapFypTtdk&account=1&type=-1&category=2&date=2001-11-11&amount=111 HTTP/1.1" 200 6313 What I don't get is why in GET /expenses/manage_operations/ request all the data from the previously posted form is being attached. In my view I have set success_url: class OperationCreate(CreateView, OperationMixIn): model = Operation form_class = OperationForm success_url = reverse_lazy('manage_operations') def get_form_kwargs(self): ( ... ) return kwargs def form_valid(self, form): ( ... ) if self.request.is_ajax() and self.request.POST: form.save() return JsonResponse({'result': 'success'}) return super(OperationCreate, self).form_valid(form) def form_invalid(self, form): if self.request.is_ajax() and self.request.POST: form.save() return JsonResponse({'result': 'error'}) return super(OperationCreate, self).form_invalid(form) Here is my main javascript code reposible for handling modal and new operation button: <script type="text/javascript"> $(document).ready(function () { $(document).ajaxSuccess(function () { … -
Installing Channels: Python Django version compatibility
The Django app compiles, but when I try to run it: (virtualenv) root@computer:path# python manage.py runserver 0.0.0.0:8000 It gives error: File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/channels/routing.py", line 75, in resolve_routing raise ImproperlyConfigured("Cannot import channel routing %r: %s" % (routing, e)) ImproperlyConfigured: Cannot import channel routing 'codebench.routing.channel_routing': cannot import name ProtocolTypeRouter According to this https://github.com/VincentTide/django-channels-celery-example/issues/1 It maybe related to Python version, so I did: (virtualenv) root@computer:path# alias python=python3 (virtualenv) root@computer:path# python -V Python 3.5.2 (virtualenv) root@computer:path# python manage.py runserver 0.0.0.0:8000 Traceback (most recent call last): File "manage.py", line 3, in <module> import eventlet ImportError: No module named 'eventlet' (virtualenv) root@computer:path# pip install eventlet Requirement already satisfied: eventlet in /root/.virtualenvs/codebench/lib/python2.7/site-packages Requirement already satisfied: greenlet>=0.3 in /root/.virtualenvs/codebench/lib/python2.7/site-packages (from eventlet) Requirement already satisfied: enum-compat in /root/.virtualenvs/codebench/lib/python2.7/site-packages (from eventlet) Requirement already satisfied: enum34 in /root/.virtualenvs/codebench/lib/python2.7/site-packages (from enum-compat->eventlet) Now I stuck at: ImportError: No module named 'eventlet' I have the following packages installed: channels==1.1.6 daphne==1.4.0 Django==1.9 eventlet==0.20.0 -
How to print in template something when queryset build with union() changes?
I have two queryset: q1 and q2. I make a union of them with q1.union(q2) Now, when I print in template the queryset with a for loop, how can I print something between the two querysets? Something like: Featured results (q1 forloop) Other results (q2 forloop) Why I thought to use union instead of separated querysets? Because I want only one pagination for both Thank you -
Unapply the effect of 'makemigrations' in django
Is there anyway I can unapply the effect of command python manage.py makemigrations <app>? What I was trying to do- I have 3 apps, which have models interdependent on each other(app2 depends on app1, app3 depends on app2, app1 depends on app3). So to remove the circular dependency I removed fields from app1(which depend on app3) and use python manage.py makemigrations <app> for each app separately then python manage.py migrate. Then add those dependent fields in app1 and again use the above commands to have full tables. The issue I forgot to remove the dependent fields in app1 and used makemigrations which also worked fine. But when I am using python manage.py migrate it is giving me the CircularDependency error, I want to undo the effect of makemigrations command. The are answers about removing migrations which happens when your tables are created, but in my case I am stuck before that. -
How add varriable from funсtion to modelform
I try to transfer a new variable urls from a function to a ModelForm. In the letter, the variable comes, but in the form - saving an empty string. models.py class Order(models.Model): name = models.CharField(max_length=25, verbose_name="Имя*") phone = models.CharField(max_length= 20, verbose_name="Мобильный телефон*") email = models.EmailField(max_length=25, verbose_name="Электронная почта*") text = models.TextField() urls = models.URLField() views.py def viewperson(request, slug): trainer = Trainer.objects.get(slug = slug) urls = (reverse('trainers:viewperson', args=[slug])) if request.method == 'POST': model_form = ModelOrderForm(request.POST) if model_form.is_valid(): subject = "New order" phone = model_form.cleaned_data['phone'] name = model_form.cleaned_data['name'] text = model_form.cleaned_data['text'] email = model_form.cleaned_data['email'] recipients = [mail@gmail.com'] message = name + " " +" "+ phone + " " + "site.com"+urls +" "+ text if result['success']: try: model_form.cleaned_data['urls']=urls #Here i try to send urls in forms urls-field instance = model_form.save() send_mail(subject, message, email, recipients) return redirect('thanks_for_order') except BadHeaderError: return HttpResponse('Invalid header found') else: messages.error(request, 'Error reCAPTCHA. Tray again.') return redirect('trainers:viewperson' , slug=slug) else: model_form = ModelOrderForm() return render(request, "trainer_person.html", {'trainer':trainer, 'model_form':model_form,}) -
How to make Django migrations on Google Cloud Platform?
I would like to host my app on Google App Engine and have a Google SQL instance for the database. The main part of the app is an API built with Django Rest Framework. I asked Google Cloud Support about the best practices of making migrations in production when I need to modify the database's schema. Since I am new to web development, perhaps any experts here have similar experience and can verify if the suggested process is something what I can really follow? For database migration best practice, you could create a separate development/test/backup instance of your Cloud SQL database. Let's say for example your DB instance for production is DB1, create a dev instance namely DB2 that has all the tables of DB1. After that, configure your app to point DB2 instance temporarily. Please make sure that both instances are in sync and updated. Then, deploy a new version of your app that points to DB2 so you can update DB1 (add new tables, columns) as your official database instance in the production environment. Then you can point it again to DB1 and update DB2. -
Angular 4 with Django as backend
how can we link frontend and backend of an application which will be using Angular 4 and Django. -
Using django CSRF middleware with views returning JsonResponse
I want to use CSRF middleware with API Views in Django. Here is a demo view I want to use CSRF with, I am confused how to integrate CSRF here. def login(request): try: if len(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password'])))==1: print(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password']))) return JsonResponse({'exit':'0','msg':'Success'}) return JsonResponse({'exit':'2','msg':'User Invalid'}) except Exception as e: return JsonResponse({'exit':'10','msg':'Unknown Error Occured'}) Any help or suggestions will be appreciated. Thanks. -
Djongo, put mysql object id into mongodb listfield from admin
We are using Djongo drivers for django and mongodb compatibility. We have to insert into a Mongodb document a ListField that contains multiple Mysql object pk (as integer or string), obviusly from the admin interface. There's a way? Just for info, without that ListField all work properly and the database router is configured. Thanks all EXAMPLE Mongo document: class MongoDocument(models.Model): field1 = models.CharField(unique=True, max_length=100) LISTFIELD = models.SOMETHING() field3 = models.CharField(max_length=40,unique=True,default=uuid.uuid4) fieldN = models.BooleanField(default=True) class Meta: abstract = True Mysql table: class MysqlTable(models.Model): field1 = models.DecimalField() field2 = models.CharField() field3 = models.CharField() fieldN = models.IntegerField() -
Django: TestClient, cookie detection not working, even though they are supplied
I have a view that contains the following code: language = 'nl_BE' language-cookie = self.request.COOKIES.get('PreferredLanguage') if language-cookie and language-cookie != 'nl_BE': language = 'fr-FR' (...) context['iframe_url'] = language_adapted_url_intro + language + language_adapted_url_outro I am writing tests for our program, and this is the test that is supposed to test the code above. class TestStoreListView(TestCase): def setUp(self): self.client = Client() def test_language_cookie_detection_FR(self): self.client.cookies = SimpleCookie({'Name': 'PreferredLanguage', 'Value':'fr_BE'}) response = self.client.get(reverse('store_appointment')) self.assertTrue('fr-FR' in response.context['iframe_url']) yet this test keeps failing with the following error: self.assertTrue('fr-FR' in response.context['iframe_url']) AssertionError: False is not true But how can this be? The cookie is supplied and the if/else in the view is simple enough. Other tests verify that a context['iframe_url'] is indeed returned (but with nl_NL as its 'language'. Does anyone know what I am doing wrong? -
How can I create a personal for each account in django ? Note: not in admin site
I am a beginner and still learning Django. I am wondering how can I build a personal site for each account like Facebook , Instagram, etc.Thank you very much. English is not my first language.