Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get field from different model to filter in filter.py?
is there some way how get field from different model to my filter which is used in my template? I am trying to filter by category_name from Category model in Warehouse model which is connected with Category Model by Product model. When I try in shell, relation is working: Warehouse.objects.filter(product__category__category_name__icontains="shoes") But when I use similar code in filter.py, I get blank field instead of field for category (other fields from filter are working, so filter is OK): class WarehouseDataFilter(django_filters.FilterSet): product = django_filters.CharFilter(label="Product", field_name="product__name", lookup_expr='icontains') category = django_filters.CharFilter(label="Kategorie", field_name="product__category__category_name", lookup_expr="icontains" ), pyear = django_filters.NumberFilter(label="Rok výroby", field_name="product__pyear") class Meta: model = Warehouse fields = ("product", "pieces") attrs={"a": {"class": "orange"}, "thead": {"class": "orange"}} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form.helper = WarehouseDataFilterFormHelper() models.py class Warehouse(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) pieces = models.IntegerField("Quantity", null=True, blank=True) updated_on = models.DateTimeField(auto_now=True, null=True) class Product(models.Model): name = models.CharField("Product", max_length=150) pyear = models.IntegerField("Rok Výroby", null=True, blank=True) drop = models.IntegerField("Drop", null=True, blank=True) productgroup = models.ForeignKey(ProductGroup, on_delete=models.CASCADE, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) class Category(models.Model): category_name = models.CharField("Category", max_length=100, blank=True, null=True) -
Using NuxtJS (or VueJS) to handle dynamic Django forms?
I have a Django site with Bootstrap styling the front-end. The primary function of the site is to show a form, send the form submission to the Django View, and have the view render back a output page based on the information in the form. The form is pretty dynamic, using jQuery. When one particular dropdown is selected, another field might be disabled. When another dropdown value is selected, it might unhide a with extra form fields (conversely, it can re-hide the div if another dropdown value is selected) One of the main features that I've done is to save all of the form field values into the DB, so that we can use a specific URL to retrieve that exact input/output. When the inputs are loaded from the database, all of that same jQuery is being run to disable, hide, show different parts of the form. And it all seems kind of brittle or prone to errors. All of that run-up for the actual question: I am learning about NuxtJS. Is there a specific feature of NuxtJS or development pattern that is going to help me with this dynamic loading of a conditional Django form? Are there specific things … -
Trim a dajango model attributes
I have a project in django, witch uses database first. The problem is the data format, because they have a lot of blank space. As I am using rest_framework, I would like to trim the objects before pass it to the serializer, because if I try to do something like nombre = serializers.CharField(source='nombre.strip') it says that I cannot use build-in functions. So, if anyone can help me I it would be great. -
Could not connect to wss
I want to add websockets chat to my Django (DRF) application. I am following this tutorial https://dev.to/earthcomfy/django-channels-a-simple-chat-app-part-3-a3b My versions django-rest-passwordreset==1.2.1 channels==3.0.5 channels-redis==3.4.1 Nginx configuration What should I add for websockets? upstream app { server django:8800; } server { listen 80; server_name 127.0.0.1; client_max_body_size 100M; location / { proxy_pass http://django:8800; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_read_timeout 300s; proxy_connect_timeout 75s; } ... Routing websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] I have a standard consumer: class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) I am sending request wss://localhost:6060/ws/chat/r1 On the server side I see logs: nginx_1 | 172.18.0.1 - - [28/Sep/2022:19:55:22 +0000] "\x16\x03\x01\x02\x00\x01\x00\x01\xFC\x03\x03<\xA1\xCE\xACW\x06T\x84\x1F\xE3\x13\xD8F\x00\x03\x11\xC3><4k~_\x14\x83j=\xD1}u^R '\xCE\xF3\xB2\x142\x84+J~\xEC\xDAG?c\xD0)q\xBDZ\xD9\x95_\x1C\xED\x83L,\x1C" 400 157 "-" "-" "-" But have the following error. How to fix it? -
Django: how to pass data from view to forms to validate it
In my form class I have a contact field in string to save several contacts separated by semicolons. In the request, contacts is an array so I do a ";".join(contacts) to get one contact field for my class form. I would like to pass this ";"join(contacts) contact from my view to the form class to validate it. -
How to add decorator to class based view in django
I have signup class based view in my django authentication application. I created a new file: decorators.py from django.shortcuts import redirect def authenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if not request.user.is_authenticated: return view_func(request, *args, **kwargs) else: return redirect('/') return wrapper_func and in my view I have: from .decorators import authenticated_user class Signup(View): @authenticated_user def get(request): ... And it results in an error: AttributeError at /accounts/signup-professor/ 'ProfessorRegister' object has no attribute 'user' But if I add same decorator to function based view it works. Why is this happening and how to fix it? -
How to send kwargs arguments via .save() method to a post_save signal?
I have two models, Process and Notification and I need to create a notification when a process is saved so Im using a post_save signal for this: def create_notification(sender, instance, *args, **kwargs): if instance.status in ["ERR", "FIN"] or instance.percent == 100: type = kwargs["type"] notification = Notification() notification.account = instance.owner notification.process = instance notification.status = "UNREAD" notification.content = instance.description notification.notification_type = type if instance.sub_processes.exists(): for sub_process in instance.sub_processes.all(): if sub_process.model_id != "": notification.model_id = sub_process.model_id if sub_process.model_name != "": notification.model_name = sub_process.model_name notification.save() this is working fine but my problem is that I need to pass an extra argument when I save a process, this argument is for the Notification Object that Im creating, which is type so every time im saving a Process object (in a view for example) im trying to do something like this process.save(type="EMM") but its not working, the line type = kwargs["type"] in create_notification signal isn't doing anything, so how can I send extra arguments to save method ? -
how do I display the tags used more than once only one time?
The same tags are being repeated and displayed in the dropdown list. It is looping over the tags used in each post but it is not checking if the tags are repated or not. So is there any way that I can avoid this repetition? my dropdown list is as below: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for post in posts %} {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}"> {{ tag.name }} </a> {% endfor %} {% endfor %} </div> </div> views.py def home(request, tag_slug=None): posts = Post.objects.all() #tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) return render(request, 'blog/home.html', {'posts':posts}) models has title = models.CharField(max_length=100) content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default= 'blog_default.jpg', upload_to='blog-pics') tags = TaggableManager() I need to solve this issue. I want to use the same tags in different posts but I want to display the tags just once in the dropdown list. -
How to design a model for a Django TaskManager App?
I need a small task manager app that performs certain tasks, e.g. copy file, send email, create pdf and so on. The tasks must also run in an order/priority, e.g. first: create pdf, second: send mail. I'm currently wondering what a good model would be for this. Somewhere I don't quite like the ideas I have. Among other things, I have questions like: How could the model look like? Should i use an abstract class? What about inheritance? Should i use NULL values here and better use a large table instead of dividing it into individual tables? Example for "models.py": class Channel(models.Model): name = models.CharField(max_length=50, unique=True, null=False) active = models.BooleanField(default=False) @admin.display(boolean=True) def is_active(self): return self.active def __str__(self): return self.name class Meta: db_table = 'channel' verbose_name = 'Channel' verbose_name_plural = 'Channel' class Task(models.Model): name = models.CharField(max_length=50, unique=True, null=False) active = models.BooleanField(default=False) priority = models.IntegerField(null=False) channel = models.ForeignKey(Channel, on_delete=models.CASCADE, related_name='%(class)s_channel') @admin.display(boolean=True) def is_active(self): return self.active class Meta: abstract = True class CopyFile(Task): path_src = models.CharField(max_length=200, null=False) path_dest = models.CharField(max_length=200, null=False) pattern = models.CharField(max_length=200, null=False) def __str__(self): return self.name class Meta: db_table = 'task_copy_file' verbose_name = 'Task (CopyFile)' verbose_name_plural = 'Task (CopyFile)' class SendMail(Task): recipient = models.CharField(max_length=200, null=False) sender = models.CharField(max_length=200, null=False) content … -
I am getting this error: AttributeError at /home/ 'list' object has no attribute 'values'
models.py from django.db import models class Student(models.Model): Student_Name = models.CharField(max_length=40) Father_Name = models.CharField(max_length=40) Contact = models.CharField(max_length=10) Address = models.CharField(max_length=120) def __str__(self): return self.Student_Name serializers.py from rest_framework import serializers from .models import Student class StudentForm(serializers.ModelSerializer): model = Student fields = ['Student_Name','Father_Name','Contact','Address'] app urls.py from django.urls import path from restapiapp import views urlpatterns = [ path('home/', views.HomeView, name='home'), ] admin.py from django.contrib import admin from .models import Student admin.site.register(Student) views.py from django.http import HttpResponse,JsonResponse from rest_framework.decorators import api_view from .models import Student from .serializers import StudentForm @api_view(['GET']) def HomeView(request): serializer_obj = Student.objects.all() serializer1 = StudentForm(serializer_obj,many=True) return JsonResponse(serializer1.data, safe=False) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'restapiapp', ] urls.py from django.urls import path, include from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('', include('restapiapp.urls')), ] Error: Internal Server Error: /home/ Traceback (most recent call last): File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc … -
django-allauth Azure Ad Configurations
I'm tyring to setup django azure ad authentication using django-allauth but currently the documentations is not having proper documentation for setting up Azure ad. I have client_id, secret and tenant_id with me. I have tried few configurations but it seems to be not working. Config 1: SOCIALACCOUNT_PROVIDERS = { 'azure': { 'APP': { 'client_id': 'client_id', 'secret': 'secret', 'key': '' } } } Config 2: SOCIALACCOUNT_PROVIDERS = { 'azure': { 'APP': { 'client_id': 'client_id', 'secret': 'secret', 'key': '', 'tenant_id': '', } } } I have experimented few more configuration but its seems to be not working https://django-allauth.readthedocs.io/en/latest/providers.html -
Django Picture showing as broken when referenced in template
I am trying to create a settings page for user profiles and I have hit a roadblock. I included a profile image inside of my User model and when trying to reference said ImageField in my profile template the image shows up as broken. Firstly, everything else related to the storing of a profile image works. When an account is created, the default image saves and same with using the upload picture form. The issue comes when trying to display the current profile picture through the model's url and the image shows up as broken. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(max_length=300, blank=True) profileimg = models.ImageField(upload_to='profile_images', default='blank-profile.jpg') verified = models.BooleanField(default=False) def __str__(self): return self.user.username views.py def settings(request): user_profile = Profile.objects.get(user=request.user) if request.method == "POST": if request.FILES.get('image') == None: image = user_profile.profileimg bio = request.POST['bio'] user_profile.profileimg = image user_profile.bio = bio user_profile.save() if request.FILES.get('image') != None: image = request.FILES.get('image') bio = request.POST['bio'] user_profile.profileimg = image user_profile.bio = bio user_profile.save() return redirect('settings') return render(request, 'settings.html', {'user_profile': user_profile}) Section of html file that tries to show image <img width="100" heigh="100" src="{{ user_profile.Profileimg.url }}" /> I have also added all of the necessary MEDIA_URL/root settings and have tried … -
Django form not showing errors but redisplays new form
I have a Insert view which displays model data from one primary and one related model. Once finished displaying the data a form is appended to the table to add a new related item. This works fine - however if I enter invalid data (like a invalid time to be exact), and hit one of the submit buttons, it simply refreshes the page with a blank entry form for the related data again. It doesn't display the data I entered, and it doesn't display an error message even though the form includes the error fields. I have tried adding form_invalid to my CBV and calling the form but I can see that it just calls the InserView again with no context (which basically does the get_context_data call again and give me a new blank form). How do I get it to put up the form with my data from before and the errors as well. See code below: views.py class SegmentAddView(LoginRequiredMixin,CreateView): login_url = reverse_lazy('login') model = Segment template_name = 'segment_add_view.html' form_class = SegmentForm def get_context_data(self, **kwargs): context = super(SegmentAddView,self).get_context_data(**kwargs) program_info = get_object_or_404(Program, pk=self.kwargs['pk']) context['program_info'] = program_info last_segment = program_info.segments.last() if last_segment: add_sequence_num = last_segment.sequence_number + Decimal(1.00) else: add_sequence_num = Decimal(1.00) … -
Django: Display data from other table
I'm having a hard time displaying some datas from two or three tables. So this is my code for showing all the data only from Device table. def device(request): if request.method == 'GET': queryset = Device.objects.all() if queryset: data = {"queryset": queryset} return render(request, 'device/device.html', data) else: return render(request, 'device/device.html') And I want to add some data from other table, how do I insert it here? -
Adding parameters into URL via django url name
There are following files: #urls.py from django.urls import path from . import views app_name = 'some_app' urlpatterns = [ path('', views.index, name='index'), path('some_url/', views.view_func, name='some_url') ] #views.py from django.shortcuts import redirect def index(request): return redirect('some_app:some_url') def view_func(request): pass Now, if I follow the first link (index) it will redirect me to /some_url/. How can I change my code to add any parameters to URL for redirecting to /some_url/?param1=abc&param2=def? -
how can i view my python bot data in my mysql table?
In the bookfiles folder, there are bots I wrote with python. I imported my model class inside bots. I created the table in the models.py file in the database, but the bots' data is not displayed. There are only column names. How can I display this data in my database table? I've included the bot's code below. from ast import Str from base64 import decode import requests from bs4 import BeautifulSoup import pandas as pd import csv from time import sleep from random import randint import numpy as np from bookList.models import BookList headers = dict() headers[ "User-Agent" ] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" def sendBooksToMysql(): bkmArt() def bkmArt(): pages = range(1, 3, 1) for page in pages: url = "https://www.bkmkitap.com/sanat" results = requests.get(url, headers=headers) soup = BeautifulSoup(results.content, "html.parser") book_div = soup.find_all("div", class_="col col-12 drop-down hover lightBg") sleep(randint(2, 10)) for bookSection in book_div: img_url = bookSection.find("img", class_="lazy stImage").get('data-src') name = bookSection.find("a",class_="fl col-12 text-description detailLink").get('title') author = bookSection.find("a", class_="fl col-12 text-title").get('title').replace('Model:', '') publisher = bookSection.find("a", class_="col col-12 text-title mt").get('title').replace(name, '') price = bookSection.find("div", class_="col col-12 currentPrice").text.replace('\n', '').replace('TL', ' TL') b_link = bookSection.find("a").get('href') bookList = BookList.objects.using("bookList").update_or_create( site_name="Bkmkitap", site_id="1", image=img_url, #book=name, #author=author, publisher=publisher, price=price, link=b_link, … -
django Templates sum prices of cart items
Inside DJango templates, in an HTML Page, I have the following lines of code in body. {% for cart_data in cart_items|slice:"0:"%} <div class="Cart-Items pad "> <div class="image-box"> <img src={{cart_data.img_url}} style="height:120px;"}} /> </div> <div class="about"> <h1 class="title">{{cart_data.name}}</h1> <h3 class="product_id">{{cart_data.retailer_sku}}</h3> <div class="sku"> <div class="color">{{cart_data.color}} ({{cart_data.size}})</div> </div> </div> <div class="prices"> <div class="amount">$ {{cart_data.price}}</div> </div> </div> {% endfor %} This code extacts the cart items and displays them on the page. Now I want to do is sum all the proces and show total after this loop. How to do that? -
Django SAML2 Authentication with AZURE
I have a Django application in production on an Ubuntu 20.04 server that uses python3.8.10 and I'm trying to implement the SSO connection with pysaml2 with Azure. I chose to use the django-saml2-auth-ai package. So I have configured correctly according to the doc. However when I try my url /accounts/login/ I get an error /saml/deny/. same for /saml/acs/. however when I try the url /saml/welcome/ it redirects me to the SAML connection correctly so I know there is no problem with my Azure configuration. urls.py import django_saml2_auth.views urlpatterns = [ path('saml/', include('django_saml2_auth.urls')), path('accounts/login/', django_saml2_auth.views.signin), path('', login_, name="login"), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), ] settings.py # more code... LOGIN_URL = "/accounts/login" LOGIN_REDIRECT_URL = 'accounts:index' # more code... SAML2_AUTH = { 'SAML_CLIENT_SETTINGS': { # Pysaml2 Saml client settings 'entityid': 'https://mysiteweb.com/', 'metadata': { 'local': [ os.path.join(BASE_DIR, 'mysiteweb.xml'), ], }, 'service': { 'sp': { 'logout_requests_signed': True, 'idp': 'https://sts.windows.net/83d4d*****-*****-***/' } } }, 'debug': 1, 'DEFAULT_NEXT_URL': 'https://mysiteweb.com/', 'NEW_USER_PROFILE': { 'USER_GROUPS': [], # The default group name when a new user logs in 'ACTIVE_STATUS': True, # The default active status for new users 'STAFF_STATUS': False, # The staff status for new users 'SUPERUSER_STATUS': False, # The superuser status for new users }, 'ATTRIBUTES_MAP': { # Change Email/UserName/FirstName/LastName to … -
Corse headers adding Error while using Django in IIS
I have a django application which is hosted in IIS (with custom URL) and its front end is hosted in Angular. The front end is showing corse related error so i tried to resolve that by adding 'corseheaders' in settings.py of my backend code. After that when i tried to access the API (by clicking the hosted URL in IIS) the following error is showing in the browser. Error occurred while reading WSGI handler: Traceback (most recent call last): File "D:\TESTAPP\API\venv\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) Following is the changes i have done in the settings.py of my backend(django). Actually i have added the last line with "corsheaders". if its removed the error is gone. ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'survey_app.apps.SurveyAppConfig' "corsheaders", ] Can you guys please help me out. -
passing a value in anchor tag in django
So I'm in my profile page & want to edit my profile so I click edit button ,it takes me to a edit page where I have two buttons 'save'(inside form tag) & 'Exit'. Now if I click exit I want to get redirected to profile page of same person again. what input should I pass in below tag to do this? (<a href="{% url 'profile' %}"><button>Exit</button></a> -
what is the fastest and easiest to learn styling framework for django? [closed]
I've been developing this app in django and was wondering whether people had an idea what would be the optimal framework for styling the web app. Figma? Tailwind? Sass? I don't really have an eye for designing and want something rather simple and fast. Thank you very much for any answer! -
django.db.utils.IntegrityError: NOT NULL constraint failed: sales_position.created
Hi I'm working on a django project where I'm parsing a CSV file to create objects. I'm getting a database error that results in django.db.utils.IntegrityError: NOT NULL constraint failed: sales_position.created It looks like a database error because before the traceback I get the follwing message: sqlite3.IntegrityError: NOT NULL constraint failed: sales_position.created The above exception was the direct cause of the following exception: Traceback (most recent call last): Does deleting all migrations except 0001_initial.py fix this? -
How to get the number of created raw in bulk-create in django orm
Need to know the count of created raws in a bulk-create query in django. how can I get it ?? please help. -
How to compress a video using FFmpeg in Django Rest Framework?
I want to resize the video and picture files. so I looked for it and found FFmpeg and now I'm getting errors while compressing. FileNotFoundError: [WinError 2] The system cannot find the file specified Code import os import subprocess import ffmpeg MEDIA_MAX_UPLOAD_SIZE = 5242880 def check_media_size(media): media_size = media.size if media_size < MEDIA_MAX_UPLOAD_SIZE: return media_size @api_view(["POST"]) def medias_upload(request): if request.method == 'POST': received_media=request.FILES.getlist('media') allowed_mime_types = ['image/jpeg','image/png','image/gif','image/jpg','video/mp4','video/mkv','video/mov','video/avi'] upload_data = [] if received_media: for media in received_media: received_media_mime_type = mime_type_check(media) received_media_size = check_media_size(media) if received_media_mime_type in allowed_mime_types and received_media_size: new_uuid = uuid.uuid4() if str(received_media_mime_type).split('/',1)[0] == "image": file_type = str(received_media_mime_type).split('/',1)[1] converted_uuid = subprocess.run(f'ffmpeg -i {media} -acodec {file_type} temp_location/{new_uuid}') upload_data.append(converted_uuid) if str(received_media_mime_type).split('/',1)[0] == "video": file_type = str(received_media_mime_type).split('/',1)[1] converted_uuid = subprocess.run(f'ffmpeg -i {media} -acodec {file_type} temp_location/{new_uuid}') upload_data.append(converted_uuid) else: return Response({"response": False, "return_code":"Failed", "result": {}, "message": "Wrong MIME-TYPE or MAXIMUM file size allowed 5MB"}, status=status.HTTP_404_NOT_FOUND) return Response({"response": True, "return_code": "success", "result": {"media_uploaded_uuid":upload_data}, "message": success["success"]}, status=status.HTTP_200_OK) return Response({"response": False, "return_code":"Failed", "result": {}, "message": "No Data Found"}, status=status.HTTP_404_NOT_FOUND) Q . Is there any better way to compress video and picture file size? -
How to display JSON data in Django webpage like in JSON viewer?
I'm creating a webpage in Django that will display the contents of a JSON file in the database. So far, I was able to display the raw JSON output in my webpage like this. { "name": "John", "age": 22, "gender": "male" } But I also intended to display the "beautify" version of this in my webpage like in any JSON viewer. Any idea on how to implement this in my code?