Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have a TypeError: expected string or bytes-like object during "migrate" (Django)
I am using Django. I changed something in my model, which is 'datefield'. I changed it from datetimefield ('taxi_time') to datefield ('taxi_date') & timefield ('taxi_time'). I did manage.py makemigrations but I couldn't manage migrate. Error is following. Running migrations: Applying taxi.0017_auto_20171214_2256... OK Applying taxi.0018_auto_20171214_2336...Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards field, File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 238, in add_field self._remake_table(model, create_field=field) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 113, in _remake_table self.effective_default(create_field) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 229, in effective_default default = field.get_db_prep_save(default, self.connection) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save prepared=False) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1301, in get_db_prep_value value = self.get_prep_value(value) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1296, in get_prep_value return self.to_python(value) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1258, in … -
How to print a form using reportlab package in django?
views.py in function some_view the drawing function p.doForm is not taking a Form model as input .what i have to do to print that form into pdf. i need to conver that object into string or send info form requests from django.http import HttpResponseRedirect, HttpResponse, request from django.shortcuts import redirect, render from .forms import Form_db_att from django.utils import timezone from .models import FormDb # Create your views here. def home(request): if request.method == 'POST': form = Form_db_att(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.timestamp = timezone.now() model_instance.save() return HttpResponseRedirect('/home/test') else: form = Form_db_att() return render(request, 'mforma/name.html', {'form': form}) def thanks(request): form = Form_db_att(request.POST) model_instance = form.save() model_instance.save() return render(request, 'mforma/thanks.html', {'form': form}) from reportlab.pdfgen import canvas from django.http import HttpResponse def some_view(request): # Create the HttpReormponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = ' filename="somefilename.pdf"' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.doForm(Form_db_att) # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response -
How to force duration display as H:i in django?
I have a duration field which with validations, the maximum is 24 hours. However when 24 hours is displayed it shows as: 1 day, 0:00:00 I want it to show as 24:00 I am currently displaying the DurationField: <td>{{ entry.duration }}</td> -
Http delete method using jQuery ajax on django rest backend fails on Safari, but works in Chrome
I want to use django rest framework as backend and jQuery in the frontend to post and delete. Using $.ajax POST works fine. But delete call fails on Safari but works in Chrome. Here is the sample code: django models.py: from django.db import models class Article(models.Model): title = models.CharField(max_length=250) content = models.TextField() create_date = models.DateTimeField(auto_now_add=True) urls.py: urlpatterns = [ path('api/v1/articles/', views.ArticleList.as_view()), path('api/v1/articles/<int:pk>', views.ArticleItem.as_view()), ] views.py: class ArticleList(generics.ListCreateAPIView): queryset = Articles.objects.all() serializer_class = ArticleSerializer class ArticleItem(generics.RetrieveUpdateDestroyAPIView): query set = Articles.objects.all() serializer_class = ArticleSerializer serializer.py class ArticleSerializer(serialisers.ModelSerializer): class Meta: model = Article fields = ('id', 'title', 'content', 'create_date') jQuery: # on delete link $("#talk).on('click', 'a[id^=delete-]', function() { var pk = $(this).attr('id').split('-')[1]; delete_article(pk); }); function delete_article(pk){ $.ajax({ url: "api/v1/articles/"+pk, type: "DELETE", data: { pk: pk }, success: function(son) { $('#post-'+pk).hide(); console.log("delete successful") }, }) }; In Safari 11.0.1, in console it only shows "0: undefined". It is not going into success loop. In Chrome delete function is successful. -
Library, but also a project impacting another
In the moment, I have two github repositories, i.e. repo1 and repo2. Both are two django projects created by our team. In requirements.pipin ~/work_projects/repo1, I have the line -e git+ssh://git@gitlab.com/repo2.git@de5622dcf0b9a084f9b0a34cdd1d932026904370#egg=repo2 Hence, repo2 becomes a library used by repo1 in ~/.virtualenvs/venv/src (repo1's virtual environment). In the moment, I need to modify both repositories at the same time. My main focus in the moment is that each time I modify repo2, I need to test out the results on repo1. I want to look at the impact of repo2 on repo1 once modified. I don't want to push my changes on github and reinstall repo2 on repo1 each time I want to see those changes. How could I make it works easily, workaround? -
Basic authentication curl reqest to django request
I want to convert this curl request to django request curl -user admin:cadmin --request GET http://13.125.119.197:8050/lua/iface_ports_list.lua?clisrv=server -
How to check django staff user first time login in admin panel?
I am workign on a django project and i am using the default auth app for authentication. I know that there is a last_login field in user model which stores the user's last login time. When a staff user logs in first timeinto the admin panel, i want to check if last_login field is none & redirect him to the change password page. I want to know where should i put this check ? Do i need to extend the login form, if yes how to do i pass it to my login function as the admin url's are generated by django admin app. Is there any login callback fucntion in django where i can do this ? -
Django Admin, modify/customize the names in the select box of a manytomany field
I have 2 models Category and Product. Category has a FK to itself, and Product a FK to Companies. class Product(Meta): categories = models.ManyToManyField(Category, related_name='products') class Category(SEO, MetaData): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) In Django Admin in Product Create/Edit Page I need to select the Categories for Parent. At this moment is just a long select box, with the names of Categories. I want to introduce the all path of the category-subcategory. Ex: Now: Category A Name Need: Category Parent Name :: SubCategory Parent Name :: Category A Name I don't want to modify def str because is used also in other places. -
Admin InlineForm add links to Detail Page of the Inline Model and add custom javascript
In Admin for InlineForm there is a link that goes to the website, be default the text is (View on site). I want to add a similar link that goes to that model(that is inline) Detail Edit Page. Insert a JavaScript script in one of the Edit/Details Model Page in Admin How can this be done ? -
d3 chart not responsive inside split container
I want to make this d3 js library chart responsive inside split pane. I use split.js for split pane and container. see this example Any helpful reply can be appreciated. Thanks in Advance <!DOCTYPE html> <html lang="en"> <head> <title>Split.js</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css"> <style> html, body { height: 100%; } body { padding: 8px; background-color: #F6F6F6; box-sizing: border-box; } .split { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; overflow-y: auto; overflow-x: hidden; } .content { border: 1px solid #C0C0C0; box-shadow: inset 0 1px 2px #e4e4e4; background-color: #fff; } .gutter { /*background-color: transparent;*/ background-color: #00000017; background-repeat: no-repeat; background-position: 50%; } .gutter.gutter-horizontal { cursor: col-resize; background-image: url('vertical.png'); } .gutter.gutter-vertical { cursor: row-resize; background-image: url('horizontal.png'); } .split.split-horizontal, .gutter.gutter-horizontal { height: 100%; float: left; } </style> <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script> </head> <body> <div id="c" class="split content"> <div id="a" class="split split-horizontal"> <div id="chart-div" style="width:50vw;height:80vh;border:1px solid blue;"></div> </div> <div id="b" class="split split-horizontal"> <textarea row="8" style="height: 90%; width: 100%;"></textarea> </div> </div> <div id="d" class="split content"> <!-- <textarea row="8" style="height: 90%; width: 100%;"></textarea> --> </div> </body> <script src="split.js"></script> <script> Split(['#a', '#b'], { direction: 'horizontal', gutterSize: 8, sizes: [50, 50], cursor: 'col-resize' }) Split(['#c', '#d'], { direction: 'vertical', sizes: [50, 50], gutterSize: 8, cursor: 'row-resize' }) Split(['#e', '#f'], { direction: 'vertical', sizes: … -
Temporal Database with Django Rest Framework using perform_update
We are trying to implement a temporal database so that we are able to track changes made All our models have the following fields vt = models.DateTimeField(db_column='VT', default=datetime(3000, 12, 31, 23, 00, 00, 000000)) # Value To vflag = models.IntegerField(db_column='VFlag', default=1) # Version Flag 1 = Current, 0 = Old When using the Django rest framework I’ve tried to modify the perform_update in my viewset to duplicate the existing record, make the updates and then set temporal fields appropriately. It works when I have 1 record and the first update However once I try and make a second update it fails and create a duplicate of the changes and overrides the very first record. Original Record Currency = AUD, VFlag = 1, VT = time1 Perform update - success Currency = USD, VFlag = 1, VT = time2 Currency = AUD, VFlag = 0, VT = time1 Next perform update currently produces - fails Currency = GBP, VFlag = 1, VT = time3 Currency = GBP, VFlag = 1, VT = time3 Currency = USD , VFlag = 0, VF = time2 Expected update output Currency = GBP, VFlag = 1, VT = time3 Currency = USD, VFlag = 0, … -
Django and Flask on same nginx server
I currently have a Djago app running on my main site when I visit mysite.com. However, I'd like mysite.com/flaskapp to run a separate Flask application. I'm able to set up two nginx site-enabled config files and run each app on a different port but, for various reasons, I'd like to run them all on the same port (if possible). When I configure my flaskapp/ location in my nginx server file I get a 404 error. Here's my supervisor config file: [program:MYSITE] command=/var/www/html/MYSITE/prodenv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/MYSITE.sock MYSITE.wsgi directory=/var/www/html/MYSITE/public_html autostart=true autorestart=true stderr_logfile=/var/log/MYSITE.err.log stdout_logfile=/var/log/MYSITE.out.log [program:FLASKAPP] directory=/var/www/html/MYSITE/public_html/FLASKAPP/api command=/var/www/html/MYSITE/public_html/FLASKAPP/venv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock FLASKAPP:app autostart=true autorestart=true stderr_logfile=/var/log/FLASKAPP.err.log stdout_logfile=/var/log/FLASKAPP.out.log And my nginx site-enabled file: server { listen 80; listen [::]:80; server_name MYSITE; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/html/MYSITE/public_html; expires 30d; } location / { include proxy_params; proxy_pass http://unix:/var/www/html/MYSITE/public_html/MYSITE.sock; } location /FLASKAPP/ { include proxy_params; proxy_pass http://unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock; } } I wrote a function to check the request url @app.errorhandler(404) def page_not_found(error): return 'This route does not exist {}'.format(request.url), 404 Which returns: This route does not exist http://MYSITE/FLASKAPP The Flask app is clearly working, but the routing is screwed up. How can I fix this? -
remove multiple cross sign when using python autocompelete light in django
I have implemented django-autocomplete-light with django 1.5. But in that i have face one issue like when i set default value of form, this library display multiple cross sign for single record. In that i have used choiceWidget. Here I attached image of issue. Here Some of code : event_form = event_form_class(initial={'klant': klant}) forms.py (in that event_form_class define ) self.fields['klant'].widget = autocomplete_light.ChoiceWidget('KlantAutocomplete') in template i have used following line: {{ event_form.klant }} -
Where can I write the after query logic in RetrieveAPIView?
Where can I write the after query logic in RetrieveAPIView? In my models.py I have a Message class: class Message(models.Model): """ message """ message_num = models.CharField(default=getMessageNum, max_length=16) title = models.CharField(max_length=64) content = models.CharField(max_length=1024) is_read = models.DateTimeField(null=True, blank=True) create_user = models.ForeignKey(User, related_name="created_messages") receive_user = models.ManyToManyField(User, related_name="received_messages") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.title In the views.py: # the message list class UserMessageListAPIView(ListAPIView): serializer_class = UserMessageSerializer permission_classes = [] def get_queryset(self): user = self.request.user messages = user.received_messages.all() return messages # the message detail class UserMessageRetrieveAPIView(RetrieveAPIView): serializer_class = UserMessageSerializer permission_classes = [] def get_queryset(self): user = self.request.user messages = user.received_messages.all() return messages You see, in the UserMessageRetrieveAPIView I can retrieve the message instance. How can I do the logic to set the message's is_read ? Where I can set it? -
django HTML ajax did not alert?
I finally get the report successfully, but the ajax-alert did not show, just nothing shows in my website. why this happened? how to re-write hte code ? here is my code: ajax: function get_report(dataname){ $.ajax({ url:"/file_parse/", type:"POST", contentType: "application/json", async: true, data:JSON.stringify({ 'button':'button2', 'data':dataname }), //提交参数 success:function (data) { if(data.status == 'success'){ alert('OK') } } }) } <td> {% csrf_token %} <input type="button" id="btn2" class="btn btn-info btn-xs" name="{{item.sn}}" value="report" onclick="get_report(this.name)"> </td> views: if button_name == 'button2': ...... report.save return HttpResponse("{'status':'success'}", content_type='application/json') -
django test cases can't get past the @login_required decorator on a view function
I've scoured stackoverflow and tried several different solutions, but my test code always goes to the login redirect. This is what I have: class LoggedInSetup(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create(username="lolwutboi", password="whatisthepassword") self.client.login(username='lolwutboi', password='whatisthepassword') number_of_submissions = 13 for sub in range(number_of_submissions): Submission.objects.create(title='Amazing', description='This is the body of the post', author=str(self.user), pub_date=timezone.now()) class LoggedInTestCases(LoggedInSetup): def test_logged_in_post_reachable(self): self.client.login(username='lolwutboi', password='whatisthepassword') resp = self.client.get('submission_post') self.assertEqual(resp.status_code, 200) -
What steps should I follow on creating Django based Facebook app?
I noticed that a lot of code snippets found on the internet are outdated or deprecated, that's why I want to ask somebody experienced about what library or SDK should I use to quickly and painless create an web application that will retrieve some facebook user data (by consent), process it and output a result ? I am familiar with Django, that's why I want to do that in python/django. Also I will be thankful if some snippets / examples provided. Basically, it would help me a lot in my process of understanding how it works. -
Django seems to be ignoring my CSRF token header
I am updating a project from Django 1.8 to Django 1.11. This project was in a functional (production-ready) state prior to me beginning upgrade work - so I suspect that there's a Django / Django REST Framework code change that I've been caught up in. I have a REST / JSON API exposed via Django REST Framework, and am interfacing with this API via JavaScript. Using 'unsafe' HTTP verbs against the API (e.g. POST) is resulting in a 403 Forbidden response: {"detail":"CSRF Failed: CSRF token missing or incorrect."} I can clearly see (in Chrome developer tools) I am passing a CSRF token via a HTTP header: HTTP_X_CSRFTOKEN:dTOkbfkOn1cumhbF64nHSvLbdC4k95vNgRVZ0WleUDLKl5Iuo95flMkKyKFvFIPp Which corroborates with my CSRF_HEADER_NAME setting: In [3]: settings.CSRF_HEADER_NAME Out[3]: 'HTTP_X_CSRFTOKEN' (I am setting this by passing the CSRF token to JavaScript in a template file, which I haven't included because this doesn't seem to be the broken part (I can see the CSRF token header)). Is anyone aware of a Django / DRF change that could've affected me? -
How to Embed Code and Images in a Blog Post
I'm trying to teach myself Django, by creating a personal blog. At the moment I have a Post class in my models, that stores the body as a TextField. Similar to class Post(models.Model): title = models.CharField(max_length=150) body = models.TextField() author = models.ForeignKey(Author, related_name='blog_posts') published = models.DateTimeField(default=timezone.now) slut = models.SlugField(max_length=100, unique_for_date='publish') Which does 90% of what I want. What I want to be able to do though, is include things in the body of the post that aren't text. Specifically images, and code snippets. How can I achieve that? Is there a data type that I can use? Or some other way? -
Posting json data to django rest create api view?
I have a form: class ProductFormView(FormView): form_class = ProductForm template_name = 'forms/ajax.html' success_url = '/form-success/' model looks as: class Product(models.Model): name=models.charfield() category=models.Foreignkey(Category) ... class Category(models.Model): type=models.Foreignkey(Type) created=.. .... and ajax.html: $(document).ready(function(){ var $myForm = $('.my-ajax-form') $myForm.submit(function(event){ event.preventDefault() var $formData = $(this).serialize() $.ajax({ method: "POST", url: 'api/create', data: $formData, success: handleFormSuccess, error: handleFormError, }) }) function handleFormSuccess(data){ console.log(data) } function handleFormError(jqXHR, textStatus, errorThrown){ console.log(jqXHR) console.log(textStatus) console.log(errorThrown) } }) To send the product category through the form onto api I used the view to obtain the object through context data.Its not working ..How can we send the object of category through ajax? -
Testing multiple file upload to a model viewset using APIClient's post in Django Rest Framework
I'm new to Test Driven Development and was trying to test an endpoint like so: url = '/v3/edm-list/extract/' c = APIClient() c.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) with open(test_email_list_path, 'rb') as eml, open(test_exclude_list_path, 'rb') as exl: data = { 'tickers': tickers, 'email_list': eml, 'exlude_list': exl, 'exclude_keywords': exclude_keywords, 'simular_user_num': similar_user_num } response = c.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) Using APIClient's post, I'm sending a post request to my model viewset: class EDMListViewSet(viewsets.ModelViewSet): queryset = EDMList.objects.all() serializer_class = EDMListSerializer With the model: class EDMList(models.Model): tickers = models.CharField(max_length=512) email_list = models.FileField(upload_to='edm_list/consolidated_emails') exclude_list = models.FileField(upload_to='edm_list/excluded_emails') exclude_keywords = models.CharField(max_length=512) similar_user_num = models.IntegerField() And serializer: class EDMListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = EDMList fields = ('tickers', 'email_list', 'exclude_list', 'exclude_keywords', 'similar_user_num') Now whenever I run my tests, it returns: Traceback (most recent call last): self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 400 != 200 But whenever I open the browsable API, and post there, I runs correctly. I'm guessing the problem is how I use the client's post, but I have no idea what I'm doing wrong. -
how to simplify this code in django views?
total = { 'count': 0, 'price': 0 } for goods in estimate.goods_list.all(): total['count'] += goods.count total['price'] += goods.count * goods.goods.price return render(request, 'estimate/detail.html', {'estimate':estimate, 'total': total}) in django views, how to simplify this codes? can i delete the for block? -
functional test in django cant find an element by id
I want to get the content of a table in a html file through browser.find_element_by_id(), but I always get the same error, even when I have tried different options. I don't know whether the error is in the html, the urls, the views or the tests files. This is the error I get: ====================================================================== ERROR: test_multiple_users_can_start_lists_at_different_urls (functional_tests.tests.NewVisitorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/hugo/Code/AttractoraProject/AttractoraDjango/functional_tests/tests.py", line 71, in test_multiple_users_can_start_lists_at_different_urls self.wait_for_row_in_list_table('1: Buy peacock feathers') File "/home/hugo/Code/AttractoraProject/AttractoraDjango/functional_tests/tests.py", line 27, in wait_for_row_in_list_table raise e File "/home/hugo/Code/AttractoraProject/AttractoraDjango/functional_tests/tests.py", line 21, in wait_for_row_in_list_table table=self.browser.find_element_by_id('id_list_table') File "/home/hugo/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 341, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "/home/hugo/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 855, in find_element 'value': value})['value'] File "/home/hugo/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute self.error_handler.check_response(response) File "/home/hugo/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="id_list_table"] This is the urls.py file: from django.conf.urls import url from django.contrib import admin from Attractora import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home_page, name='home'), url(r'^Attractora/new$', views.new_list, name='new_list'), url(r'^Attractora/the-only-list-in-the-world/$', views.view_list, name='view_list'), ] This is the views.py file: from django.shortcuts import redirect, render from Attractora.models import Item # Create your views here. def home_page(request): return render(request, 'home.html') def view_list(request): items=Item.objects.all() return render(request, 'list.html', {'items':items}) def new_list(request): Item.objects.create(text=request.POST['item_text']) return redirect('/Attractora/the-only-list-in-the-world/') This is the … -
CSS disappears when 'DEBUG' Django is turned False
I'm working with Django and I'm using a AdminLTE framework for the estilização, but, when I turn the DEBUG to False, the page shows with pure html. DEBUG = True: DEBUG = False: -
parse python datetime object in javascript within django app
I'm passing the following variable to a template: from django.utils import timezone dt = timezone.now() print(type(dt)) # <class 'datetime.datetime'> Everything works fine if I use it in my HTML directly: {{ dt | date:'D d M Y' }} which renders to Thu 14 Dec 2017. However when I try to access the variable in my javascript I get an error: <script> {{ dt | safe }} </script> Uncaught SyntaxError: missing ) after argument list Furthermore, I get a slightly different error when I try to render a list of datetime objects: dt_list = [timezone.now() for _ in range(3)] and within my js: <script> console.log({{ dt_list | safe }}) </script> Uncaught SyntaxError: Unexpected token < So my question is how can I convert a python datetime object to something I can use in JS?