Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, url configuration reverse question. Gives ImproperConfigured
I tried to use this 2 lines to check if url reverse works...: from django.urls import reverse reverse('country-autocomplete') It suppose to give me: u'/country-autocomplete/' I did this earlier and it worked perfectly, since I had couple of problems and did couple of changes in environment(?). Now I'm trying to run these commands in cmd->python with swthed on environment and it gives me this fault: from django.urls import reverse reverse('raildict-autocomplete') Traceback (most recent call last): File "", line 1, in File "C:\Users\me\Envs\sc_project\lib\site-packages\django\urls\base.py", line 31, in reverse resolver = get_resolver(urlconf) File "C:\Users\me\Envs\sc_project\lib\site-packages\django\urls\resolvers.py", line 69, in get_resolver urlconf = settings.ROOT_URLCONF File "C:\Users\me\Envs\sc_project\lib\site-packages\django\conf__init__.py", line 76, in getattr self._setup(name) File "C:\Users\me\Envs\sc_project\lib\site-packages\django\conf__init__.py", line 57, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting ROOT_URLCONF, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What could be done to make it not working and what could be done to make it work? Thank you! -
How to show Django page with VenoBox?
Need the content of the Django page in the grey container but it's displayed over it That's how I link from <a href="{% url 'work' work.id %}" data-vbtype="ajax" class="venobox" title="Portfolio Details"></a> enter image description here -
relationships's visualization on localhost admin
I've settled one models.py (with two different classes), both of them appear on admin (localHost) where are pointing to two different databases. from django.conf import settings from django.db import models class Alimenti(models.Model): alimento = models.CharField(max_length=250, null=True) codice_alimento = models.IntegerField(unique=True, null=True) parte_edibile = models.FloatField(blank=True, null=True) def __str__(self): return '{} {} {} '.format( self.alimento, self.codice_alimento, self.parte_edibile ) class Genere(models.Model): alimento = models.CharField(max_length=250, null=True) gruppo_merceologico = models.CharField(max_length=250, null=True) codice_alimento = models.IntegerField() def __str__(self): return '{} {} {}'.format( self.alimento, self.gruppo_merceologico, self.codice_alimento ) Between the two classes, there is only one column with same IntegerField (codice_alimento) which I would like to use as one-to-one relationship, so that if I visualize on the admin page and I click over that column's value it open the correspondent row of the other Class' value. First, is it possible? Second, how to process it? I've tried both cases, one-to-one relationship and foreign-keys, none of these were working properly. I did NOT set primary keys since it does automatically when I run makemigrations but it doesn't lead me anywhere. None of cases here posted enlighten me about the solution. I am stuck on that issue and lost energies to figure it out, help please. -
Which framework is better to work with pycharm and django? [closed]
I have 45 lakh record in database. I need to develop a system in python using django which will perform elastic search on the database by searching for names and ID's Which framework i can use to build this system pycharm or vscode? -
Postgresql Generated Column requires sum of multiple integer array columns
I have a table that has 2 integer columns and 2 integer array columns that keep scores in them. For example, my row would look like the follow: { physical_ed: 40, music: 90, first_term: {10,23,43}, second_term: {1,5,5,7} } The array fields are declared as an integer[]. I need to generate a score column that sums up all of these fields. So far I have tried: ALTER TABLE scores DROP IF EXISTS score; ALTER TABLE scores add COLUMN total_score integer GENERATED ALWAYS AS (physical_ed::integer + first_term[3]::integer + second_term[1]::integer + second_term[2]::integer + second_term[3]::integer) STORED; The problem I have with the above, is it does not account for varying values in the array but sometimes that field could have 5 different values instead of just 3. I have tried running a select statement and I can calculate the sum of each array in a select statement normally like so: SELECT *, (SELECT SUM(s) FROM UNNEST(first_term) s) as total_first_term from scores; Unfortunately, this does not work inside a generated column query and we do need it to be part of our generated total_score sum. -
Update MySQL database with new field in Django
I have an existing MySQL database and all the models are created using makemigrations Django command. I updated my models with a new field and I run: python manage.py makemigrations <app> python manage.py migrate Although the makemigrations command adds the new field to my model, when the migrate command runs, I get the output: No migrations to apply. I want to update my schema without deleting the previous one. any thoughts? -
how to define a form field in modal django inlineformset
i want to submit child form with javascript pop up ,if number_of_cars = 3 it will pop up a form with 3 input fields for Car car_name , i have dont it from front end , but i dont know to add them to the pop up form <form method="POST">{% csrf_token %} <div class=" col-12 "> <div class="col-12 col-sm-9 col-md-12 divColor mt-2 mx-auto row " > <div class=" col-12 col-sm-9 mx-auto row p-0"> <div class="col-12 col-md-6 p-0 mx-auto text-center"> <br> {{form.owner | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.number_of_cars | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:qua'}} <input type="button" class="btn btn-light col-12 col-sm-10 mx-auto" name="" id="CARBTN" value="CAR" data-target="#CAR" data-toggle="modal"> </div> </div> <button class="col-4 mx-auto shadow-lg border-right border-left">insert</button> </div> </div> <div id="CAR" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="my-modal-title">CAR</h5> <p class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span></p> </div> <div class="modal-body"> </div> </div> <button type="submit">save</button> </div></div> </form> <script> $(document).ready(function(){ $('#CARBTN').on('click',function () { let allValue=[]; let numberOfInput=$('#qua').val(); let allContent=''; let justforName=0; let numOfContent=$('.modal-body input').length; for(let j=0;j<numOfContent;j++){ justforName=j+1; allValue.push($('input[name="CAR'+justforName+'"').val()); } if(numOfContent!=numberOfInput){ for(let i=0;i<numberOfInput;i++){ justforName=i+1; allContent+='<input class="form-control"' +'type="text" name="CAR'+justforName+'"' +'placeholder=" CAR '+justforName+'">'; } $('.modal-body').html(allContent); } for(let j=0;j<allValue.length;j++){ justforName=j+1; $('input[name="CAR'+justforName+'"').val(allValue[j]) }})}) </script> class Car(models.Model): car_name = models.CharField(max_length=20,unique=True) owner = models.ForeignKey(Creator,on_delete=models.CASCADE) class Creator(models.Model): … -
Unable to Cancel Orders in Django
I would like to add the option for customers on my site to cancel their orders, but I'm having trouble getting it to work. I've created the view and the URL, but something is evidently wrong with them. Here's how it looks on the site: delete_order View: def delete_order(request, pk): """ Cancel an order from the profile page """ order = Order.objects.get(id=pk) if request.method == "POST": order.delete() return redirect('/') return render(request, "delete_order.html", {'item': order}) Order Model: class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) full_name = models.CharField(max_length=50, blank=False) phone_number = models.CharField(max_length=20, blank=False) country = models.CharField(max_length=40, blank=False) postcode = models.CharField(max_length=20, blank=True) town_or_city = models.CharField(max_length=40, blank=False) street_address1 = models.CharField(max_length=40, blank=False) street_address2 = models.CharField(max_length=40, blank=False) county = models.CharField(max_length=40, blank=False) date = models.DateField() date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return "{0}-{1}-{2}".format(self.id, self.date, self.full_name) Django Url: url(r'^delete_order/(?P<pk>\d+)/$', delete_order, name="delete_order") Html Url: <a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Cancel</a> This is the error I am getting: Any feedback is greatly appreciated! -
Django webpack loader: how to refer to static images compiled by webpack
I'm setting up webpack for a a Django application, for which django-webpack-loader appears to be the obvious choice. I can compile my js and scss files just fine, but I've hit a wall when it comes to loading in the images. My webpack.config.js file looks like this (I removed the scss, minifiers, babel, etc. for conciseness): const path = require('path'); const webpack = require('webpack'); const BundleTracker = require('webpack-bundle-tracker'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const TerserPlugin = require("terser-webpack-plugin"); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = { context: __dirname, entry: { main: ['@babel/polyfill', './ledger/static/ledger/js/index.js'] }, output: { path: path.resolve('./ledger/static/ledger/compiled_assets/'), filename: "[name]-[hash].js" }, module: { rules: [ { test: /\.(png|jpe?g|gif|svg)$/, use: [ { loader: "file-loader", options: { outputPath: 'images' } } ] } ] } mode: 'development' } As far as I've been led to believe, file-loader is what I need to load in the static image files. When I run the build, the image file happily sits in my compiled_assets/images directory with its hash added. The problem seems to be in how to refer to the file. While the js files load fine by using the {% render_bundle 'main' 'js' 'DEFAULT' %} tag, I can't get the image files to appear. The … -
Django how to create a modal edit with Ajax?
I have created in my app a form with which I could store data in my database. But now I'm trying to create an edit button (using an ajax call with jQuery) in the datatable such as last column. I want that when I press on the button 'edit' that open a modal form it gives me the possibility to modify the data just filled. This is my models.py: class Materiale(models.Model): conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True) class Conto(models.Model): nome=models.CharField('Nome Conto', max_length=30, blank=True, default="") def __str__(self): return self.nome And this is my table, with the button in the last column: <tbody> {% for element in elements %} <tr id="element-{{element.id}}"> <td class="elementConto userData" name="conto">{{element.conto}}</td> <td> <button class="btn btn-light p-0" onClick="editUser({{element.id}})" data-toggle="modal" data-target="#myModal"> </button> </td> So after I have created my modal code in the template.html: <form id="updateUser"> <div class="modal-body"> <input class="form-control" id="form-id" type="hidden" name="formId"/> <label for="conto">Conto</label> <input class="form-control" id="form-conto" name="formConto"/> </div> </form> After that I have created the ajax call in the following manner: function editUser(id) { if (id) { tr_id = $("#element-" + id); conto = $(tr_id).find(".elementConto").text(); $('#form-id').val(id); $('#form-conto').val(conto); $("form#updateUser").submit(function() { var idInput = $('input[name="formId"]').val(); var contoInput = $('input[name="formConto"]').val(); if (contoInput) { $.ajax({ url: '{% url "crud_ajax_update" %}', data: { 'id': … -
What is the difference of URL and Path in Django?
I have come across path and url methods in urlpatterns of url.py file. It's clear that both these methods can be used to declare the url path but what is the significant usage of them and when should I use one over the other? -
Trigger action after file upload into server(File exist on the server path)
I hit one question below, could you please help to give some suggestions? Appreciate. I want to get duration of a videofile upload by user, then update this “duration” into database after file uploaded. I find "post_save", but it looks this execute before the file upload(before this file exist in this server path, so if I use "post_save", I will hit the error that this file is not exist). Here is my step: 1.Create Voice Model include Field: videoFile(FileField) and the duration of this video(FloatField) 2.After user upload this file into server, I will run my algorithm in the file path and calculate this duration of this file(input: filepath and this filename; output: duration) 3.After get this duration of this file, I need to update this database immediately So my question is, how to execute my algo immediately after this file already uploaded into server? And then update database. -
Is this possible to invoke the method of QGroundControl from a Django(Python) web application?
I have a Django web application hosted on Ubuntu 18.04 and on the same machine I have installed the QGroundControl. In my Django Web Application there are two buttons (Take Off & Return to Land). Is this possible that when I press the Take Off button from my Web Application, it should invoke the Take Off method of QGroundControl? How can I connect the Django (Python) Web Application & QGroundControl? There will be some API or Web Service etc? Any idea? -
How to move user authentication permissions from django admin to html select input
How to move user authentication permissions from django admin to html select input Cannot make status selectable from frontend <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <div class="container-fluid bg-light p-4"> <div class="form-group" > <label for="name">Name</label> <input type="text" class="form-control" id="name" placeholder="Enter name"> </div> <div class="form-group" > <label for="name">Surname</label> <input type="text" class="form-control" id="surname" placeholder="Enter Surname"> </div> <div class="form-group"> <label for="select1">Select status</label> <select class="form-control" id="select1"> <option>Supervisor</option> <option>Staff</option> <option>Active</option> </select> </div> <button class="btn btn-success">Add new user</button> </div> -
PayTm gateway integration
I'm trying to integrate Paytm gateway in my e-commerce website, but I get this error when I am checking out. Additional information: - I have used the same order parameters in another website I developed so there's nothing wrong with that. -
Running a group of tasks from another task celery
I'm having some trouble solving how to call tasks from another task in celery. Lets say I have the following tasks @shared_task def task_1(arg1, arg2): return @shared_task def task_2(arg1, arg2): return @shared task def task_3(arg1, arg2): return At the moment I'm calling tasks the following way. def task_caller(): task_1.apply_asyng(args=[arg1,arg2], queue='queue_1') task_2.apply_asyng(args=[arg1,arg2], queue='queue_1') task_3.apply_asyng(args=[arg1,arg2], queue='queue_2') I know i can check whether a task has finished or not with something along the lines of res = AsyncResult('task_id') res.ready() But, can this be done from inside another celery task? This way I can create custom tasks that call another tasks without stopping execution. I think about something like this @shared_task def super_task(arg1, arg2): task_1 = task_1.apply_async(args=[arg1,arg2], queue='queue_1') res_1 = AsyncResult(task_1.id) if res_1.ready(): # .... task2 and task3 But i'd have to check if each task has finished individually this way. Can tasks be grouped in some way and be called from another task? In my case task_2 does not need info from task_1 but I'd want to know if both tasks have finished. -
Getting The Multi Value dictketError when passing data through URL in Django contains spaces
This is the my Django URL looks like http://127.0.0.1:8000/viewpro.html?d=5%20STAR. But my passing data like d =5 STAR. But my problem is when using pname=request.GET['d'], it shows multivalueDictKeyError and i can't bind the data in the variable. Can u please help me to solve it.... -
How to put condition in django signals
I working on hospital management system.In this user first register as Doctor or patient for that i had userprofileinfo model.I also have profile model for the user which is create as soom as user register,here problem arise i want profile is only created if user type is pateint but i dont know how to check condition in django Signals. i tried some way but it show following error type object 'UserProfileInfo' has no attribute 'instance' files:- userprofileinfo.py patientprofile.py -
Why Is Django Creating Blank Text File With Project Name As Filename?
Python 3.8.2 Django 3.0.9 Ubuntu 20.04 I've been away from coding for a couple years & I went through the tutorial again to refresh my memory. After starting a new project, I wanted to rename the directory that contains asgi.py, settings.py, urls.py, & wsgi.py, so I can organize my project better. So I renamed that dir to config, & then changed the appropriate code in manage.py, asgi.py, settings.py, & wsgi.py, so it refers to "config.settings" & not "projectname.settings", since that dir is no longer called projectname. Now, when I run the server, it runs fine but it mysteriously creates a blank text file in the directory with manage.py, & the filename is the project name. Why is this happening? How do I stop it? -
How to get comment for the particular Blog Post in Django?
#Models.py #BlogPost Model class BlogPost(models.Model): POST_CATEGORY = ( ('Education','Education'), ('Tech','Tech'), ('Automobile','Automobile'), ('Other','Other') ) title = models.CharField(max_length=150) thumbnail = models.ImageField(upload_to='Blog Thumbnail') category = models.CharField(max_length=100, choices = POST_CATEGORY ) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) slug = models.CharField(max_length=200, unique=True, null=True) tags = models.CharField(max_length=150, null=True, blank=True) writer = models.ForeignKey(User,on_delete=models.CASCADE,null=False) def __str__(self): return self.title #BlogComment Model class BlogComment(models.Model): post = models.ForeignKey(BlogPost,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() parent = models.ForeignKey('self',on_delete=models.CASCADE,null=True) timestamp = models.DateTimeField(auto_now_add=True) #Views Code def blogPost(request, slug): post = BlogPost.objects.filter(slug=slug) '''How to get comment for particularly this post''' comments = BlogComment.objects.filter(post=post) # It is giving a wrong answer '''The error I am getting ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.''' print(comments) context = { 'Post':post, 'Comments':comments } return render(request,'blogpost.html',context) How to get the comment for the particulary for this blog post? The error I am getting -" ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing." -
Crispy Field (combobox) depend of another Crispy Field(combobox)
I need Cbo 2 to work depending on the selection of Cbo 1. Excuse my english, I took the translator, pls help! I tried with a for and if, but, don't worked Model: class Producto(models.Model): """Clase Producto""" id_prod = models.AutoField(primary_key=True) nombre_producto = models.CharField(max_length=200) familia_producto_id_familia = models.ForeignKey(FamiliaProducto, models.DO_NOTHING, db_column='familia_producto_id_familia', verbose_name="Familia de Producto") tipo_prod_id_tip_prod = models.ForeignKey('TipoProd', models.DO_NOTHING, db_column='tipo_prod_id_tip_prod', blank=True, null=True, verbose_name="Tipo de Producto") precio_compra = models.BigIntegerField(verbose_name="Precio de Compra") precio_venta = models.BigIntegerField(verbose_name="Precio de Venta") stock = models.BigIntegerField() stock_critico = models.FloatField(verbose_name="Stock Critico") codigo_barra = models.BigIntegerField(verbose_name="Codigo de Barra") kilos_litros_id_kg_lt = models.ForeignKey(KilosLitros, models.DO_NOTHING, db_column='kilos_litros_id_kg_lt', verbose_name="Unidad de Medida") descripcion = models.CharField(max_length=50, blank=True, null=True) fecha_vencimiento = models.DateField(blank=True, null=True) imagen = models.ImageField(blank=True, null=True, max_length=100) class FamiliaProducto(models.Model): """Clase Familia de Producto""" id_familia = models.AutoField(primary_key=True) nombre_familia = models.CharField(max_length=50) class Meta: managed = False db_table = 'familia_producto' def __str__(self): return self.nombre_familia class TipoProd(models.Model): """Clase Tipo de Producto""" id_tip_prod = models.AutoField(primary_key=True) nombre_tipo = models.CharField(max_length=100) familia_producto_id_familia = models.ForeignKey(FamiliaProducto, models.DO_NOTHING, db_column='familia_producto_id_familia', blank=True, null=True, verbose_name="Familia del Producto") class Meta: managed = False db_table = 'tipo_prod' def __str__(self): return self.nombre_tipo I don't know much python and this simple thing is frustrating View: def agregar_producto(request): """Definimos los datos necesarios para agregar producto""" data = { 'producto':ProductoForm(), 'familia':FamiliaForm(), 'tipo':TipoForm() } if request.method == 'POST': formulario = ProductoForm(request.POST) if formulario.is_valid(): … -
'static'. Did you forget to register or load this tag?
This code WAS working, and now it's not. Is this a bug? I load static, but it says I am not. I don't know how to resolve it HERE'S MY CODE -
forbidden error 403 get in console while direct uploading to S3
I was upload image through server to s3. but I want to use direct uploading to S3 because of fast uploading. I used django-s3direct package for direct uploading. I follow all step but still I get this error. I am new at it. please Help while uploading I get error in console POST https://s3-ap-south-1.amazonaws.com/collegestudentworld-assets/img/mainpost/amar.jpg?uploads 403 (Forbidden) initiate error: collegestudentworld-assets/img/mainpost/amar.jpg AWS Code: AccessDenied, Message:Access Deniedstatus:403 settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME =os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_ENDPOINT_URL = 'https://s3-ap-south-1.amazonaws.com' #'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' #"https://collegestudentworld-assets.s3-website.ap-south-1.amazonaws.com/" AWS_S3_REGION_NAME = 'ap-south-1' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' S3DIRECT_DESTINATIONS = { 'primary_destination': { 'key': 'uploads/', 'allowed': ['image/jpg', 'image/jpeg', 'image/png', 'video/mp4'], }, 'mainpost':{ 'key':'img/mainpost/', 'auth': lambda u:u.is_authenticated }, } bucket policy { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListAllMyBuckets" ], "Resource": "arn:aws:s3:::*" }, { "Effect": "Allow", "Action": [ "s3:ListBucket", "s3:GetBucketLocation", "s3:ListBucketMultipartUploads", "s3:ListBucketVersions" ], "Resource": "arn:aws:s3:::collegestudentworld-assets/*" }, { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:PutObjectAcl", "s3:*Object*", "s3:ListMultipartUploadParts", "s3:AbortMultipartUpload" ], "Resource": "arn:aws:s3:::collegestudentworld-assets/*" } ] } CORS Configuration <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>http://127.0.0.1:8000</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <ExposeHeader>x-amz-server-side-encryption</ExposeHeader> <AllowedHeader>*</AllowedHeader> </CORSRule> <CORSRule> <AllowedOrigin>*.collegestudentworld.com</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <ExposeHeader>ETag</ExposeHeader> <AllowedHeader>*</AllowedHeader> </CORSRule> … -
output to html results in JSON format clean
I have a django app that is executing some python scripts and returning results to webpage .... unfortunately the results that are in JSON format look nasty as hell and hard to read .. I am using Visual Studio Code and using the Terminal in that the JSON output is lovely and nice to read which is not good for this .... Anyone know a way to present the results in nice standard JSON Format on my webpage from django.shortcuts import render import requests import sys from subprocess import run, PIPE def button(request): return render(request,'homepage.html') def external(request): out=run([sys.executable,'//home//testuser//data-extract.py'],shell=False,stdout=PIPE) print(out) return render(request,'homepage.html',{'data':out}) -
Access class method inside AJAX call
I have two models with single to one relation. class myModel1(models.Model): fk = ForeignKey(myModel2) status = ChoiceField class myModel2(models.Model): def status(self): last = self.mymodel1_set.last() // Get last instance of related myModel1 status = last.status return status Then I send a queryset via ajax call. qs = MyModel2.objects.all() qs_json = serializers.serialize('json', qs) return HttpResponse(qs_json, content_type='application/json') Now how can i access status in my template in a way like qs_json[0].status?