Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript search filter on user generated table from Django
I'm trying to create a dynamic search engine with javascript from a user generated table that is created with a form that adds a song to the table. I want to search the list that's already created. It's not doing anything when I type in anything and no errors in the DOM. Can some someone tell me where i went wrong? Here's my HTML: {% extends "base.html" %} {% load static %} {% block title %}My Song List{% endblock %} {% block content %} <input type="text" name="search" placeholder="Search by Title" class="animated-search-form" id="myInput onkeyup="search();"> <div class="translucent-form-overlay"> <form action="/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Add Song" /> </form> </div> <div id="list-container"> <h1 style="text-decoration:underline">Sorted Alphabetically by Song Title</h1> <h5> <table id="myList"> {% for song in song_list %} //song_list is the model <tr> <td>Title: {{song.title}}</td> <td>Artist: {{song.artist}}</td> <td>Year: {{song.year}}</td> <td>Genre: {{song.genre}}</td></tr> {% endfor %} </table> </h5> </div> {% endblock %} And here's my javascript: function myFunction() { // Declare variables var input, filter, table, tr, td, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myList"); tr = table.getElementsByTagName("tr"); // Loop through all table rows, and hide those who don't match the search query for (i = 0; i < … -
Form Validation using Django Templates
I created a form inside my template, my problem is to get data without using forms module. class DentalRecordCreateView(CreateView): template_name = 'patient/dental_create.html' model = DentalRecord fields = '__all__' success_url = '/' def post(self, request, *args, **kwargs): pt = self.kwargs['pk'] #get id from previous insert form form = self.form_class(request.POST) #this is where pycharm is pointing the problem tooth = [18, 17, 16, 15, 14, 13, 12, 11, 21, 22, 23, 24, 25, 26, 27, 28, 48, 47, 46, 45, 44, 43, 42, 41, 31, 32, 33, 34, 35, 36, 37, 38] tooth.reverse() mytooth = {} if form.is_valid(): dental = self.form.save(commit=False) for t in tooth: mytooth["{0}".format(t)] = request.POST.getlist('tooth_' + str(t),False) # returns value each textbox from form tooth. Value for tooth status [decayed, etc.] mytooth2 = " ".join(mytooth[str(t)]) dental.status = mytooth2 dental.position = t messages.success(request, pt) # display values return redirect('index') else: messages.error(request, "Error") The error says that 'NoneType' object is not callable I find the I find the class based views confusing, does anyone have a good tutorial on how to use it for CRUD operations? Thanks -
Django: DeleteView for bulk delete
I am using django-actions for implementing custom actions in generic ListView. Following are the methods to perform specific tasks: actions.py from django.http import HttpResponseRedirect from django.utils.translation import gettext as _ def archive_stores(view, queryset): queryset.update(archive=True) return HttpResponseRedirect('.') def unarchive_stores(view, queryset): queryset.update(archive=False) return HttpResponseRedirect('.') def delete_stores(view, queryset): queryset.delete() return HttpResponseRedirect('.') archive_stores.short_description = _('Archive') unarchive_stores.short_description = _('Unarchive') delete_stores.short_description = _('Delete') Now the above works fine and using the actions menu I can perform all the 3 tasks. I am stuck in figuring out the following: For Archive and Unarchive how to show success and error messages. For Delete, how to use the my existing DeleteView as it already has confirmation page etc. And most importantly, how to pass the queryset to DeleteView so that it can perform bulk delete. Thanks. -
Filter Django Form Field
I have two form fields I need to filter on and not sure how to. For example, in my forms.py file, I create two fields as such: field_1 = forms.CharField(label='', widget=forms.TextInput(attrs={ 'class': "input-field", 'id': "field-1", 'type': "text", })) field_2 = forms.CharField(label='', widget=forms.TextInput(attrs={ 'class': "input-field", 'id': "field-2", 'type': "text", })) In my HTML, I'm trying to filter by Id, but not sure I can do what I want to: {% for inputfield in fields %} {% if inputfield.id == "field-2" %} {{ inputfield }} {% endfor %} {% endfor %} The filter on inputfield.id does not work. Is there a way to filter so that I present only the field I want? -
Django: Creating XML files dynamically from database, to be served for AJAX request
I am trying to serve the contents from a database table (new contents will be added to the table with time) to an HTML table. New contents need to be appended as new rows to the HTML table. Can you help me with the creation of XML files dynamically and where it should be stored in the server? -
Django: Best Practice/Advice on handling external IDs for Multiple Multi-directional External APIs
So this is more of a conceptual question, and I am really looking for someone to just help point me in the right direction. I am building a middleware platform where I will be pull data in from inbound channels, manipulating it, and then pushing it out the other door to outbound channels. I will need to store the external id for each of these records, but the kicker is, records will be pulled from multiple sources, and then pushed to multiple sources. A single record in my system will need to be tied to any number of external ids. a quick model to work with: class record(models.Model): #id Name = models.CharField(max_length=255, help_text="") Description = models.CharField(max_length=255, help_text="") category_id = model.ForeignKey(category) class category(models.Model): #id name = models.CharField(max_length=255, help_text="") description = models.CharField(max_length=255, help_text="") class channel(models.Model): #id name = models.CharField(max_length=255, help_text="") inbound = models.BooleanField() outbound = models.BooleanField() Obviously, I cannot add a new field to every model every time I add a new integration, that would be soooo 90s. The obvious would be to create another model to simply store the channel and record id with the unique id, and maybe this is the answer. class external_ref(models.Model): model_name = models.CharfieldField() internal_id = models.IntegerField() … -
How to run a Django Project on a Personal Run Server
I've been wanting to run my own server for a while and I figured that running one for my django website would be a good start. What do you recommend I use for this? I've been trying to use a Ubuntu Virtual Machine to run it on one of my old laptops that I don't really use anymore until I can buy a dedicated server. Should I run it from a Virtual Machine? If so, would Ubuntu be best? That appears to be the case, but I want to be sure before I invest in anything. I want to be able to access the website from other computers, just like any other website. Am I going about this wrong? If so, what can you suggest me? -
Elastic Beanstalk with python 3.4 still using python 2.7
I just spin up some environment using EB with python 3.4 and Django but it keeps failing, looks like the error occurs when installing using pip install -r requirements.txt this are the events from the web console: Time Type Details 2017-10-06 20:22:39 UTC-0600 WARN Environment health has transitioned from Pending to Degraded. Command failed on all instances. Initialization completed 69 seconds ago and took 14 minutes. 2017-10-06 20:22:20 UTC-0600 ERROR Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. 2017-10-06 20:21:17 UTC-0600 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2017-10-06 20:21:17 UTC-0600 ERROR [Instance: i-0b46caf0e3099458c] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2017-10-06 20:21:14 UTC-0600 ERROR Your requirements.txt is invalid. Snapshot your logs for details. I followed this tutorial: django-elastic-beanstalk-django and deploying-a-django-app-and-postgresql-to-aws-elastic-beanstalk on both I'm stuck at the same step -
Routers urls with django rest framework 3.6 and django 1.11
I have a django 1.7 with djangorestframework 3.3.2 site, and I'm migrating to django 1.11 with DRF 3.6. All things are working fine except routers with urls. My Router: router = routers.DefaultRouter() router.register(r'options', MicrositeViewSet) My urls: urlpatterns = [ # '', url(r'^api/v1/', include(router.urls)), ] My viewsets: from django.shortcuts import get_object_or_404 from rest_framework import viewsets, mixins from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.response import Response from rest_framework.permissions import IsAdminUser from microsites.permissions import AccountPermission from microsites.models import Microsite from microsites.serializers import SelfManagedMicrositeSerializer, MicrositeTestProfileSerializer class MicrositeViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ A viewset for viewing and editing microsites. """ authentication_classes = (SessionAuthentication,) permission_classes = (AccountPermission,) serializer_class = SelfManagedMicrositeSerializer queryset = Microsite.objects.all() def list(self, request, *args, **kwargs): microsite = request.microsite account = request.account queryset = Microsite.objects.filter(account=account) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = self.get_queryset() microsite = get_object_or_404(queryset, api_key=pk) self.check_object_permissions(self.request, microsite) microsite.pull() microsite.set_request_user(request.user) serializer = self.get_serializer( microsite, metadata=request.GET.get('metadata', False), categories=request.GET.get('categories', False), ) return Response(serializer.data) def update(self, request, pk=None, *args, **kwargs): partial = kwargs.pop('partial', False) queryset = self.get_queryset() microsite = get_object_or_404(queryset, api_key=pk) serializer = self.get_serializer(microsite, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) This code exactly as it is works with django 1.7 and DRF 3.2, but in django 1.11 and DRF 3.6 does … -
user authentication across domains in Django
Say I have a site, with name = NAME, all ending with .com structured as: NAMEjobs, NAMEblog, NAMEnews, .... so on and so forth under an umbrella domain NAME****. And I wanted to build apps for each of these domains how would I share authentication (for a signed in user) across these? I looked at django shared-session but not sure if there's a better route to go. I'd prefer to not roll my own solution. -
How to send Data with jQuery to Django view and render the Django template?
I have some data in javascript and want to send it to a Django view function. After that I want to render a Django template using HttpResponse, but how it works? First I had send some data to a Django view with jQuery.ajax() and used the response data, now I want to send data within a second jQuery.ajax() - after a button was clicked - to a different Django view function and finally render a simple template, like how it works, if I click a simple link on a website. I have cut the snippet as far as possible for the sake of clarity $(matchfield).on('click', function(event) { event.preventDefault(); var field = $(this).val(); $.ajax({ method: "POST", url: "/view-function/", data: { "field": field }, dataType: "json", context: this, success: function (data) { if(data.message === 1) { points = 100 $('#submit').on('click', function(event) { event.preventDefault(); $.ajax({ url: "/another-view/", method: "POST", data: {"points": points}, success:function(response){ $(document).html(response) } }) }) } } }); }); If the #submit Button was clicked, The status code of the Response is 200 and Chrome Dev Tools shows the complete excepted new html page in Preview(without css style), but nothing happens on the current page. I used return HttpResponse(template.render(context, request)) I … -
Interactive chat based assistant for a website
Trying to build an interactive chat like application capable of handling Natural Language questions for my Institution's website.I am planning to use Python as language. Django for backend. It should be able to fetch data from database. Pandas/SQLite which one to prefer? Enlighten with outline of the process! How to achieve it? Should Machine Learning be used ? Thanks. -
'AutoField' object has no attribute 'remote_field'
I am getting a strange error in Django 1.8: 'AutoField' object has no attribute 'remote_field' I have a model like: from django.db import models from django.utils import timezone class Event(models.Model): product_type = models.CharField(max_length=250, null=False, blank=False) received_time = models.DateTimeField(editable=False) source_json = models.TextField() event_id = models.CharField(max_length=250, null=False, blank=False) # https://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add def save(self, *args, **kwargs): if not self.id: self.received_time = timezone.now() return super(Event, self).save(*args, **kwargs) @classmethod def event_id_is_already_saved(cls, event_id_in_question): items_found = cls.objects.filter(event_id=event_id_in_question) if items_found: return True return False views like: import json from django.http import HttpResponse from rest_framework import viewsets from events.utils.elastic_db_utils import get_elastic_exact_search_from_query_dictionary from events.serializers import EventSerializer from events.models import Event def list_events(request): all_events = Event.objects.all() serialized = [EventSerializer(event) for event in all_events] return HttpResponse(json.dumps(serialized)) class EventViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Event.objects.all().order_by('-received_time') serializer_class = EventSerializer urls: from django.conf.urls import url, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'events', views.EventViewSet) urlpatterns = [ url(r"^$", views.search_elastic_db, name='search-elastic-db'), url(r"^events", views.list_events, name='list-events'), url(r'^api/', include(router.urls)), ] Neither my viewset, nor the ^events endpoint work, both get same error. There is nothing wrong with my model that you can see in a shell: In [1]: from events.models import Event In [2]: Event.objects.all() Out[2]: … -
How do i show an active link in a django navigation bar dropdown list?
I have a navbar menu with a list of links which i want to show the active link when the user is on the page, so far i have managed to do this with links that dont have dropdowns like this. But I cannot seem to get it right with the dropdown links in such a way that if the user is on a page on the dropdown link the parent link on the navbar gets highlighted.like this. Any help would be greatly appreciated. -
django view didn't return an HttpResponse object when retrieving file
I've run into an issue when creating a custom view for processing requests for media file. I've customized it to be able to do custom permissions checks and overrides. url(r'^media/(?P<path>.*)$', views.document_view, {'document_root': settings.MEDIA_ROOT}), @login_required def document_view(request, path, document_root): name = os.path.join(settings.MEDIA_ROOT, path) if not os.path.isfile(name): raise Http404("File not found.") if request.user.is_staff: print "staff" serve_document(request, path) else: print "FORBIDDEN" raise PermissionDenied def serve_document(rcvd_request, path): print "Send " + path # set PRIVATE_MEDIA_USE_XSENDFILE in your deployment-specific settings file # should be false for development, true when your webserver supports xsendfile # This is currently zero if settings.PRIVATE_MEDIA_USE_XSENDFILE: response = HttpResponse(mimetype='application/force-download') response['X-Accel-Redirect'] = filename # Nginx response['X-Sendfile'] = filename # Apache 2 with mod-xsendfile del response['Content-Type'] # let webserver regenerate this return response else: print "Fallback serve" # fallback method return serve(rcvd_request, path, settings.MEDIA_ROOT) return serve(request, path, path, settings.MEDIA_ROOT) When I click on a link that has the file linked to, I get The view portal.views.dashboard.document_view didn't return an HttpResponse object. It returned None instead. This doesn't make much sense since I know the serve gets called with the right path, the file exists (in fact a previous version without staff check worked in downloading the files. I've seen people have issues due … -
How to tell a systemd initiated uWSGI daemon to use a specific python?
I cobbled together the below uWSGI configuration file from examples online. (◠﹏◠) Given this configuration -- which resides in /etc/uwsgi.d/myapp.ini and which is used to start the uwsgi daemon and, in turn, myapp via systemd/systemctl -- which configuration directive do I use to tell it to use a specific virtual-environment PYTHON for myapp? Is it home =? In other words, when it invokes the django.wsgi application, how can I tell it (or how does it know) to use: /home/myapp_unixHome/.virtualenvs/myapp/bin/python? # ======================================================= # Directories ... # ======================================================= home = /home/myapp_unixHome/.virtualenvs/myapp/ <--- Python virtualenv dir. chdir = /home/myapp_unixHome/myapp/ <--- Django App here. wsgi-file = /home/myapp_unixHome/myapp/django.wsgi <--- Including this django.wsgi file. static-map = /m=/home/myapp_unixHome/myapp/static/ <--- Static files. # ======================================================= # ======================================================= # TO BE NAMED ... # ======================================================= master = true processes = 5 # ======================================================= # ======================================================= # myapp communicates w/ nginx via a UNIX domain socket. # ======================================================= socket = /run/uwsgi/myapp.sock chmod-socket = 664 uid = nginx gid = nginx vacuum = true # ======================================================= # ======================================================= # uWSGI Log file. # ======================================================= logto = /var/log/uwsgi.log # ======================================================= Thank you. -
Attribute on QuerySet (not instances!) that survives chaining
What's the best way to implement "attribute chaining" for Django QuerySets? Two possible solutions are acceptable: For a fixed number of known attributes For an arbitrary number of unknown attributes Consider the following example: class MyQS(QuerySet): def annotate_do_something(self): today = datetime.today() qs = self.annotate(do_something=Case( When(day_to_do_something=today, then=Value(True)), default=Value(False), output_field=BooleanField) # record that day_to_do_something is relative to today qs.do_something_on = today return qs class MyManager(Manager.from_queryset(MyModelQS)): pass class M(Model): objects = MyManager() date_to_do_something = DateField() qs = M.objects.annotate_do_something() qs.do_something_on == date.today() # True (in most cases :p) qs.all().do_something_on # raises attribute error :( What's the best way to ensure that the attribute gets chained through QuerySet methods. The simplest way I can imagine is to add the following method to MyQS, but it uses internal API QuerySet._clone: def _clone(self, **kwargs): # kwargs of _clone are merged into the clone's __dict__ super(MyQS, self)._clone(do_something_on=self.do_something_on, **kwargs) Obviously I could just annotate each instance with this constant value, but the obvious concern here is that I'd need to evaluate the QuerySet to see if it's "stale", which would be silly. There are performance and maintainability concerns with this approach as well of course. A possible work-around would be to always call the annotate_do_something, but if the queryset … -
Updating a Model Form Class with Form Values in Django
I am populating a Model class object with values submitted via a form. The form, of type ModelForm, is mapped to the model class. The form can be updated by a user and needs to update the same record in the database. How can I update the Model class object with new values submitted via the form without having to explicitly overwrite each Model class field? Is there an easier, more elegant way to do this in Django? Any help would be appreciated. Thanks. -
Using django signals in channels consumer classes
I am trying to develop an auction type system, where a customer makes an order, and then different stores can offer a price for that order. An interesting part of this system is that when the order is initially created, the available stores will have 60 seconds to make their respective offer. When a first store makes their offer, the "auction" will now only have the next 20 seconds for other stores to make their own offer. If they do make another offer, in this smaller allocated time, then this 20 second is refreshed. Offers can keep on being received as long as there is enough time, which cannot surpass the initial 60 seconds given. class Order(models.Model): customer = models.ForeignKey(Customer) create_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now_add=True) total = models.FloatField(default=0) status = models.IntegerField(default=0) delivery_address = models.ForeignKey(DeliveryAddress) store = models.ForeignKey(Store, null=True, blank=True, related_name='orders', on_delete=models.CASCADE) credit_card = models.ForeignKey(CreditCard, null=True, blank=True, related_name='orders') class OrderOffer(models.Model): store = models.ForeignKey(Store, related_name="offers", on_delete=models.CASCADE) order = models.ForeignKey(Order, related_name="offers", on_delete=models.CASCADE) create_time = models.DateTimeField(auto_now_add=True) Besides these requirements, I also want to update the client when new offers arrive in real-time. For this, I'm using django-channels implementation of WebSockets. I have the following consumers.pyfile: from channels.generic.websockets import WebsocketConsumer from threading import Timer … -
Using django searcvector return duplicates objects
I have this code: vector = SearchVector('product__name', weight='A') + SearchVector('product__tags__name', weight='B') logger.info("busqueda libre, query %s" % query) data = StockItem.objects.annotate(search=vector).filter(search=query, product__cover__isnull=False, available=True).order_by(sort) And return duplicates objets in the query, i can use distinct because the order is give by the user, so what i can use for fix this problem? -
Django LDAPSearch Debug
I'm having troubles grouping users in Django. I can authenticate fine until I try group users. When I add AUTH_LDAP_GROUP_SEARCH I'm not able to login any longer with LDAP users and I get INVALID_CREDENTIALS: AUTH_LDAP_GROUP_SEARCH = LDAPSearch("cn=groups", ldap.SCOPE_SUBTREE, f"(objectClass={AUTH_LDAP_GROUP_SEARCH_ROLE})" ) AUTH_LDAP_GROUP_TYPE = PosixGroupType() The groups are posixGroups, the objectClass is correct on the search and are the groups are under cn=groups. Can I iterate over the AUTH_LDAP_GROUP_SEARCH results to ensure that it's returning correctly? What's the best way for me to debug this? -
Elements in List of List (django python HTML template engine)
I am really trying for 2 hours now and used the search, but i dont know what i am doing wrong Lets say i have a list of lists. Every list in the list has a variable count of items. timelist = [['12:00', '12:30'], ['13:00', '13:30', '14:00']] How can i get the value of each element... According to the doc i have to do it like this (i want to add the values into a table): {% for everylist in timelist %} {% for a in everylist %} <td>{{ a }}</td> {% endfor %} {% endfor %} But it doesnt work. What am i doing wrong? EDIT: I want to insert the value of the time into a website (e.g. 12:00). I am creating a web calendar. The value of the time shall be written into a table. The values are random. -
How to store user location disregarding language
I'm trying to develop a kind of ""simple"" social network using Django and Postgres. Users can signup by providing name, email and address. The address is a set of other fields: street, city, state, country. I want to provide an experience like Airbnb provides. Users can search for a city, state and country in any language they want. But I have to store it in a retrievable way to build reports and data analysis. For example, if someone search and register himself as citizen of 東京, I should be able to include this user on reports about Tóquio, or Tokyo. In other words, system has to know about cities disregarding the language. What I did is download a huge database with city names and aliases, but the maintenance is a pain. The database lack some cities and information. Also, this pain happens with state and countries too. Create development environments and migrate data almost lead mates to suicide. Actually, I'm thinking about drop my current cities database and tie it to a service like Google Maps, but I'm not sure if it will solve my reports requirements. How to create reports by country, state and cities using Google. I'm afraid … -
DJANGO download object has no attribute 'product_image_url'
I have I big database with images and i want to use download in my site where the user to can download personal images. i will try to use download method from this question(without sure if that is correct) is the fist time to try using download method in my site. but I take this error message : AttributeError at /download/125/ 'MyModel' object has no attribute 'product_image_url' here my code : models.py : def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): name = models.TextField() slug_name = models.SlugField() upload = models.ImageField(upload_to=user_directory_path) views.py: def download_image(request, id): descripts=MyModel.objects.filter(user=request.user) product_image =get_object_or_404(descripts,pk=id) print product_image product_image_url = product_image.product_image_url() image_url = MyModel.objects.get(descripts,pk=id).image_code_url() print product_image_url wrapper = FileWrapper(open(settings.MEDIA_ROOT+ product_image_url[6:], 'rb')) print wrapper content_type = mimetypes.guess_type(product_image_url)[0] response = HttpResponse(wrapper, mimetype=content_type) response['Content-Disposition'] = "attachment; filename=%s" % product_image_url return response urls.py : url(r'^download/(?P<id>\d+)/$',views.download_image, name='download_image'), settings.py STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR, 'static','static_dirs'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static','static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'static','media') MEDIA_URL = ('/media/') html : for data in images %} <a href="{% url 'download_image' data.id %}" class="btn btn-default">Download</a> {% endfor %} any idea to help me ? and if the image can be in .zip file I appreciate more. -
How to format a pandas dataframe for use with pandas-highcharts within Django
I'm trying to use pandas-highcharts within a Django project; I'm able to produce the graph, but the data is not plotted, so I'm guessing my pandas dataframe is not formatted correctly, or maybe I'm not using the right method to render the template. The result: My dataframe: Entrée d'eau - Archimède - 0013A2004166CFCD timestamp 2016-12-23 00:05:18+00:00 29.0 2016-12-23 00:05:27+00:00 29.0 2016-12-23 00:05:37+00:00 29.0 2016-12-23 00:05:47+00:00 29.0 2016-12-23 00:05:58+00:00 29.0 My view: from django.shortcuts import render from data.models import Value import pandas as pd from pandas_highcharts.core import serialize # [...] df = pd.DataFrame.from_records( Value.objects.filter(device=a).values("timestamp", "leak_value")) df.dropna(inplace=True) # not sure about this df.set_index("timestamp", inplace=True) df.sort_index(inplace=True) df = df.truncate( before=pd.to_datetime(request.POST.get("start")), after=pd.to_datetime(request.POST.get("stop"))) df = df.rename( index=str, columns={"leak_value": "{} - {} - {}".format( Room.objects.filter(unit=unit_sel).get(device=a), Device.objects.get(address=a).devicetype, a)}) print(df.head()) # DEBUG chart = serialize( df=df, render_to='Leak Values', title="Leak Values", output_type='json') return render(request, "leak_chart.html", context={"chart": chart}) My template (I include jquery and highcharts in base.html): {% extends "base.html" %} {% block body %} {% load staticfiles %} <div id="Leak Values"></div> <script type="text/javascript"> new Highcharts.Chart({{chart|safe}}); </script> {% endblock %} The page source: https://pastebin.com/EkJYQPLQ By the way I haven't found a tag for pandas-highcharts and I don't think I have the privileges to create it. I'm using pandas-highcharts 0.5.2