Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't upload few images with form in django
I have django app (django 1.6) and I have problem to send few images, to upload few images. On front-end side this is OK, I can drag and drop images and see them there. The problem starts when I push save button. From few images uploaded in front-end side, now I can see only one. So, for example, from 2 uploaded images in front-end, now I can see only one. Here is html where I'm uploading images: <ul class="uploads"> {% for formset in forms%} {{ formset.management_form }} {% for a in formset %} {% if 'can_edit_posts' in perm_list or a.attachment.value %} <li class="{% if not a.attachment.value %}empty{% endif %}" data-form-name="{{ a.attachment.html_name }}"> {{ a.id }}{{ a.post_locale }} {{ a.attachment.value.url }} {{ a.attachment.html_name }} <div class="preview"> <div class="action"> <span class="icon-hospital">Add Image</span> </div> <img src="{% thumbnail a.attachment.value 400x400 autocrop=False %}" alt=""> <input class="upload-media" name="{{ a.attachment.html_name }}" type="file" value="{{ a.attachment.name }}" multiple> <input type="hidden" class="files-to-exclude"> </div> <div class="description"> <div class="filename">{{ a.attachment.value.name }}</div> <div class="filesize">{{ a.attachment.value.size }}</div> <ul class="btn-group"> <li class="download"> <a class="button icon-download-alt" href="{{ a.attachment.value.url }}" target="_blank"></a> </li> {% if formset.can_delete and 'can_edit_posts' in perm_list %} <li class="delete"> {{ a.DELETE }} <label for="{{a.DELETE.auto_id}}" class="button icon-trash"></label> </li> {% endif %} </ul> </div> <div class="previews"></div> … -
Use a jQuery script with a HTML button
In my django admin form, I have a field which look like this. The Select All button use a jQuery script : $(document).ready(function () { $('#id_season_0').click(function (event) { //on click if (this.checked) { // check select status $('.checkbox').each(function () { //loop through each checkbox this.checked = true; //select all checkboxes with class "checkbox1" }); } else { $('.checkbox').each(function () { //loop through each checkbox this.checked = false; //deselect all checkboxes with class "checkbox1" }); } }); }); But the problem is : Select All is also a field in my models and I don't want to have it anymore. So I'm actually trying to apply a little modification. I would like to use a HTML button instead of BooleanField for SelectAll So I'm using this code in change_form.html : <button id="selectall" type="button" class="checkbox"> Select All </ button> I tried to change the id by : selectall but that doesn't work. Help please ? -
Nested for loop in django template not showing correct output
So i have this loop which is showing the correct output when i print it in my views.py file for x in list4: print x[0] for y in x[3]: print y[1] print "\n" but while running the same loop in django templqate to show the vales in the form it shows repeated output test.jinja2 code {% extends "base.jinja2" %} {% block content %} {% block body %} {% for x in ques %} <form class='form-horizontal' method=POST action="/test-portal/student/test/"> <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}"> <div class="form-group"> <input type="hidden" name="id" value={{x.0}}> <label for="ques_title" class="col-sm-2 control-label" name='ques_title'>{{x[3]}}</label> </div> {% for y in x[3] %} <!-- {% for b in y %} --> <div class="form-group"> <div class="col-sm-2"> <!-- <input type='checkbox' name='flag' id="new" value={{x}}> --> <label for="option" class="col-sm-2 control-label" name='ques_title'>{{y[1]}}</label> </div> </div> <!-- {% endfor %} --> {% endfor %} {% endfor %} <div class="form-group"> <button type="submit" class="btn btn-default" name='button' value='submit'>SUBMIT</button> <!-- <td><button type="submit" class="btn btn-default" name='button' value='options'>ADD OPTIONS</button></td> --> </div> </form> {% endblock %} {% endblock %} -
How do I create a page that inputs data in Mysql database using Django?
I want to create a Django app that takes some data from the user, not through the inbuilt admin page but through a page that I made. Then save the date to Mysql database. Finally, display the data in the Mysql database in a new page. How can I do this? -
Database "is being accessed by other users" error when using ThreadPoolExecutor with Django
I'm working on a project where we parse a somewhat large file and process each row asynchronously (we make API calls for each row) using ThreadPoolExecutor. This used to be done synchronously and we had a passing test suite. Now, however, when running the tests Django's default test runner errors out in teardown_databases: Traceback (most recent call last): File "manage.py", line 34, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/test.py", line 72, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python3.5/site-packages/django/test/runner.py", line 551, in run_tests self.teardown_databases(old_config) File "/usr/local/lib/python3.5/site-packages/django/test/runner.py", line 526, in teardown_databases connection.creation.destroy_test_db(old_name, self.verbosity, self.keepdb) File "/usr/local/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 264, in destroy_test_db self._destroy_test_db(test_database_name, verbosity) File "/usr/local/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 283, in _destroy_test_db % self.connection.ops.quote_name(test_database_name)) File "/usr/local/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.OperationalError: database "test_sftpm_db" is being accessed by other users DETAIL: There are 10 other sessions using the database. (We're using … -
Unable to find webpack bundle files
I build a Django/reactJS app and deployed into Heroku. It seems that Heroku unable to find my bundle javascript file which I build using webpack. ~.herokuapp.com/static/bundles/main-8a6ba07e9be57a159df0.js Error 404 not found This is my webpack configuration //require our dependencies var path = require('path') var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: './assets/js/index', output: { path: path.resolve('./assets/bundles/'), filename: '[name]-[hash].js', }, plugins: [ //tells webpack where to store data about your bundles. new BundleTracker({filename: './webpack-stats.json'}), //makes jQuery available in every module new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' }) ], module: { loaders: [ {test: /\.jsx?$/, exclude: /node_modules/, //use the babel loader loader: 'babel-loader', query: { //specify that we will be dealing with React code presets: ['react', 'es2015', 'stage-0'] } } ] } } My file directory looks like this `-assets -node_modules -app -djangoproject -templates -manage.py -package.json -Procfile -webpack.config.js` Everything works find in local. -
seek does not work with in memory file
I have Django REST and my endpoint accept POST with attachemtn. if serializer.is_valid(): instance = UploadedFile.objects.create( file=serializer.validated_data['file'], username=self.request.user.get_username(), ) Then I put file to the function. And repeatedly loop read this in-memory file. for pair in daterange(start_date, end_date): bkk_start_datetime = mom_datetime.datetime.combine(pair, mom_datetime.time(0, 0)) bkk_end_datetime = mom_datetime.datetime.combine(pair + timedelta(days=1), mom_datetime.time(0, 0)) ans_dict = { "bkk_start_datetime": bkk_start_datetime, "bkk_end_datetime": bkk_end_datetime, "pin_values": pin_values_from_file(instance, bkk_start_datetime, bkk_end_datetime) } ans.append(ans_dict) This function has problem because file does not seek to the first location. Although I put .seek(0) def pin_values_from_file(instance: object, start_date: datetime, end_date: datetime): csv_file = io.StringIO(instance.file.read().decode('utf-16')) csv_file.seek(0) # Seek the first line again. Otherwise next day will be zero all reader = csv.reader(csv_file, dialect='excel-tab') count = 0 holder = AwardHolder() logger.info(f"pin_values_from_file receive {start_date}, {end_date}") How to let it re-read in-memory file? -
Django - missing FROM-clause entry for table
Okay, its been a while yet I can not solve or understand this problem. I also looked the other ones questions which has the same or similar title but I think this one seems different. I am not a pro in django and its admin face, but trying. So any help would be great. I am currently trying to build an admin interface for listing the fan profiles. ( there are fans and famous users ) And I was able to list them by their deleted post count. ie. they post something and this can be deleted by moderators but not users theirselves. And I wrote an sql query for it. sql_deleted_post_count = """ SELECT COUNT(*) FROM posts_post WHERE posts_post.state = {state_deleted} AND posts_post.deleted_by_id != posts_post.user_id AND posts_post.user_id = profiles_user.id """.format(state_deleted=Post.STATE_DELETED) This seems okay in the first place. It lists the correct results for the correct users. But problem begins when I try to search a fan profile in the search section in the django admin panel. Here you can see the search section and the correct deleted post count lists When I want to search a fan profile, here what happens : ProgrammingError at /cp/profiles/fanprofile/ missing FROM-clause entry for … -
How can I validate the return value of upload_to callback against the max_length in Django?
I have a model field which is of FileField type and below is how it is defined in the model. some_file = models.FileField(upload_to=get_me_file_path, max_length=100) Here, get_me_file_path is a function which accepts the instance and the file name. This function prepends the relative local path (let us say this takes upto 30 characters) to the file name and returns the prepended file name. The file name originally comes from the user. The problem is, when the file name is between 71 characters and 100 characters long, the database refuses to store the file name into the field and consequently the application throws 500 Internal Server error. My question is what is the neat and Pythonic way of validating the string returned by the upload_to callback against the max_length? I have a solution which is working for me currently, but it involves hardcoding the max allowed length. Here is my working solution. In the Django form, I defined a clean_<fieldname> function which looks like this: def clean_some_file(self): in_file = self.cleaned_data['some_file'] if in_file is not None and len(in_file.name) > 70: raise forms.ValidationError('Too long file name!') return in_file The above solution propagates the error message to the form -> template -> user and work … -
Need API for Developer to post a content in Social Media from the platform with different users with python.
I need API for Developer to post a content in Social Media from the platform with different users with python. The Post should post from the particular user logged in that platform. Any suggestion for API provider? -
How to build a simple webpage to save a number and call it back next time?
I'm sure this is a SUPER noob question, but I'm having trouble finding resources which detail simple client-side server-side interactions. I've got a webpage where clicking a button uses a little JavaScript to increment a counter by one. Naturally when the page is refreshed, the number resets. How could I set up some simple backend or database that instead will save the number and call it back the next time the page is loaded? -
Pass associative array trough Ajax
I've been trying to understand AJAX, and I do manage to send single pieces of data. But when I try to send an array nothing goes trough. I've tried to format it as JSON, but not really been successful in that regard. I've searched trough stackoverflow by any combinations of tips and tricks have almost gotten me all the way. Here is the JS without most of the math to get the prices: var data = []; $('[id$="-subtotal"]').each(function () { subtotal = some_math; id = some_ID_Number; data['id-' + String(id)] = subtotal }); $.ajax({ url: '/test/', type: 'POST', dataType: "JSON", data: { 'prices': data, 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val() }, success: function (data) { } }); And I've been trying to access the array with: request.POST.get('prices') -
Django url not being found on live version (ubunutu nginx) - sometimes works on refresh
I took over a django project which had some urls in the url.py file. Every url pointed to a template and everything was working fine. On my local machine, I created a 2 new templates and added 2 lines in the url.py file to point to them: . . url((r'^register$'), TemplateView.as_view(template_name="accounts/register.html"), name="Registration Form"), url((r'^register-confirm$'), views.registration_confirm, name="Registration Pin Form"), . . (second url points to a function in the view) Everything works perfectly fine on my local machine. However when I deploy the project on an ubuntu server using nginx these urls, and these urls only are sometimes not found. I get the following error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: and the urls are nowhere to be found in the list. When I hit refresh SOMETIMES it works and sometimes it doesn't. How can this be? any explanations? Thanks -
Can django models deal with 'Class-level' attributes?
I am looking to build a django app that somehow handles 'class-level' attributes (via an abstract class?) in a way that they can be inherited if no project-specific equivalent value has been defined explicitly. Is this something that can be implemented in Django's model? It's clearly a messy hack but I was thinking I could 'hard code' rates of roles in the project class and use max() between the two: models.py class Project(models.Model): name=models.CharField(max_length=30) rate_role1=100 rate_role2=120 class hourly_rates(models.Model): project=models.OneToOneField( Project, on_delete=models.CASCADE, primary_key=True, ) role= models.CharField(max_length=20) rate= models.DecimalField(max_digits=8, decimal_places=2) -
How to call ugettext from Django shell?
I work on a Django project which is localized and works fine in many languages. Now for a reason I need to call ugettext from its shell. Here is what I did: >>> from django.conf import settings >>> settings.LANGUAGE_CODE u'fa-ir' >>> from django.utils.translation import ugettext as _ >>> print _("Schedule & Details") Schedule & Details As you see the phrase "Schedule & Details" did not print in Persian language. Is it possible to translate a phrase and then print it inside Django shell? Thank you -
Django Rest Framework validator not execute inside extra_kwargs
I have Administrator module extended from default Django User module. In Django Rest Framework, I create a serializer for this module with username and email validators. Everything go well when I declare validators inlined: class AdministratorCreateUpdateSerializer(ModelSerializer): username = serializers.CharField( source='user.username', validators=[UniqueValidator(queryset=User.objects.all())] ) email = serializers.EmailField( source='user.email', validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField( source='user.password', allow_blank=True, style={'input_type': 'password'} ) first_name = serializers.CharField( source='user.first_name' ) last_name = serializers.CharField( source='user.last_name' ) class Meta: model = Administrator fields = [ 'username', 'email', 'password', 'first_name', 'last_name', ] But the validators not execute when I declare it inside extra_kwargs: class AdministratorCreateUpdateSerializer(ModelSerializer): username = serializers.CharField( source='user.username', ) email = serializers.EmailField( source='user.email', ) password = serializers.CharField( source='user.password', allow_blank=True, style={'input_type': 'password'} ) first_name = serializers.CharField( source='user.first_name' ) last_name = serializers.CharField( source='user.last_name' ) class Meta: model = Administrator fields = [ 'username', 'email', 'password', 'first_name', 'last_name', ] extra_kwargs = { 'username': { 'validators': [UniqueValidator(queryset=User.objects.all())] }, 'email': { 'validators': [UniqueValidator(queryset=User.objects.all())] }, } Does this problem come from using source when define addition fields or something else? -
save values into database Django
Hi i am relatively new to Django. I have a timesheet for user to enters the details, when the submit button is chosen, the data in those filled-up fields will be saved into the Database. But i have no idea why mine doesnt work. As the values will be saved then it will be retrieved and be displayed in a table from in another html file. timesheet.html {% extends 'hrfinance/base.html' %} {% block title %} Timesheet {% endblock %} {% block link %} {% load staticfiles %} <link rel="stylesheet" href="{% static 'hrfinance/css/timesheet.css' %}"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> /*to ensure that all the textbox and checkbox have been filled before users can submit*/ function validation() { /*ensure start date has been entered*/ if (!$('#studentid').val().trim()) { alert('Please fill in student ID field'); } /*ensure start date has been entered*/ if (!$('#studentname').val().trim()) { alert('Please fill in student name field'); } /*ensure start date has been entered*/ if (!$('#sdate').val().trim()) { alert('Please fill in start date field'); } /*ensure end date has been entered*/ if (!$('#edate').val().trim()) { alert('Please fill in end date field'); } /*ensure checkbox has been ticked*/ if (!$('#agree').is(':checked')) { alert('Please indicate that you have satisfied all the requirements'); } else{ console.log('ok') } } … -
Inheritance in python 3.6
Can someone please explain why this doesn't work class MansionDesign(Listview): sequence = Design.objects.filter(design_type__name='maisonette').order_by('created_at').reverse() queryset = [sequence[i:i + 3] for i in range(0, len(sequence), 3)] template_name = 'designs/mansions.html' but when i change the above class to a subclass of view like below, class MansionDesign(View): def get(self, request): sequence = Design.objects.filter(design_type__name='maisonette').order_by('created_at').reverse() queryset = [sequence[i:i + 3] for i in range(0, len(sequence), 3)] return render(request, 'designs/mansions.html', {'object_list': queryset}) the code seems to work just fine. The error I get from the above class is 'name sequence is not defined'. I would appreciate some clarification on this. Thanks in advance. -
How to create api sub-resource in django rest framework
So coming from a java stack where one can create sub-resource using any of the java-ee stack (jax-rs, jersey, restlet, rest-easy). A java sample code snippet might look something like this. @Path('library') public class Library{ // some get post resource endpoint @Path('books') BookResource bookSubResource() {} } So if this were to be achieved in django rest framework. What is the best way or pattern to go about this, given we have a resource APIView called LibraryAPIView and BookAPIView Thanks -
How not to add data to index if its already in it?
I have command that adds data from database to elasticsearch index, here it is: class Command(BaseCommand): def handle(self, *args, **options): self.create_index() self.push_db_to_index() def create_index(self): indices_client = IndicesClient(client=settings.ES_CLIENT) self.es_index = 'my_foods_and_foods_by_ingredients' self.es_type = 'foods_and_foods_by_ingredients' if indices_client.exists(self.es_index): indices_client.delete(self.es_index) indices_client.create(index=self.es_index) indices_client.put_mapping( index=self.es_index, doc_type=self.es_type, body={ 'foods_and_foods_by_ingredients': { 'properties': { 'title': { 'type': 'completion', 'preserve_separators': False, 'preserve_position_increments': False, 'max_input_length': 50, 'analyzer': 'simple' }, 'restaurant_id': { 'type': 'long' } } } } ) def push_db_to_index(self): data = [ self.convert_data_to_bulk(each_object, 'create') for each_object in Food.objects.all() ] bulk(client=settings.ES_CLIENT, actions=data, stats_only=True) def convert_data_to_bulk(self, each_object, action=None): each_food_data = each_object.get_each_food_data() metadata = { '_op_type': action, '_index': self.es_index, '_type': self.es_type } each_food_data.update(**metadata) return each_food_data The problem is that its not rational, for example if there are 70.000 objects in the database, this script will delete them from index and than add them again. I want this script to add only that data that is not in index yeat but i cant figure out how to do it. Thanks for your time -
Can't sent few images in management_form, images are missing
I have django app (django 1.6) and I have problem to send few images, to upload few images. On front-end side this is OK, I can drag and drop images and see them there. The problem starts when I push save button. From few images uploaded in front-end side, now I can see only one. So, for example, from 4 uploaded images in front-end, now I can see only one. I don't know where can be a problem. I'll be thankful for any help. My url: url('^post/create/$', PostAdd.as_view(), name="event_create"), My views: class PostAdd(BasePostEdit): permission_required = 'calendars.can_create_posts' Paretnt view: class BasePostEdit(PermissionRequiredMixin, FormView): form_class = PostForm template_name = "calendars/post_form.html" success_url = reverse_lazy('home') def get_permission_object(self): return self.request.session["current_calendar"] def get_context_data(self, form): context = super(BasePostEdit, self).get_context_data() if form.instance.pk: # if we get an url to edit a post set the current calendar to posts # calendar self.request.session["current_calendar"] = form.instance.calendar # update seen by PostSeenBy.update_seen_by([form.instance, ], self.request.user) cur_calendar = self.request.session["current_calendar"] locales = [] initial = {'calendar': cur_calendar} for loc in cur_calendar.locales.all(): if not loc.pk in form.instance.locales.values_list("locale", flat=True): locales.append({'locale':loc}) if not form.instance.pk: AllLocaleFormset = inlineformset_factory(Post, PostLocale, formset=BasePostLocaleFormset, extra=cur_calendar.locales.count()) formset = AllLocaleFormset(initial=locales, instance=form.instance) else: PostLocaleFormset = inlineformset_factory(Post, PostLocale, formset=BasePostLocaleFormset, extra=len(locales)) formset = PostLocaleFormset(queryset=form.instance.locales.all(), initial=locales, instance=form.instance) if self.request.GET.get('pub_date', None): … -
Django queryset optimisation: Reverse lookup on _set with filter
I have these models and I need to do some calculations and present them to the user. I render approx 2-3k of rows which results in 4k queries done to the DB (shown from debug toolbar). Is there any way to optimize this? I've tried with prefetch_related but it just adds another query on top of 4k already that are being done.. class Cart(models.Model): name = models.CharField(max_length=15) def sum_for_this(self, taxtype, tax): return self.carttax_set.filter(tax__type__name=taxtype, tax__tax=tax).aggregate( sum=Coalesce(Sum('tax_amount'), Value('0')) ).get('sum') class TaxType(models.Model): name = models.CharField(max_length=10) class Tax(models.Model): name = models.CharField(max_length=100) type = models.ForeignKey(TaxType) tax = models.DecimalField() class CartTax(models.Model): cart = models.ForeignKey(Cart) tax = models.ForeignKey(Tax) base = models.IntegerField() tax_amount = models.IntegerField() What I do in template is: {% for cart in cartlist %} {{ cart.sum_for_this }} {% endfor %} I've tried with this but no effect: Cart.objects.prefetch_related('carttax_set').all() That method def sum_for_this is doing all the queries.. -
Django 1.9 Paginator in Search- page contains no results
views.py ITEMS_PER_PAGE = 3 def search_page(request): #************** Start of Paging code change for search results ************** form = SearchForm() query_set1=[] show_results = False if 'query' in request.GET: # if request.GET.has_key('query'): query = request.GET['query'].strip() if query: keywords = query.split() q = Q() for keyword in keywords: q1 = q & Q(title__icontains=keyword) q2 = q & Q(user__username__icontains=query) query_set1 = Bookmark.objects.filter(q1 | q2)[:20] form = SearchForm({'query': query}) paginator = Paginator(query_set1, 3) #query_set1 = paginator.object_list.order_by('id') try: page=int(request.GET['page']) except: page=1 bookmarks=paginator.page(page) variables = RequestContext(request,{ 'form': form, #'list_obj': bookmarks.object_list, 'bookmarks': bookmarks, 'show_results': show_results, 'check_page': paginator.object_list, 'show_tags': True, 'show_user': True, 'show_paginator': paginator.num_pages >=1 , 'has_prev': bookmarks.has_previous(), 'has_next': bookmarks.has_next(), 'page': page, 'pages': paginator.num_pages, 'next_page': page + 1, 'prev_page': page - 1, }) #return render_to_response('bookmark_list.html', variables) # ************** End of Paging code change for search results ************** if 'ajax' in request.GET: return render_to_response('bookmark_list.html', variables) else: return render_to_response('search.html',variables) paginator code in bookmark_list.html {% if show_paginator %} <div class="paginator"> Status of previous {{ has_prev }} & Next {{ has_next }} & show_paginator {{check_page}} {% if has_next %} <a href="?page={{ next_page }}">Next &raquo;</a> {% endif %} (Page {{ page }} of {{ pages }}) {% if has_prev %} <a href="?page={{ prev_page }}">&laquo; Previous</a> {% endif %} </div> {% endif %} Even though … -
how to change special characters sent from view to template python/django
I have a problem - trying to send object from view.py file into template, but apostrophe is converted to "& quot;" . This is my code: view.py file: total['test'] = {} total['test']['2017-02-10'] = 2000 total['test']['2017-03-10'] = 25000 total['test']['2017-04-10'] = 20400 total['test']['2017-05-10'] = 24000 return render(request, 'homepage.html', { 'total' : json.dumps(total), }) template: <script> console.log( JSON.stringify( {{ total}} ) ); </script> And result: console.log( JSON.stringify( {& quot;test& quot;: {& quot;2017-02-10& quot;: 2000, & quot;2017-03-10& quot;: 25000, & quot;2017-04-10& quot;: 20400, & quot;2017-05-10& quot;: 24000 } } ) I had to add the space between "&" and quot because of auto-convert this characters by stackoverflow. Thanks in advance, -
How to implement Yosai Authentication and Authorisation in Django Project?
I am trying to implement Yosai- Security Framework for Python applications in django project following this documentation. The Web Integration page says, yosai.web is designed to integrate with any kind of web application. It can integrate with any application framework, such as Django, Pyramid, Flask, or Bottle. This is made possible through application-specific implementations of the WebRegistry API. 1.What is WebRegistry? 2.How can use WebYosai to implement Authentication and Other functionalities. I have gone through the documentation but I could not understand the implementation.Any help would be greatly appreciated.