Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use d3 to read live csv data from url generated by python script
I just straight to the point. I have tried to read the csv data using d3 from a url generated by python script without downloading it but failed. Most probably i missed out something **The code for d3 and data reading** **diagnostic.html** var csvData; $(document).ready(function() { csvData = $.ajax({ type: "GET", url: "http://192.168.0.96/system/diagnostics/download?job=af97ee71-9f38-4a94-8f34-586668431793&format=csv", dataType: "text/csv", success: function (result) { alert(csvData.getAllResponseHeaders()) } }); }) d3.csv("csvData", type, function(error, data){ if (error) throw error; // console.log(data); initialDomain = d3.extent(data, function(d) { return d.Timestamp; }); x.domain(initialDomain); ydomain = d3.extent(data, function(d) { return d.AGV_Mileage; }); y.domain(ydomain); x2.domain(x.domain()); y2.domain(y.domain()); Other codes that related to the csv dump_diagnostic.py from __future__ import absolute_import from __future__ import unicode_literals from celery import shared_task from django.core.cache import cache from django.core.files.storage import default_storage from django.utils import timezone from django_mongokit import get_database try: from cStringIO import StringIO except: from io import StringIO import gzip import os.path import time from ..document import Diagnostic DIAGNOSTIC_FOLDER = 'tmp/diagnostics' @shared_task(bind=True, rate_limit='3/m') def dump_diagnostics(self, start, end): _purge_old_files() unique_id = '%s-%s' % ( timezone.localtime(start).strftime('%Y%m%d_%H%M%S'), timezone.localtime(end).strftime('%Y%m%d_%H%M%S')) lock_id = 'dump_diagnostics_%s' % unique_id acquire_lock = lambda: cache.add(lock_id, True, 120) renew_lock = lambda: cache.set(lock_id, True, 120) release_lock = lambda: cache.delete(lock_id) while not acquire_lock(): time.sleep(1) file_path = os.path.join(DIAGNOSTIC_FOLDER, 'diag-%s.csv.gz' % unique_id) if default_storage.exists(file_path): return … -
Django model puzzle && default values that are dynamic
I have looked at many questions, but haven't found any quite what I am looking for. I apologize if I missed similar questions. Here is my basic outline of what I am trying to build (and having trouble with). I am building a meal plan where meals are made up of dishes...dishes are made up of Ingredients (a food item plus the quantity), and then the actual food items such as almonds, water, spinach, etc. An example of this is the meal of Breakfast...it is made up of two dishes of (1) Cereal and (2) Coffee...the dish of cereal is made up of the ingredients (1) Milk with 200g and (2) cereal with 200g. I have a Food Model, Dish Model, Ingredient Model && Meal Model that allows me to build that. Here are my models to get idea (abbreviated): class Food(models.Model): name = models.CharField(max_length=128) class Dish(models.Model): name = models.CharField(max_length=128) instructions = models.TextField() food = models.ManyToManyField(Food, through='Ingredient') user = models.ForeignKey(User, default=1) class Ingredient(models.Model): food = models.ForeignKey(Food, on_delete=models.CASCADE) dish = models.ForeignKey(Dish, on_delete=models.CASCADE) quantity = models.CharField(max_length=128) class Meal(models.Model): user = models.ForeignKey(User, default=1) name = models.CharField(max_length=128) dishes = models.ManyToManyField(Dish) time = models.DateTimeField(default=now, blank=True) With these, and appropriate admin.py setup, I am able to … -
Apply migrations and models from all the apps
I'm using Django and I have an schema like mainapp |---mainapp | |---migrations.py | |---models/ |---app2 |---migrations/ |---models/ But, when I execute: python manage.py migrate it is generationg the tables of mainapp/models, but no the app2/models and app2/migrations either. How can execute those migrations? -
django-concurrency is doing nothing
I am testing my app for concurrency I am using django-concurrency For every model added from concurrency.fields import IntegerVersionField version = IntegerVersionField( ) So i open with 2 browser windows my app. log with 2 different users and the edit with both same record . Save with one then I save with second one and always second one just overwrites the first one . Basically does nothing . Expected to get an error on my second save. What could be the issue ? -
Google App Engine with Django
Hi I want to create a web app with google app engine. I am going to use python for my backend language with restful apis. I am going to use cloud datastore(NoSQL database), cloud storage, and cloud sql(SQL database) for storage. I am new to web development so I will have to learn a web framework. Should I use django or flask? -
Django Rest Framework Incorrect Model View response
I have some issue with drf, can someone point out what am i doing wrong ? This is my views function, I have also implemented easy_thumbnails so that i can crop the image if such a request is made. from __future__ import unicode_literals from django.shortcuts import render from rest_framework import viewsets from rest_framework.response import Response from .models import Image from .serializers import ImageSerializer from easy_thumbnails.files import get_thumbnailer class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer def retrieve(self, request, pk=None): height = request.GET.get('height', None) width = request.GET.get('width', None) print("height = {}".format(height)) print("width = {}".format(width)) print("id = {}".format(pk)) img = Image.objects.get(pk = pk) options = {'size': (height, width), 'crop': True} thumb_url = get_thumbnailer(img.image).get_thumbnail(options).url return Response(thumb_url) right now if goto http://127.0.0.1:8000/api/images/ it returns me a list of images and http://127.0.0.1:8000/api/images/1/?height=320&width=420 returns a response like HTTP 200 OK Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept "/media/10438039923_2ef6f68348_c.jpg.320x420_q85_crop.jpg" if i comment out this code, i can search by id, otherwise i can't def retrieve(self, request, pk=None): height = request.GET.get('height', None) width = request.GET.get('width', None) print("height = {}".format(height)) print("width = {}".format(width)) print("id = {}".format(pk)) img = Image.objects.get(pk = pk) options = {'size': (height, width), 'crop': True} thumb_url = get_thumbnailer(img.image).get_thumbnail(options).url return Response(thumb_url) If i … -
Not working JQuery validation on Django forms
To give a background, I made a for loop for each field in the form to display.Also, I put a button that conditions what fields to be filled and not. Also, I settled on putting the optional fields in a dropdown div, I made two for loops. After making this, the Bootstrap won't work and can submit even if required fields are empty. Now I'm working with Jquery validation plugin just to make things work but still won't. Can someone help me with what I'm doing wrong? This is a part of the form.html <div class="panel-body"> <div class="choice_content" id="form_content"> <h2>Submit your own Sample!</h2> <div class="button_content text-center"> <button type="button" class="btn btn-primary btn-lg outline" id="urlType-btn">URL</button> <button type="button" class="btn btn-primary btn-lg outline" id="localType-btn">Local Sample</button> </div> </div> <!--choice_content--> <form class="form-horizontal" enctype="multipart/form-data" method='POST' id="sampleForm" style="display: none;" action="/sample/submit/"> {% csrf_token %} <div class="form-container"> {% include 'analysis/form_template.html' %} </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success"> Run Analysis! </button> </div> </div> </form> </div> form_template.html {% load form_fields %} {% for field in form %} {% if field.auto_id == "id_proxy_host" or field.auto_id == "id_proxy_user" or field.auto_id == "id_proxy_password" or field.auto_id == "id_proxy_port" or field|is_radio or field.auto_id == "id_url_sample_name" or field.auto_id == "id_local_sample_name" or field.auto_id == "id_no_content_fetch" … -
Django, model split when a single model is getting huge?
I've already broken down models.py into separate model files. One of model file is getting huge, and I want to break it apart, but don't know how. One way I can think of is, break methods into several classes (as mixins) and inherit them. but not sure if it's the best way to go about it. -
Will a view complete even if a user times out?
If I have a view in Django such as def hello(request): first_up(request) do_stuff(request) return render(request, 'hello.html') If a user requests this page, but times out before the view can complete or navigates away before the view reaches the 'render' will the view still complete it's task? For example if the view finishes the first_up function but the user navigates away or closes their browser etc. Will the do_stuff function still complete? Thanks! -
Django get custom m2m field value
Scenario: I have lots of questions in a test bank, and some of them are similar. So I defined a custom m2m field that allow me to know the similarity of each two questions. My models: class Question(models.Model): number = models.SmallIntegerField() question = models.TextField() related_q = models.ManyToManyField("self", related_name='RelatedQuestion', through='RelatedQuestion', symmetrical=False, blank=True) class RelatedQuestion(models.Model): from_question_id = models.ForeignKey(Question, on_delete=models.CASCADE, blank=True, related_name="source+") to_question_id = models.ForeignKey(Question, on_delete=models.CASCADE, blank=True, related_name="destiny+") similarity = models.FloatField() The similarity looks like below. Question How can I get the similarity later on? >>> Question.objects.get(pk=5757).related_q.first() <Question: 100-1-1-1 下顎骨中最重要的力軌(trajectory)為何? > >>> Question.objects.get(pk=5757).related_q.first().id 1 >>> Question.objects.get(pk=5757).related_q.similarity Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'ManyRelatedManager' object has no attribute 'similarity' >>> Question.objects.get(pk=5757).related_q.first().similarity Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'Question' object has no attribute 'similarity' >>> Question.objects.get(pk=5757).RelatedQuestion_set.all() Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'Question' object has no attribute 'RelatedQuestion_set' >>> Question.objects.get(pk=5757).RelatedQuestion.similarity Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'ManyRelatedManager' object has no attribute 'similarity' -
very weird issues with default url on heroku production pipeline
I have super simple pipeline on heroku github (master branch just one ) -> Staging - > production All worked until I have modified my default url in my main app and nor it does work in my DEV does work in my Staging but when i move it from staging to production I get Not Found The requested URL / was not found on this server. from this line url(r'^$', views.dashboard_rent, name="dashboard_rent"), from django.conf.urls import include, url from django.contrib import admin from ajax_select import urls as ajax_select_urls from dashboard import views from wkhtmltopdf.views import PDFTemplateView admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('registration.backends.default.urls')), url(r'^explorer/', include('explorer.urls')), url(r'^lease/', include('lease.urls')), url(r'^payment/', include('payment.urls')), url(r'^condition/', include('conditions.urls')), url(r'^unit/', include('unit.urls')), url(r'^client/', include('client.urls')), url(r'^dashboard/', include('dashboard.urls')), url(r'^$', views.dashboard_rent, name="dashboard_rent"), url(r'^ajax_select/', include(ajax_select_urls)), url(r'^pdf/$', PDFTemplateView.as_view(template_name='my_template.html', filename='my_pdf.pdf'), name='pdf'), ] my dashboard app url from django.conf.urls import url, include,patterns from dashboard import views urlpatterns = [ url(r'^rent/dashboard/$', views.dashboard_rent, name="dashboard_rent"), url(r'^rent/unit/dashboard/$', views.dashboard_unit, name="dashboard_unit"), ] -
Most efficient / proper way to give Json response in Django?
I am writing a polling view in Django -- being called once per second. I'd like to avoid the effect of hammering the server (since its a small device). Currently I'm returning this response: `return HttpResponse(json.dumps({'body':body}))` but is there a more appropriate way to do this, thus using minimal resources / features for this simple / ongoing response? -
Braintree JSv3 payment_method_nonce Value Bad With HostedFields
I have looked at a few posts on here with the same issue but under different circumstances that don't supply me with an answer to my particular issue... I was using Braintree JSv2 with my Django project and all was working fine. Since I have migrated over to v3 of Braintree, the only issue I seem to have right now is that the value inputted to "payment_method_nonce" is not there... Here is the code that is supposed to be dumping the payment_method_nonce value: document.querySelector('input[name="payment_method_nonce"]').value = payload.nonce; And here is the code that is supposed to be grabbing it on the python side: client_payment_nonce = request.POST['payment_method_nonce'] When submitting this in my dev environment, I get an error (MultiValueDictKeyError) for "payment_method_nonce". I am using Django 1.9 and Python 2.7. I am also using the example given by Braintree for a simple integration using HostedFields... -
Django FilePathField filter used entries
I have the following Model where the FilePathField should be unique: class Gallery(models.Model): template = models.FilePathField(path=".../templates/galleries/", unique=True) In the admin, I would like the dropdown list to only show me those entries that have not been used, yet, in order to make the selection among available answers more easy. After all, any already used option in the resulting dropdown list will give me an error anyway and does not need to be shown to me in the admin. Unfortunately I am having problems wrapping my head around this. Can anyone tell me where I could insert something similar to the following: used = [gallery.template for gallery in Gallery.objects.all()] return [file for file in files if file not in used] ...or might I have overseen an option somewhere in Django that could already give me the desired result? -
Django prevent the user from waiting [duplicate]
This question already has an answer here: Python Django Asynchronous Request handling 4 answers I have a task that I run once a user submits a form that doesn't need to be completed before the view is rendered in return to the user. with transaction.atomic(): process(charge) return redirect('complete') Here is an example of what I am doing. The process function does not need to complete before the view is rendered. Is there a way to run that function without making the user wait for that block of code to complete? Thanks -
Nginx 504 Gateway timed out when using ssl
Last week after adding the SSL certificates to the django application, I tried to reach the admin page, but I got timed out - 504 Gateway time-out. The application is in a docker container and the database(Postgres) is in a separate container both connected with docker-compose. The application uses uWSGI + nginx. I know there are a lot of threads out there covering this issue, but the problem is I am getting the problem only on my computer(Ubuntu LTS 16.04). I tried it from a friend's computer and I had no issues. Is the problem in my two computers or in the settings of the Internet connection? It is worth mentioning that the certificates are created using OpenSSL. Furthermore, prior to using the https connection, I had no issues of reaching the admin page, so it should not be because of the application, however, now even using http ends with a 504 time-out. The error that I find in the docker container is: [error] 105#0: *29 upstream timed out (110: Operation timed out) while reading response header from upstream, client: ******, server: localhost, request: "POST /admin/login/?next=/admin/ HTTP/1.1", upstream: "uwsgi://unix:///path/to/Socket.sock", host: "localhost" Moreover, I tried expanding the time out time as … -
Django admin change_form with ajax query
I'm working with an ModelAdmin from my model. I have a field that i need to check if it's right. It's a string and i'm using to send to the server and this returns me a graph in what i can check the string it's ok. The big question is about how to use the ajax whith the admin view, and the view returns me the object. It's a little different from the classic way with ajax+views, because i have now the admin mode class inside admin.py. I redefine the change_form template and add the js and ajax calls. But returns me nothing at the moment. Thanks for your advices! -
I am getting multiple errors with django and uwsgi on a docker
I am porting a django website to another server using a docker. This is the Dockerfile I used to set up my new (and old) docker: FROM debian:latest RUN apt-get update RUN apt-get upgrade -y RUN apt-get install -y python python-dev python-setuptools RUN easy_install pip RUN apt-get install sqlite3 RUN pip install django==1.6.8 RUN pip install uwsgi RUN pip install sorl-thumbnail RUN pip install django-modeltranslation RUN pip install south RUN pip install django-rosetta RUN apt-get install -y libjpeg-dev RUN apt-get install -y libfreetype6-dev RUN apt-get install -y zlib1g-dev RUN apt-get install -y libpng12-dev RUN pip install pillow RUN sed -i 's/except AttributeError/except (AttributeError, KeyError, IndexError)/' /usr/local/lib/python2.7/dist-packages/sorl/thumbnail/engines/pil_engine.py WORKDIR /*path*/ EXPOSE 8000 CMD uwsgi --http :8000 --module *name*.wsgi:application --static-map /static=/*path*/*name*/static --static-map /media=/*path*/media I set up the project and everything but now i keep getting "INTERNAL SERVER ERROR" This is the log: *** Starting uWSGI 2.0.15 (64bit) on [Mon May 15 20:48:49 2017] *** compiled with version: 4.9.2 on 15 May 2017 09:31:53 os: Linux-4.4.0-64-generic #85~14.04.1-Ubuntu SMP Mon Feb 20 12:10:54 UTC 2017 nodename: 1a830a6c390f machine: x86_64 clock source: unix detected number of CPU cores: 2 current working directory: path detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support … -
Django django_admin_log' doesn't exist
I have setup a new database with MySQL and run python manage.py migrate then run python loaddata db.json to load data from my previous sqlite database. But now when I try to access the admin pages I get ProgrammingError at /admin/ (1146, "Table 'myapp.django_admin_log' doesn't exist") Other answers say to run syncdb but it not longer exists. Any ideas? -
Django - can't get highchart to display data
I'm trying to display a chart with help of Highchart by following this solution: Passing Django Database Queryset to Highcharts via JSON But I can't get the data to appear: Still new to this and appreciate your help, folks! views.py class ChartData(object): def check_valve_data(): data = {'member_no': []} people = Member.objects.all() for unit in people: data['member_no'].append(unit.member_no) return data def chartViewHigh(request, chartID='chart_ID', chart_type='column', chart_height=500): data = ChartData.check_valve_data() chart = {"renderTo": chartID, "type": chart_type, "height": chart_height, } title = {"text": 'Check Member Data'} xAxis = {"title": {"text": 'Member'}, "categories": data['member_no']} yAxis = {"title": {"text": 'Data'}} return render(request, 'chart/chartViewHigh.html', {'chartID': chartID, 'chart': chart, 'title': title, 'xAxis': xAxis, 'yAxis': yAxis}) chartViewHigh.html {% extends 'base.html' %} {% load staticfiles i18n %} {% block head %} <link href="{% static 'css/chart.css' %}" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> {% endblock head %} {% block main %} <h1 align="center">Analysis</h1> {% block content %} <div id={{ chartID|safe }} class="chart" style="height:100px; width:100%"></div> {% endblock %} {% block extrajs %} <script> var chart_id = {{ chartID|safe }}; var chart = {{ chart|safe }}; var title = {{ title|safe }}; var xAxis = {{ xAxis|safe }}; var yAxis = {{ yAxis|safe }}; </script> <script> $(document).ready(function() { $(chart_id).highcharts({ chart: chart, title: title, … -
Django Multiple inheritance with different tables
I tried to create some models (first time using django) I actually looked at some exmaples but most of them don't work. Example: class Piece(models.Model): name = models.CharField(max_length=100) class Meta: abstract = True class Article(Piece): pass class Book(Piece): pass class Monday(Book, Article): pass class Tuesday(Book, Article): pass Soo my goal is to get the value with something like this -> Monday.Article.name. I want to have different tables for every weekday, containg the articles name (i hope this is understandable). This is the error i get: ERRORS: Testing.Monday: (models.E005) The field 'id' from parent model 'Testing.book' clashes with the field 'id' from parent model 'Testing.article'. Testing.Monday: (models.E005) The field 'name' from parent model 'Testing.book' clashes with the field 'name' from parent model 'Testing.article'. Testing.Tuesday: (models.E005) The field 'id' from parent model 'Testing.book' clashes with the field 'id' from parent model 'Testing.article'. Testing.Tuesday: (models.E005) The field 'name' from parent model 'Testing.book' clashes with the field 'name' from parent model 'Testing.article'. It looks like my Article and Book are using the same name.. How does this work. Thanks -
Djago error with PostgreSQL migration
I was trying to run my Django App with PostgreSQL as my database engine earlier used sqlite, this is my settings.py. I was doing the installation by tutorial https://djangogirls.gitbooks.io/django-girls-tutorial-extensions/optional_postgresql_installation/ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'djangogirls', 'USER': 'cherzik', 'PASSWORD': 'ADMIN', 'HOST': 'localhost', } } this is errors, help please d:\py\djangogirls>python manage.py migrate System check identified some issues: WARNINGS: blog.Comment.created_date: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default f or this field. This may not be what you want. If you want to have the current da te as default, use `django.utils.timezone.now` blog.Post.created_date: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default f or this field. This may not be what you want. If you want to have the current da te as default, use `django.utils.timezone.now` Traceback (most recent call last): File "C:\Users\Кирюшик\AppData\Local\Programs\Python\Python35\lib\site-package s\django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "C:\Users\Кирюшик\AppData\Local\Programs\Python\Python35\lib\site-package s\django\db\backends\base\base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Кирюшик\AppData\Local\Programs\Python\Python35\lib\site-package s\django\db\backends\postgresql\base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Кирюшик\AppData\Local\Programs\Python\Python35\lib\site-package s\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was … -
How to update or Add Widget in Django ModelForms's init method?
My Model Form looks like this class AbcForm(forms.ModelForm): class Meta: model = Abc Rate_field = PaychoiceField(lable='ABC rate', widget = RateSelect) How do I Update the Rate_field in init method so that I do not see the Data which is displayed by the widget. For certain condition, let's say if rate = not_payable. I don't want to disable the field but I just want to disable the widget. Or is there any wat I can override the field? -
Celery add task dynamically to chain
I am using celery 3 with Django. I have a list of jobs in database. User can start a particular job which starts a celery task. Now I want user to be able to start multiple jobs and it should add them to the celery queue and process them one after the other not in parallel as with async. I am trying to create a job scheduler with celery where user can select the jobs to execute and they will be executed in sequential fashion. If I use chain() then I cannot add new tasks to the chain dynamically. What is the best solution? -
No Values in ManyToManyField
I have a UserProfile where the User chose a language. Users should have the possibility to chose more than one language so i tried to use a ManyToManyField like so: class Choices(models.Model): languages = models.CharField(choices=settings.LANGUAGES, max_length=3) def __unicode__(self): return self.languages class UserProfile(models.Model): user = models.OneToOneField(User, null=True) language = models.ManyToManyField(Choices) in my form.py i did: class UserProfileForm(forms.ModelForm): language = forms.MultipleChoiceField(required=False, choices=settings.LANGUAGES) class Meta: model = UserProfile fields=[ 'Pictures', ..... ] The problem is: The choices are shown in the template but in the admin the ManyToManyField is empty. So the Form works but the Model does not. Can somebody tell me why no Options are displayed? Where is the mistake at the M2M? Thanks for any Advise