Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Keycloak with multiple django servers
I would like to ask for advice about this problem. My current setup with single django server and keycloak is this: for login handling, I am using django-allauth library (django-allauth All bellow steps are assuming, user is working in browser. Keycloak serves as user provider and login service for django: user goes to django.server/login user is redirected to keycloak login page user logs in backend checks if user exists in django DB, if not, creates it (this is done by django-allauth) user is redirected to django home page all after-login user activities with django does not require keycloak anymore.. all permission hadnling is done by pure django (django.contrib.auth). user is identified through session. I am not using any keycloak functionalities (resources, scopes,...) EXCEPT roles (roles are synced to django as groups) My current problem is this: What if I have multiple django servers and I want them to communicate with each other with permissions of logged in user? Example: User visits djangoServer_A view which requests djangoServer_B view (which requires some authentication) and response of djangoServer_B view is returned to django_server_A view... Some pseudo-code: # djangoServer_A from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required def serverA_view(request): serverB_response = call_serverB_view(**some_parameters) return … -
Celery daemon service is not triggering target function on schedule basis in Django
celery.py under main project MAP/map import os from celery import Celery from celery.schedules import crontab from django.apps import apps os.environ.setdefault('DJANGO_SETTINGS_MODULE', map.settings') app = Celery("Celery App") app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: [app.name for app in apps.get_app_configs()]) app.conf.beat_schedule = { 'load_trafic_attendance': { 'task': traffic.tasks.load_traffic_data', 'schedule': crontab(minute="*/10") }, } task function under traffic app in task.py file @app.task(name=traffic.tasks.load_traffic_data') def load_traffic_data(): …………………… …………………… celery.conf file under script app # Celery configuration options CELERY_BIN="/home/sam/MAP/env/bin/celery" CELERY_APP="map" CELERYD_NODES="worker beat" CELERYD_CHDIR="/home/sam/MAP/" CELERYD_OPTS="--time-limit=300 --concurrency=8" CELERYD_LOG_LEVEL="INFO" CELERYD_LOG_FILE="/home/sam/logs/%n%I.log" CELERYD_PID_FILE="/home/sam/run/%n.pid" celery.service file in /etc/systemd/system/ dir [Unit] Description=Celery Service After=network.target [Service] Type=forking User=sam Group=sam WorkingDirectory=/home/sam/MAP/ EnvironmentFile=/home/sam/MAP/scripts/celery.conf ExecStartPre=/bin/bash -c 'mkdir -p /home/sam/logs; chown sam:sam /home/sam/logs; mkdir -p /home/sam/run; chown sam:sam /home/sam/run' ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} {CELERYD_OPTS}' [Install] WantedBy=multi-user.target The above setup does not call the load_traffic_data function at all though it should be called in every 10 minutes. However when we run two debug commands on shell after entering into virtual env it calls the function at every 10 minutes. what I am missing here to daemonize the service? two debug command are: celery -A map beat --loglevel=debug And celery … -
Problem to use Vuejs in Django template with django-vite
Hi i have a simple django app and i want to use Vue3 for render component on the page Lets show my code then describe my problem. < -- index.html - loaded with django --> {% load django_vite %} {% vite_hmr_client %} {% vite_asset 'js/main.js' %} <div id="app"> <counter /> </div> this is main.js scripts that use a counter.vue component import { createApp } from 'vue'; import Counter from './Counter.vue'; const app = createApp({}) app.component('counter',Counter) app.mount("#app") Counter.vue file <template> <button>{{count}}</button> </template> <script> export default { data() { return { count: 12, }; }, }; </script> When i run Django server and npm run dev, nothing show in page and also no error, but if i use below code for main.js and in index.html vue component rendered. const app = createApp(Counter) app.mount("#app") index.html {% load django_vite %} {% vite_hmr_client %} {% vite_asset 'js/main.js' %} <div id="app"></div> But i cant use this method(single component) for render i need multi components for single vue app. -
How to deploy django asgi application in vercel...?
I created a chatting application on django with songs synchronisation feature For that purpose I used channels and Daphne I tried many times but got all errors Actually I didn't know How to deploy asgi, real-time apps on vercel I really need to deploy my app on vercel -
POST http://localhost:8000/date 500 (Internal Server Error)
I don't know whats wrong with me. everytime its gives POST http://localhost:8000/date 500 (Internal Server Error). my views.py: @csrf_exempt def date(request): if request.method == 'POST': data = json.loads(request.body) selected_date = data.get('selectedDate') # Now you can do something with the selected_date, for example, save it to a model # YourModel.objects.create(your_date_field=selected_date) data = order_transactions.objects.create(settlement_date=selected_date) return JsonResponse({'message': 'Date saved successfully'}) else: return JsonResponse({'message': 'Invalid request method'}, status=400) my urls.py: path('date', date), my react: async function toBeCalledByEventListener() { await fetch('/date', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ selectedDate }), }) .then(response => response.json()) .then(data => { // Handle the response if needed }) .catch(error => { console.error('Error:', error); });}; -
WinError 2 The system cannot find the file specified:
I have Django code which uploads pdf files to the SQLite database. In the first program, I uploaded successfully into the database but now I added some code and it shows me the error. The code i added is getting the size of the file and saving it to the database my code: from django.db import models from django import forms from django.core.validators import MinValueValidator import os class BookUploadModel(models.Model): book_title = models.CharField(max_length=200) category = models.CharField(max_length=100) cover_page= models.ImageField() Book_file = models.FileField() author_name = models.CharField(max_length=100) price= models.IntegerField(validators=[MinValueValidator(5)]) published_date = models.DateField() file_size = models.BigIntegerField(null=True,blank=True) def save(self, *args, **kwargs): if self.Book_file: self.file_size = os.path.getsize(self.Book_file.path) super().save(*args, **kwargs) class Meta: verbose_name_plural = 'Books' def __str__(self): return f"Book ({self.id})" def clean_photo(self): image_file = self.cleaned_data.get('cover_page') if not image_file.cover_page.endswith(".jpg"): raise forms.ValidationError("Only .jpg image accepted") return image_file views.py file: def upload(request): form = UploadForm() if request.method=='POST': # POST, return form with data from the request form = UploadForm(request.POST,request.FILES) if form.is_valid(): form.save() form = UploadForm() return render(request,"upload.html",{'form':form}) Error: Traceback (most recent call last): File "C:\Users\Tade\.virtualenvs\djangosetup-z2E8Qdx0\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Tade\.virtualenvs\djangosetup-z2E8Qdx0\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Tade\Desktop\djangosetup\bookstore_app\views.py", line 44, in upload form.save() File "C:\Users\Tade\.virtualenvs\djangosetup-z2E8Qdx0\lib\site-packages\django\forms\models.py", line 542, in save self.instance.save() File "C:\Users\Tade\Desktop\djangosetup\bookstore_app\models.py", line 17, … -
How to remove instances inside serializer
Here inside the serializer using to_representation, validate to remove the instance that doesn't satisfy the condition "completed == total_videos" but gets all the instances, so please suggest a solution to fix this class LearnerVideoMarkUsCompleteMyCourseSerializer(serializers.ModelSerializer): course = CourseSerializerForEnrolledCourseService() total_videos = serializers.SerializerMethodField() completed = serializers.SerializerMethodField() id = serializers.UUIDField(source="course.id") def get_total_videos(self, data): total_video_count = VideoDetails.objects.filter( video__coursemodulevideos__module_id__coursesectionmodule__section_id__coursesectiondetails__course=data.course ).count() return total_video_count def get_completed(self, data): progress = data.learner.learner_video_markascomplete.filter( course=data.course, mark_us_complete=True ).count() return progress class Meta: model = LearnerVideoMarkUsComplete fields = ("course", "id", "completed", "total_videos") def validate(self, data): completed = self.get_completed(data) total_videos = self.get_total_videos(data) print("complete", completed) print("total_videos", total_videos) if completed == total_videos: return data else: return "not equal" def to_representation(self, instance): completed = self.get_completed(instance) total_videos = self.get_total_videos(instance) if completed == total_videos: return super().to_representation(instance) else: return None -
What are the alternatives to the MultiSelectField library for Django 5?
ROLES = [ ("admin", "Администратор"), ("user", "Пользователь"), ] class Permission(models.Model): title = models.CharField(max_length=100) roles = MultiSelectField(choices=ROLES) I need to implement this functionality. However, the MultiSelectField library does not work with Django 5 version. To fix this, you need to remove _get_flatchoices from the fields.py file in the root of the library. However, when installing dependencies via requirements.txt when deploying to the server, this will not work. Help me please I wanted to use ArrayField, but this is not suitable since the Sqlite database is used locally -
I encounter an error during the initial access, but subsequent accesses are normal
django.urls.exceptions.NoReverseMatch: Reverse for 'problem_detail' with arguments '(Undefined,)' not found. 1 pattern(s) tried: ['problem/(?P[^/]+)$'] this is my (codehttps://www.ideone.com/464jH9) in urls.py and this is my url : ltoj.edu.vn/problem/xau2 -
Django Invalid OTP Error - Two step login System in Django
This is my login view: def login_view(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: if user.is_active is False: messages.error(request, 'Your account has not been verified yet. Please verify your account!') return redirect(reverse('account_login')) mail_subject = "One Time Password - OTP" message = render_to_string('registration/otp_verify_email.html', { 'user': request.user, 'otp': get_otp(request), }) to_email = user.email try: send_mail( subject=mail_subject, message=message, from_email=settings.EMAIL_HOST_USER, recipient_list=[to_email], fail_silently=False ) request.session['username'] = username messages.success(request, "OTP has been sent to your mail!") return redirect('verifyotp') except Exception as e: messages.error(request, "Error occurred while sending mail. Please try again.") return render(request, 'registration/login.html') else: messages.error(request, "Invalid username or password!") return render(request, 'registration/login.html') This is otp verify view: def otp_view(request): if request.method == "POST": otp = request.POST.get('otp') username = request.session['username'] otp_secret_key = request.session['otp_secret_key'] otp_valid_until = request.session['otp_valid_until'] if otp_secret_key and otp_valid_until is not None: # Convert the stored timestamp string back to a datetime object valid_until = datetime.fromtimestamp(float(otp_valid_until)) if valid_until > datetime.now(): totp = pyotp.TOTP(otp_secret_key, interval=60) if totp.verify(otp): user = get_object_or_404(User, username=username) login(request, user) del request.session['otp_secret_key'] del request.session['otp_valid_until'] return redirect('home') else: messages.error(request, "Invalid OTP") else: messages.error(request, "OTP has been expired!") else: messages.error(request, "Something bad happened! Please try again!") return render(request, 'registration/otp_verify.html') I'm generation otp … -
Trouble in hosting Django project. Spacy nlp = spacy.load("en_core_web_sm")
I am hosting a small Django project. The project is running perfectly on my local machine but on the deployed site, it says OSError at / [E050] Can't find model 'en_core_web_sm'. It doesn't seem to be a Python package or a valid path to a data directory. The error is occuring in my views.py file where I had writted, import spacy nlp = spacy.load("en_core_web_sm") This is my requirements.txt file. (for hosting) asgiref==3.4.1 Django==3.2.8 python-dateutil==2.8.2 six==1.16.0 sqlparse==0.4.2 tzdata==2021.5 gunicorn==20.1.0 spacy==3.1.3 I already tried adding en-core-web-sm==3.1.0 but it's giving another error and frankly it's redundant because we already included spacy==3.1.3 I'm don't understand that error as everything is working fine when I run the project on my local machine. But it's not in the deployed site. Here are the github repo and the hosted site links, GitHub Repo Hosted site (Vercel) If you're trying out the website, upload the file and click generate masked text. Then you'll see the error. -
How to save PDF quickly
1 There are many images stored on the server, and the necessary images are selected from them. 2 Afterwards, each image is arranged in the form of a worksheet and saved. Frontend - Vue Backend - Django database - PostgreSQL Currently, PDFs are being generated from the Django queue using a PDF API. However, the generation speed is slow, and I wonder if you could tell me how to generate 40 pages of images within 3 seconds. There are many images. enter image description here enter image description here PDFs are being generated from the Django queue using a PDF API. The speed is considerably slow. -
Can't access "on_delete" argument of model field using _meta class (Django)
Title. I'm trying to access the on_delete argument of the field "org" here: class OrgLocation(models.Model): org = models.OneToOneField( Org, primary_key=True, on_delete=models.CASCADE, blank=True ) And I'm trying to access it with: OrgLocation._meta.get_field("org").on_delete But when I run this, I get an attribute error: AttributeError: 'OneToOneField' object has no attribute 'on_delete' Trying to access primary_key works just fine though (and same for blank). Not sure what's going on. Any suggestions? -
django-saml2-auth authenticates user but I get anonymous user in my view
I am using django-saml2-auth to authenticate my users. I see that the authentication is successful but in my view, the request.user is an anonymous user. Additional Info: I see that the call to /saml2/acs/ - request includes sessionid(a) and redirect to / with another request sessionid(b) The next HTTP call - to / - includes the received sessionid(b), but response includes sessionid with empty string enter image description here Here are django & django-saml2-auth version Django 4.2.7 grafana-django-saml2-auth 3.12.0 django-saml2-auth 2.2.1 Why is the user anonymous even after successfully logging in?' -
Search and pagination in Django
How do i ensure that the original search query is maintained when navigating to the next pagination page in Django? I attached if statement in my template to include the search query in the Url if it exists but it doesn't work -
How to make Django translations accessible from Javascript?
How do you make all of the Django app locale/<lang>/django.po translations accessible from Javascript so you can dynamically translate text in Javascript widgets? According to these docs you need to add a URL pattern to your urls.py like: urlpatterns += i18n_patterns( path("jsi18n/", JavaScriptCatalog.as_view(packages=['myapp1', 'myapp2', ....]), name="javascript-catalog"), and then in your base template's <head> add the includes: <script type="text/javascript" src="{% url 'admin:jsi18n' %}"></script> <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> I've done this, and I have Japanese locale/ja/django.po (and their compiled .mo) files for every app in my project. However, when I access the URLs generated by {% url 'admin:jsi18n' %} (/admin/jsi18n/) and {% url 'javascript-catalog' %} (/ja/jsi18n/) it doesn't contain any of my custom translations. Why is this? What step in the docs am I missing preventing my translations from being accessible in the Javascript catalog? -
CORS problem with django running on GCP compute engine code-server
I am working on a Django project. For that, I work both in my personal laptop as well on a remote code-server instance (VS Code Remote) running on GCP compute engine. I run code-remote on https://dev.myweb.com (fake url) and when running the django server via python manage.py runserver in port 8000 the built in proxy allows me to connect via https://dev.myweb.com/proxy/8000 I can get to the first page (base.html) without problem (no forms or request in that page). But when I click on login (which would bring a POST request, that I think is the problem?), I get a error like this: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Origin checking failed - https://dev.myweb.com does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you … -
Signal receivers must accept keyword arguments (**kwargs) when using pre_delete signal in Django
I am trying to make a destructor-similar signal in django to be called before any children of the class Base are deleted. The reason is that I need to change something on another models's field when this is deleted as part of cleaning up, and I want this to run when for example deleting the instance from Admin. I have this in my models.py: @receiver(pre_delete, sender = Base) def delete_shot_script(sender, instance, **kwargs): print("Calling the destructor") do_something... I am getting the error ValueError: Signal receivers must accept keyword arguments (**kwargs), why? Is the approach valid otherwise? I have tried adding **kwargs, but the error seems to persist. -
Django - PropertyFilterSet - How to filter on a property when the property refers to a model
How can I filter on a model's property with django_property_filter package given the following Django models: # models.py from django.db import models class Manager(models.Model): name = models.CharField(max_length=35) class Plan(models.Model): name = models.CharField(max_length=35) manager = models.ForeignKey(Manager, on_delete=models.CASCADE) class Member: name = models.CharField(max_length=35) plan = models.ForeignKey(Plan, on_delete=models.CASCADE) @property def manager(self): return self.plan.manager # filters.py from django_property_filter import PropertyFilterSet class Meta: model = Member fields = [] class MemberFilter(PropertyFilterSet): manager = ???( field_name='manager', ) I tried the PropertyMultipleChoiceFilter and PropertyChoiceFilter with no success. Choices was set to [(m.pk, m.name) for m in Manager.objects.all()]. -
Update mehod not working correctly in the serilizer (django rest framework)
here is the code my code i tried diffrent solution none of them work i also added function to add new question if the id is not here i think it didnt see the id and i tried logging it it says none i dont know why its not seeing my if but when i do get method i get the id in response so idont know what to do i hope i provided enough code for you thanks in advance for help serializer.py from rest_framework import serializers from .Models.QuizMaker import QuizMake from .Models.Answers import Answers from .Models.Questions import Questions import string, secrets def generate_quiz_session_token(): alphabet = string.ascii_letters + string.digits token = ''.join(secrets.choice(alphabet) for _ in range(8)) return token class AnswersSerializer(serializers.ModelSerializer): class Meta: model = Answers fields = ['id','answer', 'is_correct'] read_only_fields = ['id'] class QuestionSerializer(serializers.ModelSerializer): answers = AnswersSerializer(many=True) class Meta: model = Questions fields = ['id','question', 'description', 'image', 'answers'] read_only_fields = ['id'] class QuizSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) quiz_session_token = serializers.CharField(max_length=8, required=False) class Meta: model = QuizMake fields = ['id','name', 'req_time', 'fk_teacher_id', 'quiz_session_token', 'questions'] read_only_fields = ['id'] def create(self,validated_data): questions_data = validated_data.pop('questions') quiz = QuizMake.objects.create( name = validated_data['name'], req_time = validated_data['req_time'], fk_teacher_id = validated_data['fk_teacher_id'], quiz_session_token = generate_quiz_session_token(), ) for question_data in … -
Retrieve data from Django to Select Option through Datatable
I have a problem which I can't call Django data which is payrolled_list into select option after rendered datatable or it triggers. I just want the data from Django to reflect to select option but Im using Datatable to triggers and then reflect can anyone have an idea to regarding to my problem , I appreciate it a lot! What I tried populate data to select but don't know how to call it it is necessary using "{{payrolled_list}}" since it django and reflect to select2 ? drawCallback: function (settings) { let myDataTable = $('#tbl-box-a').DataTable(); let payrolledListData = []; $('#payroll-name').empty(); // Add an empty option $('#payroll-name').append('<option></option>'); // Populate options based on payrolled_list data for (let i = 0; i < payrolledListData.length; i++) { $('#payroll-name').append('<option value="' + payrolledListData[i].id + '">' + payrolledListData[i].name + '</option>'); } } html select <select id="payroll-name" name="PayrollName" class="form-select employee" data-allow-clear="true" ><option></option></select> Django payrolled_list = serialize('json', TevIncoming.objects.filter(status_id=4).order_by('first_name')) response = { 'data': data, //data is list 'payrolled_list': payrolled_list //this data I want to populate it to select option } return JsonResponse(response) This is my whole code datatable const table2 = $('#tbl-box-a'); if ($.fn.DataTable.isDataTable('#tbl-box-a')) { table2.DataTable().destroy(); } dataTable2 = table2.DataTable({ processing: true, serverSide: true, ajax: { url: "{% url 'employee-dv' %}", … -
Extract a subtree from the tree structure returned by DecisionTreeRegressor (recursive & iterative versions)
Given A starting root node and a certain depth, I want to extract the subtree from the scikit-learn's DecisionTreeRegressor tree. For that I want to implement and test both the iterative and the recursive versions which I have written and paste here below. The problem is that they don't return the same results (I suspect the recursive version is buggy). #recursive def get_subtree_from_rt(subtree, root_start, max_depth): if max_depth == 1: return [] nodes = [root_start] if root_start == -1: nodes.extend([root_start]) return nodes else: children = [child for child in [subtree.children_left[root_start], subtree.children_right[root_start]]] nodes.extend(child for child in children if child not in list(filter(lambda a: a != -1, nodes))) for child in children: nodes.extend(child for child in get_subtree_from_rt(subtree, child, max_depth - 1) if child not in list(filter(lambda a: a != -1, nodes))) return nodes #iterative def get_subtree_from_rt_iter(subtree, root_start, max_depth): return breadth_first_traversal(subtree, root_start, max_depth) def breadth_first_traversal(tree, root_start, t_depth): sub_tree = [] stack = deque() stack.append(root_start) sub_tree.append(root_start) while stack: current_node = stack.popleft() if current_node !=-1: left_child = tree.children_left[current_node] right_child = tree.children_right[current_node] children_current_node = [left_child, right_child] stack.extend(children_current_node) for child in children_current_node: sub_tree.append(child) current_depth = int(math.log2(len(sub_tree) + 1)) if current_depth == t_depth: break else: continue return sub_tree Could you tell me where is the bug/bugs in those snippets … -
Get the ID of the current logged-in user into a standalone script in Django?
I have a standalone script in Django that receives messages from a Redis server. Each incoming message is coded with a topic. Users of the site will indicate which topics they are interested in receiving messages for. Their preferences are stored in a database as True or False for each topic. I’m currently stuck trying to figure out a way to obtain the currently logged in user’s id so that I can reference their topic preferences against each incoming message’s topic. I can’t figure out how to get the ID of the currently logged in user into the standalone script. Does anyone know how to do this? I've been stuck on this for days so any insights would be greatly appreciated! -
Bringing a Django Model to a HTML Table
I am very new to Django and I am working on my first training project. I want to document every month a set of meters (water, electricity, and more) and I want to see those meters in a html table like: Nov 2023 Dec 2023 Jan 2024 Meter 1 500 510 Meter 2 1000 1300 Meter 3 100 110 120 I am using 4 models in models.py: model metertype -> electricity, water, and other types of meters model meter -> name/description of the meter model readingdate -> date of the reading, normally last day of month model readingsvalue -> the values I read from the meters from django.db import models class meterType(models.Model): meterType = models.CharField(max_length=100) class meter(models.Model): meterName = models.CharField(max_length=100) meterType = models.ForeignKey( meterType, on_delete=models.CASCADE) class readingDate(models.Model): date = models.DateField() class readingsValue(models.Model): readingsValue = models.DecimalField(max_digits=10, decimal_places=2) meter = models.ForeignKey(Zaehler, on_delete=models.CASCADE) readingDate = models.ForeignKey(Ablesedatum, on_delete=models.CASCADE) After this done (it seams to work in the admin area). I put up a view.py which is very basic: from django.shortcuts import render from .models import readingsValue, meter, meterType, readingDate def index(request): readingsValue = readingsValue.objects.all() meter = meter.objects.all() meterType = meterType.objects.all() readingDate = readingDate.objects.all() return render(request, "meters/index.html", {"meter": meter, "readingsValue": readingsValue, "meterType": meterType, "readingDate": readingDate, … -
Django ArrayField. How to save JSON in array from Django Admin?
I have an ArrayField in my model. My model looks like this: class UserProfile(UUIDPrimaryKeyModel): canceled_plans_data = ArrayField(models.JSONField(), default=list, blank=True) When I append python dict in this field, it gets saved and later fetched easily. But as soon as I open this model in Django Admin and without any change in any field of this model, click on save button, it gives me error. Error is following: Item 1 in the array did not validate: Enter a valid JSON. Item 2 in the array did not validate: Enter a valid JSON. I am not sure what's wrong. I have just shown this field in Admin Model like this: class UserProfileAdmin(admin.ModelAdmin): fields = ('user', 'canceled_plans_data',) How I can fix this problem?