Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FOR UPDATE cannot be applied to the nullable side of an outer join on Postgres Django app
I'm trying to create a Django app for a course to learn it and I use this repo to practice: https://github.com/hltcoe/turkle However, I ran into an issue where I keep on getting this error. Note that the issue only exists when I use postgres. NotSupportedError at /batch/1/accept_next_task/ FOR UPDATE cannot be applied to the nullable side of an outer join -
DjangoQ fails in bitbucket pipeline
I am creating a scheduled task with DjangoQ and to register it I have this code on my apps.py: from django.apps import AppConfig class ShiftsConfig(AppConfig): name = 'shifts' def ready(self): from django_q.models import Schedule func: str = 'path_to_func' schedule = Schedule.objects.filter(func=func).exists() if not schedule: Schedule.objects.create(func=func, hook='path_to_hook', schedule_type=Schedule.MINUTES, minutes=15, repeats=-1 ) It's working fine locally. Then, I wanted to deploy it and I have some pipeline steps being triggered on every commits. The steps are about linting and testing: - step: &run-linter image: python:3.7 name: Run linter caches: - pip script: - pip3 install -r requirements.txt - export DJANGO_SETTINGS_MODULE=main.settings - export DB_NAME=django - export DB_USER=django - export DB_PASS=django - export DB_POSTGRES_HOST=localhost - pylint ./* > pylint_report.txt artifacts: - pylint_report.txt - step: &run-test name: Run Test caches: - pip script: - export DB_NAME=django - export DB_USER=django - export DB_PASS=django - export DB_POSTGRES_HOST=localhost - coverage erase - coverage run manage.py test - coverage xml -i services: - postgres artifacts: - coverage.xml But on the testing step when I call coverage run manage.py test I receive: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 17, in execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/init.py", line 419, in execute_from_command_line … -
Django- SummerNote- Staticfiles
How to grab local resource of image after copying image from summernote text area? for ex. i'm taking screenshot and pasting it into comment section configured with summernote editor. after posting it i can see image source in inspect like this : img src="/resources/ec/resources/WYSIWYG_images/2022/1/20/dc72bc03-d2ae-4e15-9252-1f1dacb8c6e0.png" style="height: 250px;" but after copying that image from posted comment and using it to another comment. it changes image source like this : img src="http://192.168.1.213:8006/resources/ec/resources/WYSIWYG_images/2022/1/20/dc72bc03-d2ae-4e15-9252-1f1dacb8c6e0.png" looks like its getting hosted by local server. but whenever i delete the first comment i posted which HAS ORIGINAL SOURCE of Image then second comment is not displaying Image. so any solution how to handle that? -
Different structure path of python base program
when i works with coverage i see that when i want to run test with it i must code for example like "coverage run manage.py test src.apps.accounts.tests " in terminal and when i want see the result i must write "coverage report --include=src/apps/service/accounts/* -m " .my question is why we use ". " for run and use "/ " for see the result? and in general when we should use "." and when we should use "/" (this example did not only one case i see so i want a way to understand when should use each other of them) *in advance i am tank you for get me full solution and read the my question that write with my weak english understand. -
Django: Unknown column error when running on production server
When I attempt to login to my django application on the production server (AWS EBS), it keeps returning the following error (1054, "Unknown column 'two_factor_phonedevice.throttling_failure_timestamp' in 'field list'"). Strangely, the app works fine when running locally using the same MYSQL database (AWS RDS). I have tried dropping the database and re-running migrations believing it was due to an inconsistency between my db and migrations files however I still keep getting the same error. I am using the django_two_authentication module for the user authentication/logins. The table two_factor_phonedevice is created by the module to track the user devices registered for two factor authentication. I cannot seem to solve why the column can be found when running locally but cannot be found on the production server despite both using the same database. -
Django Chart data and labels
I'm currently making a dashboard that shows data for staff. I have made a function to get chart data and labels, so far, I've managed to do the labels.. but I can't seem to get the count for the amount of occurrences for each of the dates. I need the output for get_chart_data to be a list or tuple like this: 20/01/2022: 1, That means that on that day I only had 1 object added to the database for example. The code I have tried so far have failed, or give me the count up to a certain date but nothing correct. The important part is that the date range is dynamic. Views.py @login_required(login_url='/accounts/login/') def get_chart_data(request, model, data_range): end_date = dt.localdate() print(end_date) start_date = dt.localdate()- timedelta(days=data_range) print(start_date) db_objects = model.filter(transaction_date__lte=end_date, transaction_date__gt=start_date).\ values('transaction_date').\ annotate(count=Count('purchase_id')) print(db_objects) amount_objects = list(db_objects) print(amount_objects) dates = [x.get('transaction_date') for x in amount_objects] print(dates) for d in (end_date - start_date for x in range(0,data_range)): if d not in dates: amount_objects.append({'createdate': d, 'count': 0}) data = amount_objects return data @login_required(login_url='/accounts/login/') def get_label_data(request, model, data_range): label = [] end_date = dt.localdate() start_date = dt.localdate()- timedelta(days=data_range - 1) delta = start_date - end_date # returns timedelta for i in range(data_range): day … -
How can i import export with foreign key relationship
I have csv file with user addresses, and his phone number, How can i import it in my address table. Since I dont know user id of each user. i'm getting following error Line number: 1 - null value in column "user_id_id" of relation "proj_auth_useraddress" violates not-null constraint DETAIL: Failing row contains (432, null, null, someaddress, , , null). But i know relationship of user and address is through his phone number. user_id__phone # Models.py class AppUser(AbstractUser): phone = models.CharField(max_length=15, unique=True, null=True) ... class UserAddress(models.Model): address_id = models.AutoField(primary_key=True) user_id = models.ForeignKey(AppUser, on_delete=models.CASCADE) lat = models.FloatField(null=True, blank=True) lng = models.FloatField(null=True, blank=True) address1 = models.CharField(max_length=100) address2 = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=50) pincode = models.IntegerField() # Admin.py @admin.register(UserAddress) class AddressAdmin(ImportExportModelAdmin): resource_class = AddressAdminResource # Resource.py class AddressAdminResource(resources.ModelResource): class Meta: model = UserAddress import_id_fields = ('address_id',) -
django.db.utils.OperationalError: (1050, "Table 'profiles_category' already exists")
I am trying to host my website using FileZilla and PuTTY. For that, I have added the code in FileZilla remote site and I have created a database named jobs using following commands in PuTTY app. sudo mysql -u root #For Maria DB CREATE DATABASE jobs; GRANT ALL PRIVILEGES ON jobs.*TO 'hello'@'localhost'; flush privileges; exit Then python3 manage.py makemigrations command is executed and after that when I executed the python3 manage.py migrate command I got an error like this. django.db.utils.OperationalError: (1050, "Table 'profiles_category' already exists") Here the table profiles_category is not already existed. models.py class Category(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class CategoryJob(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name Can anyone suggest a solution for this? -
having issues with django installing
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'noonmusic.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() -
Set background color for each days of week in fullcalendar if a criteria matches?
I use django with fullcalendar and I want to change the color of days based of user's schedule. here is the structure of the user's schedule: Sunday: off // e.g. color should be blue Monday: work // e.g. color should be pink Tuesday: home // e.g. color should be yellow ... I want to change all Sunday's color to blue and so on. here is my code: $('#calendar').fullCalendar({ header: { left: 'prev', center: 'title', right: 'next' }, defaultView: 'month', eventLimit: true, events: [ {% for event in events %} { title: "{{ scheduled_event.title }}", date: '{{ scheduled_event.date|date:"Y-m-d" }}', time: '{{ scheduled_event.time }}', display: 'background' }, {% endfor %} ], }); -
How to add plain text to django form fields?
I wanna add just plain text to django forms. Like this image I have more than 50 questions and some questions belongs forexample personal questions so i wanna add plain text to like this red notice on the image. How to add just plain text field to my form. Here is my models.py file And here is my forms.py file [![enter image description here][2]][2] -
Swagger UI examples using drf-spectacular and x-www-form-urlencoded requests
Is it possible to generate a swagger UI page (and redoc for that matter) that has examples for both application/json and x-www-form-urlencoded request bodies? I can get examples for application/json, but not when selecting x-www-form-urlencoded as the request type fro the swagger/redoc UIs. I'm using the following decorator for the "create" method (in a ModelViewSet) @extend_schema(request=MySerializer) where MySerializer looks like the following... @extend_schema_serializer( examples=[ OpenApiExample( 'Example input', description='Creation of an alias', value={ 'user_id': 1234567890, 'obj_id': 288, 'alias': 'my alias' }, request_only=True, response_only=False, ), ], ) class MySerializer(serializers.Serializer): user_id = serializers.IntegerField() obj_id = serializers.IntegerField() alias = serializers.CharField(max_length=50) The swagger/redocs UIs will happily provide an example dropbox with "Example Input" for an application/json request body (whereby selecting the example will populate the json), but for x-www-form-urlencoded will just show a form to fill in, with no example dropbox in order to populate the fields. I can get examples (and their selection drop boxes) for query strings, i.e. when making GET endpoints that use OpenApiParameter e.g. @extend_schema( parameters=[ OpenApiParameter(name='q', description='Query string to search for', required=True, type=str, examples=[ OpenApiExample( 'Search query', value='foobar' ), ] ), ... ] ) where selecting a drop box entry will populate the text field. However, for x-www-form-urlencoded, this doesn't … -
How can I get libdbcapi_r.so, libdbcapi_r.dylib needed for sqlany-django?
I installed and configured sqlany-django, but have error Could not load dbcapi: Tried: dbcapi.dll, libdbcapi_r.so, libdbcapi_r.dylib. I installed sqlany-django with pip install sqlany-django. According to this I should run $ . /opt/sqlanywhere16/bin64/sa_config.sh , but I don't have a script sa_config.sh. I tried to download libdbcapi_r.so or libdbcapi_r.dylib but I can't find it even here. Then I'd like to add the path to library to LD_LIBRARY_PATH environment variable. How can I solve this? my system is Ubuntu 18.04 Django==1.9 sqlany-django==1.13 sqlanydb==1.0.11 -
Django: Loop through all attributes of a OneToOneField inside the template
I am trying to loop through all the related attributes of a OneToOneField inside a Django template but it gives an 'PropertyFeatures' object is not iterable error. This list of features is going to grow considerably and rendering them out individually with their own {% if %} statement is not a good idea. Is it possible to loop through OneToOneField attributes inside the template? Models class PropertyFeatures(models.Model): property = models.OneToOneField(Property, related_name="features", on_delete=models.CASCADE) is_pet_friendly = models.BooleanField(default=False) has_garden = models.BooleanField(default=False) Views def property_detailview(request, pk): template_name = "property/detail.html" property = Property.objects.get(id=pk) context = { "property": property, } return render(request, template_name, context) Template {% block content %} {% include "includes/navigation/navbar.html" %} <div class="container"> <h1> {{ property.title }} </h1> <div> {{ property.features.has_garden }} <-- This works {% for feature in property.features %} <-- This gives an error {{ feature }} {% endfor %} </div> </div> {% endblock content %} -
Django- admin login page should not affect the login of the website unless admin is login from the website
I want to separate login of admin and login of website. In django, admin login/logout affects website login/ logout basically I don't want this rather I want if admin is login the website gets automatically logout or when switch from admin to website the website require login. this the base.html page views.py for authentication -
Django chain filter show output in separate columns
Django chain filter show output in separate columns(html jinja) -
What am I doing wrong, Docker build is giving me this error " /bin/sh: -c requires an argument , The command '/bin/sh -c' returned a non-zero code: 2"
I am creating a docker file for my messaging-app, Here is my dockerfile. FROM python:3.9-alpine3.15 LABEL maintainer="Noor Ibrahim" ENV PYTHONUNBUFFERED 1 COPY ./message /message COPY ./requirements.txt /requirements.txt WORKDIR /message EXPOSE 8000 RUN RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /requirements.txt && \ adduser --disabled-password --no-create-home user ENV PATH="/py/bin:$PATH" USER user I am running this command docker build . I am getting this error while creating the build. I have tried different things but this error doesn't go away. Suggest me something I will be very grateful. Sending build context to Docker daemon 67.07kB Step 1/11 : FROM python:3.9-alpine3.15 ---> e49e2f1d4108 Step 2/11 : LABEL maintainer="Noor Ibrahim" ---> Using cache ---> 517b54d522ef Step 3/11 : ENV PYTHONUNBUFFERED 1 ---> Running in d8eb9d900584 ---> 29e281514398 Step 4/11 : COPY ./message /message ---> f84edc508eec Step 5/11 : COPY ./requirements.txt /requirements.txt ---> 608149cc5c42 Step 6/11 : WORKDIR /message ---> Running in b26ec4b33053 Removing intermediate container b26ec4b33053 ---> c608a04f1993 Step 7/11 : EXPOSE 8000 ---> Running in 8b4f7f49a3b8 Removing intermediate container 8b4f7f49a3b8 ---> a18f155d9320 Step 8/11 : RUN ---> Running in 6fa80a39c7d0 /bin/sh: -c requires an argument The command '/bin/sh -c' returned a non-zero code: 2 … -
I have some issue when creating django project. I cannot create new project, whenever I run a command, I get error
C:\Users\Dnyane\Documents\file_1>py -m django --version 4.0.1 C:\Users\Dnyane\Documents\file_1>django-admin startproject project_1 CommandError: [WinError 2] The system cannot find the file specified: 'C:\Users\Dnyane\Documents\file_1\project_1' -
`./manage.py migrate` fails with Postgresql while applying migrations for a built-in Django app
The built-in Django app that fails to migrate seems to be django.contrib.sites. Here's the full output of ./manage.py migrate: Operations to perform: Apply all migrations: account, admin, auth, contenttypes, leasikApp, sessions, sites, socialaccount Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying account.0001_initial... OK Applying account.0002_email_max_length... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying leasikApp.0001_initial... OK Applying sessions.0001_initial... OK Applying sites.0001_initial... OK Applying sites.0002_alter_domain_unique... OK Applying socialaccount.0001_initial... OK Applying socialaccount.0002_token_max_lengths... OK Applying socialaccount.0003_extra_data_default_dict... OK Traceback (most recent call last): File "/home/abhishek/.local/share/virtualenvs/leasik-iCbC7nbs/lib/python3.8/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.errors.NumericValueOutOfRange: setval: value 0 is out of bounds for sequence "django_site_id_seq" (1..2147483647) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/abhishek/.local/share/virtualenvs/leasik-iCbC7nbs/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/home/abhishek/.local/share/virtualenvs/leasik-iCbC7nbs/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/abhishek/.local/share/virtualenvs/leasik-iCbC7nbs/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/home/abhishek/.local/share/virtualenvs/leasik-iCbC7nbs/lib/python3.8/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) … -
How to get only the desired array of list from template
I'm using the apexchart library, and I want to plot the monthly/per person enroll count as a line graph. I want to add only a list of 12 numbers to data in series , excluding the first argument name. I've been looking for a lot of ways to slice a list using JavaScript in a Django template, but I haven't been able to find a solution. Help. series: [{% for enroll in monthly_enroll_list %} { name: '{{ enroll.0 | safe }}', data: {{ enroll | safe }} },{% endfor %} ], -> result: series: [ { name: 'A' data: ['A', 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'B', data: ['B', 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'C', data: ['C', 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'D', data: ['D', 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'E', data: ['E', 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'F', data: ['F', 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, … -
django access model attribute by subscription
I have a Profile schema: class Profile(models.Model): likedArticle = models.ManyToManyField('articles.Article', related_name='liked_article_set', blank=True) staredArticle = models.ManyToManyField('articles.Article', related_name='stared_article_set', blank=True) likedQuestion = models.ManyToManyField('questions.Question', related_name='liked_question_set', blank=True) staredQuestion = models.ManyToManyField('questions.Question', related_name='stared_question_set', blank=True) there are tons of other like-able and star-able object (only two examples Article and Question provided above), which follows the naming convention of liked<Model._meta.app_label>. I am coding a method for like and dislike serialisation: def tree(model, user): return { 'liked': model in user.profile.likedArticle.all(), 'stared': model in user.profile.staredArticle.all(), } The method is much more than the minimal example provided above, which if I write profile.likedModel, I need to define a method in each Model class, this is tremendous and not pythonic. therefore, I seek for a way, to automate the queryset. here are some methods that I am aware: model.__class__ # Model Model._meta.object_name # return Model in type of str First, I tried subscription: user.profile[f'liked{model.__class__._meta.object_name}'].all() # TypeError: 'Profile' object is not subscriptable Then I tried __dict__ method: model.__dict__ # returns attributes, except for callable, and many to many manager not included in the result Besides going with eval or exec, is there any other ways? thanks for your help. -
How to split a string of one model field and map it to other form field in Django 3.x
My models.py looks like below class MyModel1(models.Model): id = models.AutoField(primary_key=True) tag = models.CharField(max_length=255) class MyModel2(models.Model): id = models.AutoField(primary_key=True) name = models.ForeignKey(MyModel1, on_delete=models.CASCADE) scope = models.CharField(max_length=255) my forms.py looks like below Myform1 = modelformset_factory( MyModel2, fields=('name','scope'), extra=1, my views.py looks like def index(request): template_name = 'main/scope1.html' if request.method == 'GET': formset = Myform1() for form in formset: pass ## tried to split here (but it affects my dropdown in template) ## form.fields['name'].queryset = ## form.fields['scope'].queryset = return render(request, template_name, { 'formset': formset }) Now the tag value in MyModel1 may or may not have a special character - like a-b . If - present in the name I want to split it and have name = a and scope = b of MyModel2 . I tried to manipulate it in the views but not sure how to do that such way my template dropdown shouldn't get affected . -
Save all data in database with one query in Django
I'm a new Django programmer. I write a API call with rest_framework in Django. when call this API, my program connect to KUCOIN and get list of all cryptocurrency. I want save symbol and name this cryptocurrencies in database. For save data to database, I use 'for loop' and in every for loop iteration, I query to database and save data. my code : for currencie in currencies: name = currencie['name'] symbol = currencie['symbol'] active = (False, True)[symbol.endswith('USDT')] oms = 'kucoin' try: obj = Instrument.objects.get(symbol=symbol, oms=oms) setattr(obj, 'name', name) setattr(obj, 'active', active) obj.save() except Instrument.DoesNotExist: obj = Instrument(name=name, symbol=symbol, active=active, oms=oms) obj.save() query to database in every for loop iteration have problem ,How can I solve this problem? Exist any way in Django to save data in database in with one query. Thank you for you help. -
I am having a port mapping issue in django while using docker
Here is my code. I am developing a Django website along with docker here are my codes: docker-compose for development, I am using two services here for charity-app and db, docker-compose.yml version: '3.9' services: charity: build: context: . command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - ./charity:/charity - ./data/web:/vol/web environment: - SECRET_KEY=devsecretkey - DEBUG=1 - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme depends_on: - db db: image: postgres:13-alpine environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme Here is my code for production deployment docker-compose-deploy.yml version: "3.9" services: charity: build: context: . restart: always volumes: - static-data:/vol/web environment: - DB_HOST=db - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - SECRET_KEY=${SECRET_KEY} - ALLOWED_HOSTS=${ALLOWED_HOSTS} depends_on: - db db: image: postgres:13-alpine restart: always volumes: - postgres-data:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASS} proxy: build: context: ./proxy restart: always depends_on: - charity ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: Here is my .env file DB_NAME=dbname DB_USER=rootuser DB_PASS=changeme SECRET_KEY=changeme ALLOWED_HOSTS=127.0.0.1 Here is my view from django.http import HttpResponse def homePageView(request): return HttpResponse("Hello, World!") Here is my urls.py for app named as core in django charity project from django.urls import path from core.views import … -
This model form is not getting saved when submitted ajax django
I need this form to get submitted but it is not i got the ajax code from the net i don;t know ajax or anything else but i am willing to learn ajax or j query if it is really required Template (only the essential bits): <form method="post" class="Comment_Form" id="Comment_Form"> {% csrf_token <div class="comment_builder">{{ comment|materializecss }}</div> <button class="btn waves-effect waves-light btnw" type="submit" name="submit" value=" {{ Img.id }}" id="submit">Comment<i class="material-icons right">send</i> </button> </form> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"> </script> <script type="text/javascript"> $( "form" ).on( "submit", function(e) { const dataString = $(this).serialize(); const the_effing_id = $('#submit').val(); $.ajaxSetup({ beforeSend: function(xhr, settings) { function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); $.ajax({ type: "POST", url: "{% url 'Home' %}", contentType: 'application/json; charset=UTF-8', dataType: 'json', data: { dataString, 'the_effing_id':the_effing_id, csrfmiddlewaretoken: '{{ csrf_token }}', }, success: function () { alert("Saved") } }); e.preventDefault(); }); </script> Model code: class Comment(models.Model): not_post_method_ok = …