Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Refresh HTML table values in Django template with AJAX
Essentially, I am trying to do the same thing as the writer of this and this was trying to do. Which is to dynamically update the values of an html template in a django template via an ajax call. Both of them managed to fix their issue, however, I am unable to do so after 1.5 days. index.html {% extends 'app/base.html' %} {%load staticfiles %} {% block body_block %} <div class="container" > {% if elements %} <table id="_appendHere" class="table table-bordered"> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>User</th> <th>Date</th> </tr> {% for e in elements %} <tr> <td><a href="{{ e.A.url }}">{{e.A}}</a></td> <td><a href="{{ e.B.url }}">{{e.B}}</a></td> <td>{{ e.C }}</td> <td>{{ e.D }}</td> <td>{{ e.User }}</td> <td>{{ e.Date }}</td> </tr> {% endfor %} </table> {% else %} No data to display! <br/> {% endif %} </div> {% endblock %} <script> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: "{% url 'get_more_tables' %}", // URL to your view that serves new info data: {'append_increment': append_increment} }) .done(function(response) { $('#_appendHere').append(response); append_increment += 10; }); }, 1000) </script> views.py def index(request): elements = ElementFile.objects.all().order_by('-upload_date') context_dict = {'elements':elements} response = render(request,'app/index.html',context_dict) return response def get_more_tables(request): increment = int(request.GET.get('append_increment')) increment_to = increment + 10 elements = ElementFile.objects.all().order_by('-upload_date')[increment:increment_to] … -
Is there a generic way to implement column names?
I'm trying to implement the django-import-export library in a generic way. When setting the fields property in the Meta class there isn't a way to set the column names. When setting a Field() on the ModelResource directly it is possible. But as far as I know, you can't create those in a generic way. This is what I already have: def create_resource(django_model, model_fields): class ModelResource(resources.ModelResource): class Meta: model = django_model fields = model_fields return ModelResource() -
Django - Update integer field value in one model by change in other
Here is a project I've created to practice, in my models.py, class Post(models.Model): title = models.CharField(max_length = 140) author = models.ForeignKey(User, on_delete=models.CASCADE) votes = models.BigIntegerField(default=0, blank=True) class Vote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='voter') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='vpost') @receiver(post_save, sender=Vote) def update_votes(sender, **kwargs): # # ?? Here I have a Voteform with that user can vote any particular post. That part works well. Here is my question, whenever a user votes a particular post, I want votes field in Post model to increase as well. I know I can show it with {{post.vpost.count}} in my html. But I want that increment here. Other way I have tried, class Vote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='voter') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='vpost') def update_votes(self): p = self.post p.votes += 1 p.save() This one only works once, not working from second time, so I want to use signal method. So how can I update the vote field in Post model using signal? -
How to broaden coordinates from a location query?
I have an application where the user can enter a location query such as : Corinth The application will add a postfix ",Greece" and calculate the latitude and longitude coordinates for the city. So, the query for the coordinates will be Corinth, Greece. After, that the application returns the weather forecast for that location using DarkSkyApi. I want to only return forecasts for my country, which is Greece. The problem is that if a user types : London. Then, the location will return the coordinates of some obscure location in Greece (eg. a cafe) and give a forecast for that location. I think this creates confusion, because it gives the impression of a bug and that the app can predict forecasts for other countries as well. On the one hand, I want it to be specific enough to work for cities (eg. Athens), villages & neighborhoods (eg. Acropolis). On the other, not for minor locations (eg. cafes). How can I go about fixing that? -
Null value in column “marque_id” violates not-null constraint - Django 2.1.7
I have an issu with django, when I run django shell, and try to add some value in my database, I have an error. I used python manage.py migrations and python manage.py migrate before. >from store.models import Marque, Model charger = Model(name="Charger") charge.save() --- then I have this error, it work fine if I create "Marque" object Null value in column “marque_id” violates not-null constraint from django.db import models # Create your models here. class Contact(models.Model): email = models.EmailField(max_length=100) name = models.CharField(max_length=200) class Marque(models.Model): name = models.CharField(max_length=200, unique=True) class Model(models.Model): #Plusieurs models pour une marque reference = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) name = models.CharField(max_length=200) picture = models.URLField() marque = models.ForeignKey(Marque, on_delete=models.CASCADE) class Booking(models.Model): #plusieurs réservation pour un contact created_at = models.DateTimeField(auto_now_add=True) contacted = models.BooleanField(default=False) marque = models.OneToOneField(Marque, on_delete=models.CASCADE) model = models.OneToOneField(Model, on_delete=models.CASCADE) contact = models.ForeignKey(Contact, on_delete=models.CASCADE) Requirement.txt: Django==2.1.7 django-debug-toolbar==1.11 psycopg2==2.7.7 psycopg2-binary==2.7.7 pytz==2018.9 sqlparse==0.2.4 -
Django rest framework + django-allauth
I made a web application using python 3.6, django==1.11.5 and django-allauth==0.34.0 and would to add django-rest-framework + django-rest-auth, but there was problem, error about tzinfo. Is the django-rest-framework and django-allauth not compatible? -
Cannot see HEAD request when webhook api of survey monkey is called
I want to see a POST request on my server when someone submits survey.Following is the url of my survey. https://www.surveymonkey.com/r/HJM83KF For this i have created a function in my django views.py file.Here is the views.py file views.py import requests from django.contrib.auth import get_user_model #---------other imports--------------# def call_surveyMonkey(): s = requests.session() s.headers.update({ "Authorization": "Bearer %s" % "My_Access_Token", "Content-Type": "application/json" }) payload = { "name": "My Webhook", "event_type": ['response_completed'], "object_type": "survey", "object_ids": ["167018416"], "subscription_url": "http://ip-address-of-my-server/" } url = "https://api.surveymonkey.com/v3/webhooks" s.post(url, json=payload) print("The survey monkey has run") call_surveyMonkey() #calling the function above defined function. User = get_user_model() #--------------Other Django Views---------------------------------# This is want i see on my server. The survey monkey has run #This shows that my call_surveyMonkey() function has been called properly System check identified no issues (0 silenced). February 16, 2019 - 17:36:03 Django version 1.11.2, using settings 'tracker.settings' Starting Channels development server at http://0.0.0.0:80/ #-------other Django statements------------# But i cannot see any HEAD request on my server. I know that first survey monkey will call Http HEAD request for verification and then call POST request on my server when someone fills the form and hits 'Done' button. If i cannot see any HEAD request on my server by SurveyMonkey … -
What is the best way to store the last execution time of a scheduled task?
I need to store the last execution time of a scheduled task. Every scheduled task will use this data. What is the best way to store and keep up to date this data in Python/Django? I use Advanced Python Scheduler for scheduling. -
Script does not work on elemets inside infinite scroll
I have introduced infinite scroll in my code and now the like script does not work: the page is refreshed when I push the like button. Like-btn script: <script> $(document).ready(function(){ function updateText(btn, newCount, iconClass, verb){ verb = verb || ""; $(btn).html(newCount + '&nbsp<i class="' + iconClass + '"style="font-size:15px;"></i>' + verb ) btn.attr("data-likes", newCount) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, addLike, "fas fa-heart") } else { updateText(this_, removeLike, "far fa-heart") } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) </script>`enter code here` Infinite scroll script <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); </script> Infinite scroll works correctly but in the elements charged after infinite scroll, the like-btn script does not work. Could somebody see where is the problem? Thank you for your help! -
Two forms on same page (have different values and names etc in HTML)
I am trying to get two forms on one page. One to moderate/review a case (for moderators) and one to bookmark a case (for normal users). The way it is currently set up, both submit buttons are acting on the 'bookmark' form. i.e. when I 'review' a case, it creates a bookmark for that case and does not change the review status or comments. In models.py, 'Case' is a model with various attributes including 'status' and 'moderator_comments'. 'Bookmark' is a model with 'user' and 'case' as Foreign keys. In forms.py; they are both just normal ModelForms with 'model=' and 'fields=' only. I have tried adding various attributes like 'name', 'value', 'action' etc to the two forms and submit buttons but it hasn't fixed anything. I assume the broken logic is in my view because the 'bookmark' form is set to not show in the DOM (via {% if not bookmark %})on cases that already have a bookmark for that user. The problem persists where reviewing the case creates another bookmark (even though the bookmark form is not in the DOM in this case. def case_detail(request, case_id): if request.method == 'GET': case = Case.objects.get(id=case_id) media = Media.objects.filter(case_id=case_id) moderator_form = ModerateCaseForm(instance = … -
Django DetailView is not working with additional parameter
Hi I am new to Django programming please find my program which is not working.I am not getting any error though. urlpatterns = [ url(r'departmentlist/',views.DepartmentList.as_view(),name='departmentlist'), url(r'^departmentlist/(?P\d+)$',views.DepartmentDetail.as_view(),name='departmentdetail'), ] But when I am passing the '(?P\d+)$' alone it is working...Can any one help me. -
Route Params Not Display
I trying TO Display Deatils by Post id but i can not but post details showing on console log Please Guide Me To solve this problem I trying TO Display Deatils by Post id but i can not but post details showing on console log Please Guide Me To solve this problem <a href={"/detail/" + c.pk}>{c.title}</a> This is link to import React, { Component } from 'react'; import CustomersService from './projectservice'; const customersService = new CustomersService(); class ProjectDeatil extends Component { constructor(props) { super(props); this.state = { users: []}; } componentDidMount() { const { match: { params } } = this.props; if(params && params.pk) { customersService.getCustomer(params.pk).then((user)=>{ console.log( user); this.refs.title.value = user.title; this.refs.description.value = user.description; this.refs.image.value = user.image; this.refs.link.value = user.link; this.refs.body.value = user.body; this.refs.language.value = user.language; this.refs.slink.value = user.slink; this.setState({users: user.data}); }); } } render() { const{ users } = this.state; return ( <div > <div className="row e text-white"> {/* // {this.state.users.map( users => */} <h1 className="card-text text-white" key={users.pk}>Hello { users.pk}</h1> </div> </div> ); } } export default ProjectDeatil -
Django: How to add comments under post
I have trouble adding comments under my posts on the website I'm creating using Django. This is my story.html file, which is supposed to show the story title, the story itself, all the comments of the story and give users the ability to add a new comment. Although the form is shown, it is not usable, even though I have added comments to the stories manually through admin, none of them is shown. {% extends "pinkrubies/base.html" %} {% block content %} <div class="post-preview"> <h2 class="post-title"> {{ story.title }}</h2> <p class="post-subtitle"> {{ story.story }} </p> </div> <div class="post-preview"> {% for com in latest_comments %} <div class="post-preview"> <p class="post-subtitle"> {{ comment.com }} </p> </div> {% endfor %} </div> {% if user_id %} <div class="post-preview"> <form action="{% url 'pinkrubies:story' user.id story.id %}" method="post"> {% csrf_token %} <div class="form-group"> <p class="post-title"> Comments </p> <textarea id="text" name="text"class="form-control" placeholder="Comment" rows="4">{{ comment.com }} </textarea> </div> <button type="submit" class="btn btn-primary"> Submit </button> </form> </div> {% else %} <p class="post-meta">You must have an account to comment. <a href="{% url 'pinkrubies:login' %}"> Log in</a> or <a href="{% url 'pinkrubies:register' %}"> Register</a></p> {% endif %} {% endblock %} views.py def story_view(request, user_id, story_id): latest_comments = Comment.objects.order_by('-date') if story_id is not None: … -
Django URL view
I am trying to implement SayHello app page. This is my urls.py content from django.urls import path from hello.views import myView urlpatterns = [ path('admin/', admin.site.urls), path('sayHello/',myView), ] After adding this app to the URL, 'http://127.0.0.1:8000/sayHello/' works fine. But 'http://127.0.0.1:8000/' reports me the following 404 error page. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in editdojo_project.urls, Django tried these URL patterns, in this order: admin/ sayHello/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. How can I fix this bug? -
Django 'SessionStore' object has no attribute '_session_cache'
I am currently getting spammed by the error: dictionary update sequence element #0 has length 14; 2 is required that seems to be provoked by ('SessionStore' object has no attribute '_session_cache') I read in this question: Django project looking for "attribute '_session_cache'" that the issue might be that I don't have the django_session table, but I do and it's filled with content. Any idea what could provoke that? I am on Python 3.6.7, django 2.1.7 Here is the full error stack: File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in _get_session 190. return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "/path/to/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/path/to/venv/lib/python3.6/site-packages/django/utils/deprecation.py" in __call__ 90. response = self.process_request(request) File "/path/to/venv/lib/python3.6/site-packages/django/middleware/locale.py" in process_request 21. language = translation.get_language_from_request(request, check_path=i18n_patterns_used) File "/path/to/venv/lib/python3.6/site-packages/django/utils/translation/__init__.py" in get_language_from_request 222. return _trans.get_language_from_request(request, check_path) File "/path/to/venv/lib/python3.6/site-packages/django/utils/translation/trans_real.py" in get_language_from_request 464. lang_code = request.session.get(LANGUAGE_SESSION_KEY) File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in get 66. return self._session.get(key, default) File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in _get_session 195. self._session_cache = self.load() File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py" in load 43. s = self._get_session_from_db() File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py" in _get_session_from_db 34. expire_date__gt=timezone.now() File "/path/to/venv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/path/to/venv/lib/python3.6/site-packages/django/db/models/query.py" in get 390. clone = self.filter(*args, **kwargs) File "/path/to/venv/lib/python3.6/site-packages/django/db/models/query.py" in filter 844. return self._filter_or_exclude(False, *args, … -
how to fix ImportError in django when trying to import json?
i have a webpage that includes 2 chained dropdownlist coutries and cities where based on the selection of the first the second dropdownlist display the cities belongs to the selected country. the problem is that the first dropdownlist is displaying the fetched data from the database but the second one is still empty. and the system display the below error : from django.utils import json as simplejson ImportError: cannot import name 'json' from 'django.utils' models.py from django.db import models class country(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class city(models.Model): name = models.CharField(max_length=100) MouhafazatID = models.ForeignKey(country,on_delete=models.CASCADE) def __str__(self): return str(self.name) urls.py from django.contrib import admin from django.urls import path, include from.views import * urlpatterns = [ path('admin/', admin.site.urls), # path('', home), path('', home2), path('getdetails/', getdetails), views.py from django.shortcuts import render from django.http import HttpResponse from testapp.models import * from django.utils import json as simplejson # i think this is the error? def home2(request): countries = country.objects.all() print(countries) return render(request, 'home2.html',{'countries': countries}) def getdetails(request): #country_name = request.POST['country_name'] country_name = request.GET['cnt'] print ("ajax country_name ", country_name) result_set = [] all_cities = [] answer = str(country_name[1:-1]) selected_country = country.objects.get(name=answer) print ("selected country name ", selected_country) all_cities = selected_country.city_set.all() for city in all_cities: print … -
Model-formset genereates ValueError when rendered within if-statement
I have a template which renders model-formsets and organizes them by a common 'trade_id', so that I can update values and apply actions to all objects with the same 'trade_id' in a certain field. I tested the save()-functionality by hard-coding the 'trade_id' in views.py like this: PortfoliopositionFormset(queryset=PortfolioModel.objects.filter(trade_id=1)) This renders forms for all objects with 'trade_id' = 1, which I can then put inside <form>-tags in the template and apply actions to, and it works as intended. In order to show all objects and organize them into separate <form>-tags for each collection of objects with a shared 'trade_id' , I did this: views.py def PortfolioView(request): template_name = 'portfolio/portfolio.html' if request.method == "GET": id_list = [] queryset = PortfolioModel.objects.filter(insert_type='position') for obj in queryset: id_list.append(obj.trade_id) # No need to dive into details here, but this simply creates a list # of all available unique trade_id's in the model (there is only # one object with insert_type='position' for each 'trade_id') portfolio_object = PortfoliopositionFormset(queryset=PortfolioModel.objects.all()) context = { 'portfolio_object': portfolio_object, 'id_list': id_list, } return render(request, template_name, context) elif request.method == "POST": portfolio_object = PortfoliopositionFormset(request.POST) if portfolio_object.is_valid(): for form in portfolio_object: form.save() return HttpResponseRedirect('/portfolio/') portfolio.html {% for id in id_list %} <form method="POST"> {% csrf_token %} <table> … -
ImproperlyConfigured Set the xxxx environment variable - django-environ
In my settings.py i'm using django-environ like this: import os import environ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) env = environ.Env( SECRET_KEY=str, ) env_path = os.path.join(BASE_DIR, '.env') environ.Env.read_env('.env') SECRET_KEY = env('SECRET_KEY') My .env file looks like this SECRET_KEY = *!0#pu@ld)-e@knsmp#jo-75h$cy1c^c1bfgr97h++sb4_z42b However, when I run the app i get django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable The .env file is found and lines are being read from it, so there's no problem with finding it, but somehow it doesn't work. Am i missing something here? -
How to fix IndentationError: unindent does not match any outer indentation level for __str__
My problem is IndentationError: unindent does not match any outer indentation level for str . This is my code : from django.db import models from django.contrib.auth.models import User class Post(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published'), ) title = models.CharField(max_length=100) slug = models.SlugField(max_length=120) author = models.ForeignKey(User, related_name='chat_posts') body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') def str(self): return self.title and problem is with File "C:--------------------------\models.py", line 20 def str(self): ^ IndentationError: unindent does not match any outer indentation level Can someone help me with this? -
Good Django design practice to add a REST api later following DRY
I am starting a web application in pure Django. However, in the future, there might be a requirement for REST api. If it happens, the most obvious choice will be Django REST framework. Both the "old-fashioned" and REST parts share the models, however, the views are slightly different (permissions definitions, for example) and forms are replaced with serializers. Doing it the most obvious way would mean to duplicate the application logic several times, and thus a failure to follow DRY principle, and so the code becomes unmaintainable. I got an idea to write all the logic into models (since they are shared), but in such case, there will be no use of permission mixins, generic views and the code would not be among the nicest ones. Now I ran out of ideas. What is the best practice here? -
Django forms hide password hint
Is there a way to hide all form's field hint messages from the user,how to hide the password type hint for eg: photo given -
Why do formData objects show up as empty objects in backend for ng-file-upload?
So, I'm using formData objects to send sensitive information to Django using the ng-file-upload library. I tried sending in formData objects but they show up as empty QueryDict objects when I try to send them in formData format (which I'm assuming to be like an encryption of the object). The same issue is not encountered when I use $http service. I suspect the issue might be because of ng-file-upload using formData in its source code as well. (Basically, formData is created for formData). So, is my assumption correct ? What's happening exactly ? Scenario 1 (without using formData): parameters.data = { 'status': 'submitting', 'input_file': vm.input_file, 'method_name': vm.methodName, 'method_description': vm.methodDesc, 'project_url': vm.projectUrl, 'publication_url': vm.publicationUrl }; This parameters object is then passed to a service where Upload.upload is called. After logging request.data in Django, I correctly get the output as QueryDict which contains the said fields Scenario 2 (with formData): var formData = new FormData(); formData.append("status", "submitting"); formData.append("input_file", vm.input_file); formData.append("method_name", vm.methodName); formData.append("method_description", vm.methodDesc); formData.append("project_url", vm.projectUrl); formData.append("publication_url", vm.publicationUrl); parameters.data = formData; This parameters object is just as above, but the object in Django shows up as an empty QueryDict object instead of containing all the field like in the first case. -
Getting 403 for static files using django-s3-storage
I've set up the settings as follows: STATIC_ROOT = BASE_DIR + '/static' YOUR_S3_BUCKET = "tlot-static" # DEFAULT_FILE_STORAGE = "django_s3_storage.storage.S3Storage" STATICFILES_STORAGE = "django_s3_storage.storage.StaticS3Storage" AWS_S3_BUCKET_NAME = AWS_S3_BUCKET_NAME_STATIC = YOUR_S3_BUCKET # These next two lines will serve the static files directly # from the s3 bucket AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % YOUR_S3_BUCKET STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN but I keep getting: <?xml version="1.0" encoding="UTF-8"?> <Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>9F85922419DD93C0</RequestId><HostId>5lV1ft+jAOTvnqCvOC/fMSolHXS8foJde8XP1LxtYytlZLjejA2gvjIurYwt9Fn8Jxlgvy5IjOI=</HostId></Error> The files was deployed successfully with collectstatic, and I've set up the cors as per the docs on the bucket. What else do I need to do? -
Pulling data from db causing 404 page not found error
I'm trying to filter my views in such a way that when a specific school is chosen, pk of the school will be placed in a view function called major which would further query the db to display the proper majors corresponding to that school. I now get a page not found 404 error, and can't figure out why. url.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:Major>/', views.Major, name='Major') ] models.py from django.db import models class Major(models.Model): name = models.CharField(max_length=30, db_index=True) class School(models.Model): name = models.CharField(max_length=50, db_index=True) school_Major_merge = models.ManyToManyField(Major, through='School_Major') class School_Major(models.Model): major = models.ForeignKey(Major, on_delete=models.CASCADE) school = models.ForeignKey(School, on_delete=models.CASCADE) class professor(models.Model): ProfessorIDS = models.IntegerField() ProfessorName = models.CharField(max_length=100) ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4) NumberofRatings = models.CharField(max_length=50) #delete major from the model school = models.ForeignKey(School , on_delete=models.CASCADE) major = models.ForeignKey(Major , on_delete=models.CASCADE) def __str__(self): return self.ProfessorName views.py from django.http import HttpResponse from django.shortcuts import render from .models import professor, School, Major, School_Major def index(request): schools = School.objects.all() return render(request, 'locate/index.html', {'schools': schools}) def Major(request, school_pk): #Filter to a show the association of 1 schools majors school_choice = Major_School.objects.filter(school_id = school_pk) #Filter majors names required majors = Major.objects.filter(id = school_choice.major_id) return render(request, 'locate/major.html', {'majors' : … -
Dump JSON without escape sequence
I would like to dump my django model as a JSON file in order to use it to show points on a map by using leaflet. However, when I dump the JSON file it creates additional escape sequences for double quotes in JSON file. How do I create and save JSON file without escape sequences is my question. Below it is my code in views.py. Thank you very much in advance. def JSON(request): queryset = Poi.objects.all() queryset = serializers.serialize('json', queryset) queryset = queryset[:0] +'markers =' + queryset[0:] with open (r'C:\Users\Savas\Desktop\MY_WEB_PROJECTS\WEB_TOOLS\web_tools\static\js\queryset.json', 'w') as outfile: json.dump(queryset, outfile, ensure_ascii=False) return HttpResponse(queryset, content_type="application/json")