Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker-compose connection refused from celery
I am running docker-compose to bring together django, celery, postgres and rabbitmq, with the following docker-compose.yml version: '2' services: # PostgreSQL database db: image: postgres:9.4 hostname: db environment: - POSTGRES_USER=<XXX> - POSTGRES_PASSWORD=<XXX> - POSTGRES_DB=<XXX> ports: - "5431:5432" rabbit: hostname: rabbit image: rabbitmq:3-management environment: - RABBITMQ_DEFAULT_USER=<XXX> - RABBITMQ_DEFAULT_PASS=<XXX> ports: - "5672:5672" - "15672:15672" # Django web server web: build: context: . dockerfile: Dockerfile hostname: web command: /srv/www/run_web.sh volumes: - .:/srv/www ports: - "8000:8000" links: - db - rabbit depends_on: - db # Celery worker worker: hostname: celery build: context: . dockerfile: Dockerfile command: /srv/www/run_celery.sh volumes: - .:/srv/www links: - db - rabbit depends_on: - rabbit In one of the Django views I delegate out to a celery task which does some processing and then tries to post the results to another web service: #views.py @csrf_exempt def process_data(request): if request.method == 'POST': # #Processing to retrieve data here # delegate_celery_task.delay(data) return HttpResponse(status=200) #tasks.py @app.task def delegate_celery_task(in_data): from extractorService.settings import MASTER_NODE import json import urllib # #Some processing on in_data here to give out_data # data = {'data': out_data} params = json.dumps(data).encode('utf8') req = urllib.request.Request('http://%s/api/data/'%(MASTER_NODE), data=params, headers={'content-type': 'application/json'}) urllib.request.urlopen(req) For now MASTER_NODE is simply localhost:8001 where I am running the other web service. … -
Adding Placeholder text to Django Form Input Field
thank you so much in advance for taking the time to help me with this. Im newer to python/django and am having SO MUCH FUN learning this powerful language/framework. Having said that, i am trying to build a registration form that will allow users to register to the application and once registered, it will direct them to the user dashboard page. My code is as follows and i am still not seeing a placeholder. Is it best practice to do this as a templatetag or to do it inside the form view? views.py class RegistrationFormView(View): form_class = RegistrationForm template_name = 'registration/registration_form.html' # display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # cleaned (normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() # returns User objects if credentials are correcot user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('/dashboard/') return render_to_response('registration/registration_form.html', c, context_instance=RequestContext(request)) forms.py class RegistrationForm(forms.ModelForm): email = forms.EmailField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Email Address', 'required':True})) username = forms.CharField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Username','required':True})) password = forms.CharField(max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Password','required':True})) password2 = forms.CharField(max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Re-Enter Password','required':True})) class Meta: """The model … -
JavaScript function not updating value of variable
I have the following JavaScript function in the HTML file for one of my webpages: $('#id_date_received').on('change', function messageDepositPaid(){ if (window.confirm("Would you like to send an email confirming we have received a deposit?")) { console.log("'if(window.confirm)' statement entered in concept.html JS... ") var date = $(this).val() if (date){ date = date.split('/') var new_date = []; new_date = new_date.concat(date[2]).concat(date[1]).concat(date[0]); new_date = new_date.join('-'); } if (new_date != $(this).data('original-value')){ // CDI fee date has been changed from nothing to something console.log("It's changed") // Set the original-value so it won't send multiple times $(this).data('original-value', new_date) // Send email to relevant people var url="{% url 'comms:open_email_template' project.id %}?template=5" console.log('Url', url) $.post(url) .done(function(response){ console.log('Email sent') }) } } /*} */ else{ console.log("'else' of 'if(window.confirm)' statement entered in concept.html JS... ") var date = $(this).val() if (date){ date = date.split('/') var new_date = []; new_date = new_date.concat(date[2]).concat(date[1]).concat(date[0]); new_date = new_date.join('-'); console.log("Value of date in if(date): ", date) } if (new_date != $(this).data('original-value')){ // CDI fee date has been changed from nothing to something console.log("Value of new_date: ", new_date) console.log("Value of original-value: ", this.data) console.log("It's changed") // Set the original-value so it won't send multiple times $(this).data('original-value', new_date) id_date_received = new_date console.log("Value of id_date_received: ", id_date_received) date_received = new_date console.log("value … -
Django migrate django.db.utils.OperationalError: no such table:
Every time i try to migrate my DB in Django i get the following error: django.db.utils.OperationalError: no such table: api_patients However i do have the patients table in my models: # Create your models here class patients(models.Model): first_name = models.CharField(max_length = 255) last_name = models.CharField(max_length = 255) dob = models.DateField(datetime.date.today) gender = models.CharField(max_length = 1) def __unicode__(self): return self.id Here is my views.py (where i think the error is): from django.shortcuts import render from rest_framework import viewsets from api.models import patients from api.serializers import PatientsSerializer # Create your views here. def home(request): return render(request, 'index.html') class PatientsViewSet(viewsets.ModelViewSet): queryset = patients.objects.all() serializer_class = PatientsSerializer -
django celery Received unregistered task of type 'print_test'
In continuity with the question: celery periodic tasks not executing I have set up django with celery like: drf_project/drf_project/celery.py from __future__ import absolute_import, unicode_literals from celery import Celery import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'drf_project.settings') app = Celery('drf_project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() In drf_project/drf_project/init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] drf_project/user_management/tasks.py from drf_project.celery import app from time import strftime @app.task def print_test(): print strftime('%Y-%m-%d %H:%M:%S') with open('abc.txt', 'ab+') as test_file: test_file.writeline(strftime('%Y-%m-%d %H:%M:%S')) In drf_project/drf_project/settings.py INSTALLED_APPS += ('django_celery_beat',) CELERYBEAT_SCHEDULE = { "test_1": { "task": "tasks.print_test", "schedule": timedelta(seconds=2), }, } I ran both celery worker and beat in different terminals with commands: celery -A drf_project worker -l info -E and celery -A drf_project beat -l info -S django The beat is sending tasks to worker every 2 seconds like: [2016-11-28 12:25:19,314: INFO/MainProcess] Scheduler: Sending due task Importing contacts (print_test) But the worker throws the error like: [2016-11-28 12:24:57,551: ERROR/MainProcess] Received unregistered task of type 'print_test'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: u'[[], {}, {"chord": null, "callbacks": null, … -
Django Reverse accessor error
I dont understand why some fields of my models clash. I dont have any foreign key so why would they clash ?! Here is my code: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser import datetime import uuid # Create your models here class Patients(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length = 255) last_name = models.CharField(max_length = 255) dob = models.DateField(datetime.date.today) gender = models.CharField(max_length = 1) def __unicode__(self): return self.id -
Using Django ORM to aggregate attribute value across filtered queryset
A django queryset contains user uploaded photos and their corresponding upvotes (from viewers). I need to run a query which returns all the votes added together. Is there any way to use the ORM to return the aggregate votes? I'm assuming it would be faster than how I'm currently doing it (performance matters for me here). Currently I'm trying the following: yesterday = datetime.utcnow() - timedelta(hours = 24) photos = Photo.objects.filter(upload_time__gte=yesterday) cumulative_votes = 0 for photo in photos: cumulative_votes += photo.total_votes -
How do you post request authenticated in Qt to django rest framework with BasicAuthentication?
I want to send data through a post request but only those who are authenticated can do it. In django application I added the BasicAuthentication in settings.py ... REST_FRAMEWORK = { 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', ) } and in Qt post authenticated to do so ... QNetworkRequest request; QUrl url("https://.../data/"); url.setUserInfo("username:password"); request.setUrl(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); QString json = QString(...); QNetworkReply *reply = m_manager->post(request, json.toUtf8()); ... As an error the server returns me -> Error transferring https://username:password@.../data/ - server replied: Bad Request. I can not understand whether the problem lies in the way in which pass username: password or django app. -
Django queryset - sorting twice
How do I get a sorted queryset of Projects to display Departments alphabetically with Teams in each department also alphabetic? Símple models are like this... class Department(models.Model): name = models.CharField(max_length=50) class Teams(models.Model): name = models.CharField(max_length=50) dept = models.ForeignKeyField(Department, on_delete=CASCADE) class Meta: ordering = ('name',) class Project(models.Model): name = models.CharField(max_length=50) team = models.ForeignKeyField(Teams, on_delete=CASCADE) In Views.py I want to collect the teams and display them by Department alphabetically with the number of projects for each Team. ... team_list = [] teams_ = Teams.objects.all().order_by('dept__name') for team in teams_: projects = Project.objects.all(team=team) team_list.append((team, len(projects))) return render(request, 'index.html', {'team_list': team_list}) Then in the template... <ul> {% for team, len in team_list %} <li><a href="{% url 'team_detail' team.id %}">{{ team.dept.name|upper }} - {{ team.name|capfirst }} ({{ len }})</a></li> {% endfor %} </ul> This displays something like this... Archive - Backup (22) Archive - Archive (3) Support - Glossary (32) Support - A Team (12) Support - Members (22) Which is not correct - I want an ordered alphabetic list with departments and teams like this... Archive - Archive (3) Archive - Backup (22) Support - A Team (12) Support - Glossary (32) Support - Members (22) -
Background image not changing from javascript
I am working on a project related to image processing. Currently, I am taking a image from the webcam and saving it in some folder. Then I display that image as a background image on the div. This works fine. But when I take the image again, the background image still remains the same. But when I see the image in the folder, it has changed. Note: Both the images are saved by same name. So, previous image is just replaced by current image. And the image is taken by clicking a button. html code: <button id = "click" onclick = "mooddetect()">MOODY</button> function mooddetect() { $.ajax({ url: '/mooddetect/', type:"POST", cache:false, success: function(input) { var x = document.getElementById('photo'); x.style.backgroundImage = "url('/static/detect/test.jpg')"; }, failure: function(data) { alert('Got an error dude'); } }); } views.py: def get_image(camera): retval, im = camera.read() return im def webcam(): camera_port = 0 ramp_frames = 30 camera = cv2.VideoCapture(camera_port) for i in xrange(ramp_frames): temp = get_image(camera) print("Taking image...") camera_capture = get_image(camera) file = "./music/static/detect/test.jpg" cv2.imwrite(file, camera_capture) del(camera) @csrf_exempt def mooddetect(request): webcam() return HttpResponse("success") -
Reading from CSV: delimiter must be a string, not unicode
I had a working routine (after a few helpful folks gave me some critical advice in this thread) creating model instances from a CSV file. Up to now I have been using Python 2.7 and made sure no special characters appeared anywhere. Currently I need to move to Unicode. I added # -*- coding: utf-8 -*- at the top of my files and everything is working nicely (I can use special characters in my code and comments), save for the CSV reader routine. Namely, the shell objects to this part: dataReader = csv.reader(open(filename), delimiter=';', quotechar='"') which was working before, with TypeError: "delimiter" must be string, not unicode After reading some older questions I switched to dataReader = csv.reader(open(filename), delimiter=str(u';'), quotechar=str(u'"')) to enforce the fact that the delimiter would be a string, but I'm getting exactly the same error. What am I doing wrong? -
CSRF not working in django with safari private browsing
I am unable to POST data to my django webapp in safari private browsing (it works with Chrome incognito). I am not using localstorage. I set the X-CSRFToken header using var csrftoken = NMA.getCookie('csrftoken'); $.ajax({ type:"POST", contentType: 'application/json; charset=utf-8', beforeSend: function (request, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain){ request.setRequestHeader("X-CSRFToken", csrftoken); } }, url: "/profiler/logAnswers/ data: payload, dataType: 'json' }).done(... The csrftoken cookie is set using {% csrf_token %} and the hidden input is present inside the <form> I have inspected the request using charles and the csrftoken cookie is set and the X-CSRFToken header is set. I have noticed that safari in private browsing adds "DNT = 1" (do not track) to the header, not sure if this is causing the problem. The DNT=1 is not present in chrome incognito requests. I have logged the cookies in python2.7/site-packages/django/middleware/csrf.py using logger.debug(request.COOKIES) and the csrftoken cookie is missing (and several other cookies are missing). There are only 4 cookies printed. There are 13 cookies present in the initial request as seen in charles. As there is no csrftoken this causes the Forbidden (CSRF cookie not set.) 403 error. What does the DNT=1 in the header do? Does it limit the number of … -
django-import-export get resource field not present in model
According django-import-export Docs we can add fields to Resource that they are not present in target model. So, I have next Resource: class FamilyResource(resources.ModelResource): code = fields.Field(attribute='code', widget=widgets.CharWidget()) parent = fields.Field() class Meta: model = Family import_id_fields = ('code', ) fields = ('code', 'name', 'image', ) field parent is the field it is not present in the related model and I'd like to know how should I do to get the parent value under save_instance hook because my save_instance logic depends on parent value. -
Convert text strip "-" and put in new line
I got text fields from Salesforce and saved in Django model which value are always like this - Test Task line 1 - Test Task line 2 - Test Task line 3 I want to convert this text to another form and put it on template so that every - is a new line. Example: - Test Task line 1 - Test Task line 2 - Test Task line 3 Is it possible? Or is there another way I can do if not? I'm new and still learning Python and Saleforce. -
Get the size of a folder in Python Linux server
Im working with Django (python) in pythonanywhere.com. While the following code works well in windows, in Linux server (of pythonanywhere) the function only returns 0, without errors. What am I missing? import os def folder_size(path): total = 0 for entry in os.scandir(path): if entry.is_file(): total += entry.stat().st_size elif entry.is_dir(): total += folder_size(entry.path) return total print(folder_size("/media")) -
How to decode firebase jwt token in python
I have added firebase to allow clients to authenticate directly from the web app client (browser). I am using the firebase-web JS package and it works great. I can see in my browser that I receive a user object with information about the user, including an idToken. I need to then authenticate this user on my server backend, which is python django. In the firebase docs I found a how-to for exactly what I am trying to do, which is to verify the id token. Since they don't have the supported firebase sdk for python, I need to use a thrid party solution. I have come to the python-jose package after finding it listed on the jwt.io site. The example looks simple enough: jwt.decode(token, 'secret', algorithms=['HS256']) This is my first time using jwt. I don't know what to use for the 'secret'. I tried pasting my id token as token, and the web API key from the firebase console for secret, but got this error: jose.exceptions.JWTError: The specified alg value is not allowed I also tried the jwt debugger, which seems to be reading most of my key correctly, but the signature verification is looking for a public and/or a … -
Server image right after the domain name in Django and Heroku
Is there a way to achieve this in Django hosted on Heroku? http://www.exampledomain.com/imageofacar.jpg Image to be server right after the domain name? I am not looking for a solution via nginx server or static server, my domain is running on django. -
Django 1.4, i18n, url pattern
I have some problem with change language in my Django project. I use i18n_patterns and all other functionality. When i hit English translation, url is generated properly like from /de to /en and here is my issue. Django show me this: Page not found (404) Request Method: GET Request URL: http://0.0.0.0:8000/en Using the URLconf defined in eds.urls, Django tried these URL patterns, in this order: ^de/ The current URL, en, didn't match any of these. What did I do bad ? -
How to create a thread safe method in django
I am using django 1.10.2 with python 3.5.2 in a Linux machine. I have 2 questions that are related: What is spawn when a client connect to django? Is it a new thread for every client or a new process for every client? I need to have a method in django that must only be accessed by the client one at a time. Basically this must be a thread safe method with perhaps a lock mechanism. How do I accomplish this in django. Thanks in advance! -
celery periodic tasks not executing
I am learning celery and I created a project to test my configuration. I installed celery==4.0.0 and django-celery-beat==1.0.1 according to the latest documentation. In drf_project(main project dir with manage.py)/drf_project/celery.py from __future__ import absolute_import, unicode_literals from celery import Celery import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'drf_project.settings') app = Celery('drf_project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() In drf_project/drf_project/settings.py INSTALLED_APPS += ('django_celery_beat',) CELERYBEAT_SCHEDULE = { "test_1": { "task": "tasks.print_test", "schedule": timedelta(seconds=2), }, } In drf_project/drf_project/init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] In my user_management app (drf_project/user_mangement/) I added a tasks.py from celery import Celery from time import strftime app = Celery() @app.task def print_test(): print strftime('%Y-%m-%d %H:%M:%S') with open('abc.txt', 'ab+') as test_file: test_file.writeline(strftime('%Y-%m-%d %H:%M:%S')) when i run the celery worker and my django project dev server in different terminals by: celery -A drf_project worker -l info and python manage.py runserver I can see my task in celery log like: [tasks] . user_management.tasks.print_test But it is not executing. Also I am not getting any error. SO what I am doing wrong? I followed the official documentation of celery. -
Missing Variable Error in Django Form After Form Submission
I added a newsletter sign-up form to the footer area of my site and such had to use an inclusion_tag because I couldn't bind it to a view. It works well and as expected, but I have a strange thing happening that I apparently am not smart enough to figure out myself :) After the form is submitted, I receive the email confirmation, but two things happen: The Django Success Message doesn't appear until after I manually refresh the page. Where my form sits, there are syntax 'Missing Variable' errors. I included a screenshot for reference and my form code is below. The form fields re-appear and erros go away after refreshing the page again. home_tags.py @register.inclusion_tag('pages/tags/footer_newsletter_signup.html', takes_context=True) def footer_newsletter_signup(context): request = context['request'] title = 'Newsletter Signup' form = MailingListForm(request.POST or None) if form.is_valid(): mailing_list_full_name = form.cleaned_data.get('mailing_list_full_name') mailing_list_phone = form.cleaned_data.get('mailing_list_phone') mailing_list_email = form.cleaned_data.get('mailing_list_email') mailing_list_subject = 'Submission from Newsletter Signup' mailing_list_message = 'Yes, please add me to marketing emails.' from_email = settings.DEFAULT_FROM_EMAIL recipient_list = [from_email, 'charles@studiorooster.com'] ctx = { 'mailing_list_subject': mailing_list_subject, 'mailing_list_full_name': mailing_list_full_name, 'mailing_list_email': mailing_list_email, 'mailing_list_phone': mailing_list_phone, 'mailing_list_message': mailing_list_message } message = get_template('pages/newsletter_signup_email.html').render(Context(ctx)) msg = EmailMessage(mailing_list_subject, message, to=recipient_list, from_email=from_email) msg.content_subtype = 'html' msg.send() messages.success(request, "Thank you, you've been added to our … -
using correctly crossdomain SESSION_COOKIE_DOMAIN in django
I am using django for 2 sets of sites, that partialy share domain. One is m.example.com and one is for everything else (.example.com). Basically I ran into issues that whenever I login to .example.com, I cannot login into m.example.com unless I logout from .example.com. After some debugging I found this: https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-SESSION_COOKIE_DOMAIN Currently m.example.com has (not sure if SESSION_ENGINE is relevant here, but they are different): SESSION_COOKIE_DOMAIN = "m.example.com" SESSION_ENGINE = 'django.contrib.sessions.backends.db' .example.com has: SESSION_COOKIE_DOMAIN = ".example.com" SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' Now my question is - how do I configure it ideally that both domains can login at same time? Both domains are production websites with thousands of users so I need to be sure. P.S. I know and agree that this setup of domains is weird and maybe quite stupid. I want to get rid of it (in fact of whole app and make it single app for everything), but cannot do it that fast. -
How to get the value of parameter passed from template include tag in view.py?
I would like to get the value of parameter that passed from template. I passed variables like this : {% include "app/test.html" with id="testId" value="testValue" %} And I want to read this variables in views.py, but I don't know how to do this. Any help is appreciated. Thanks -
Error: No module named django
I have an old CentOS machine, where a software app written for Django 1.4.x is running. The software requires Python2.7. So I upgraded the implementation to Python2.7 and installed the various necessary software. on the python2.7 command prompt >>> import django Works perfectly. I am able to play around with everything fine. Even when I print sys.path it shows directories fine. But running python2.7 manage.py runserver or any other command throws up an error python2.7 manage.py runserver Error: No module named django This is the first time I have seen such an issue in last 10 years. The software works perfectly in the ubuntu version which has python2.7 installed. -
How to join multiple records of a model to another model in Django?
I need to set some tags to a question. In Question model i use Tag as ForeignKey - class Tag(models.Model): tag_text = models.CharField(max_length = 200) class Question(models.Model): tag = models.ForeignKey(Tag, on_delete = models.CASCADE) What i see in back end for a Question can select one Tag but i want a single Question can select multiple Tags. I am confused what it would be - ManyToMany / OneToMany /... Thanks