Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Page Restriction (Admin and Members could be able to see it)
Thanks for your help I got a question : I want to make accessible only for two type of people: admin (ForeignKey) and friends (ManyToMany). All belongs to the same model. The issue is user who belongs to friends are redirected to '/' and can not see the page self.object.user -> user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) self.object.friends -> friends = models.ManyToManyField(User,blank=True,related_name='friends_reservation') def get(self,request,*args,**kwargs): self.object = self.get_object() if not (request.user == self.object.user or request.user == self.object.friends): return HttpResponseRedirect('/') -
Get object attribute value after query - DJango
class item (models.Model): ITEMS = [ ("ELEC", "ELECTRICIDAD" ), ("CERR", "CERRAJERÍA"), ("REFR", "REFRIGERACIÓN"), ("PLOM", "PLOMERÍA"), ("HERE", "HERRERÍA"), ("CARP", "CARPINTERÍA"), ("TRON", "ELECTRÓNICA"), ] DAYS_OF_WORKS = [ ("LV", "LUNES A VIERNES"), ("LL", "LUNES A LUNES"), ] items = models.CharField(max_length=4, choices = ITEMS) certificate=models.ImageField(default=None) provider = models.ForeignKey(serviceProvider, on_delete=models.CASCADE, null=True) radius = models.FloatField(default=None) description= models.TextField(blank = True) days_of_works = models.CharField(max_length=2,choices= DAYS_OF_WORKS,default= "LV") hour_init = models.TimeField() hour_end = models.TimeField() This is the search for the object I do. Those with a radius equal to 50. Now how can I access another attribute of the model? response=item.objects.filter(radius=data) response.hour_end for example how can I acces to: hour_end atribute? because if I write response.hour_end gives me error -
is this a Django bug?
I created a project and within the project an app call myusers. I then created a model with the class name AllUsers. I then populated the model with data from faker. When I go to 127.0.0.1/admin under authorization I have groups and users. Under myusers I have ‘All userss’ which is a link to http://127.0.0.1:8000/admin/myusers/allusers/ so, I’m just wondering if this is a minor bug. Shouldn’t it say ‘AllUsers’ and not ‘All userss’? Or did I corrupt something along the way? -
display multiple models in one view and get slug url for each post - django
i am trying to show data from multiple models in one single view and one single template and i succeed with that but i have problem , the problem is posts from android model keep show at first because i have added android first in html page but what i want to do is show posts by date published what should i do models.py : class android(models.Model): name = models.CharField(max_length=50,default="") slug = models.SlugField(max_length=250,default="") post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name class Meta: ordering = ('-post_date',) class PCgames(models.Model): name = models.CharField(max_length=50,default="") slug = models.SlugField(max_length=250,default="") post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name class Meta: ordering = ('-post_date',) views.py : def home_page(request): pcgamesforhome = PCgames.objects.all() androidforhome = Android.objects.all() context = {'pcgamesforhome' : pcgamesforhome,'androidforhome' : androidforhome} return render(request,'html_file/home.html',context=context) home.html : <div class="container"> <div class='row'> {% for android in androidforhome %} <div class='col-xs-12 col-sm-6 col-md-4 website-thumb'> <a href="{{ android.slug }}"> <img src="{{ android.get_image }}" class='image_control_for_home_page_pc_games' alt=''> </a> <h3><a href="{{ home_page.slug }}" class="font_control_for_home_page_pc_games_name">{{ android.name }}</a></h3> </div> {% endfor %} </div> <div class="container"> <div class='row'> {% for home_page in … -
Related Object Does Not Exist at /account_settings/ plz help me to resolve this
Here is the code of my project that contains the files models.py, views.py and urls.py. it showing me the error that object does not exist. Exception Type: RelatedObjectDoesNotExist Exception Value: User has no student. now where I was mistaking. please guide me I m a newbie. I searched a lot but unable to resolve it. explain me what is the right code for it. ''' Create your models here. class School(models.Model): schoolid = models.AutoField(primary_key=True) schoolname = models.CharField(max_length=50, null= True) # schoolimage = models.ImageField() schoolcontactno = models.CharField(max_length=13, null= True) schooladdress = models.CharField(max_length=500) createddate = models.DateTimeField(null= True) schoolemail = models.EmailField(null= True) password = models.CharField(max_length=13,null= True) def __str__(self): return self.schoolname class Section(models.Model): sectionid = models.AutoField(primary_key=True) sectionname = models.CharField(max_length=500,null= True) schoolid = models.ForeignKey(School,null= True,on_delete=models.SET_NULL) class Status(models.Model): statusid = models.AutoField(primary_key=True) statustype = models.CharField(max_length=50,null=True) class Client(models.Model): userid = models.AutoField(primary_key=True) username = models.CharField(max_length=50,null = True) ceratedon = models.DateTimeField(null = True) email = models.CharField(max_length=50,null = True) password = models.CharField(max_length=13) certificatetypename = models.CharField(max_length=100,null = True) cnic = models.CharField(max_length=50,null = True) contactnumber = models.CharField(max_length=13,null = True) # image = models.CharField(max_length='',null = True) status = models.ForeignKey(Status, null=True,on_delete=models.DO_NOTHING) confirmpassword = models.CharField(max_length=13,null = True) class TblClass(models.Model): classid = models.AutoField(primary_key=True) # name = models.CharField(max_length=50,null= True) schoolid = models.ForeignKey(School,null= True,on_delete=models.SET_NULL) class RoleName(models.Model): roleid = models.AutoField(primary_key=True) … -
403 Error trying to do a post request in django
I keep getting 403 errors when I try to do a post request in Django. I disabled django.middleware.csrf.CsrfViewMiddleware and i still have this line url(r"viewing_room_capture", csrf_exempt(EmailCapture.as_view()), name="email_capture_endpoint",) Why am I getting a 403? It doesn't even look like my view executes, the request short-circuits before the view runs. And yes I do want to disable the csrf protection on my forms. I seem to remember this working a week ago but I've since rebuilt my local environment from scratch (docker-compose app) and it no longer works. I had 5 working API endpoints before this and now none of them work, I haven't touched this app in 1.5 weeks before coming back to it today and finding everything broken. In fact, I have a development deployment using the same application code running right now in the cloud and I'm not getting 403 errors on my API endpoints (i checked the commit history already, nothing that could have caused this was added since my last deploy). My middleware is: MIDDLEWARE = [ "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "app.site_translation.middleware.TranslationMiddleware", "django.middleware.common.CommonMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.security.SecurityMiddleware", "app.base.middleware.AdditionalSecurityHeadersMiddleware", "app.base.middleware.CookieMiddleware", "app.base.middleware.DomainRedirectMiddleware", "app.base.middleware.CustomRedirectMiddleware", "app.base.middleware.LegacyURLsMiddleware", # Can be used instead if wagtail#4491 is merged: # 'wagtail.contrib.redirects.middleware.RedirectMiddleware', "debug_toolbar.middleware.DebugToolbarMiddleware", ] -
Getting filtered list of another class within the DetailView which is looping through some other class
views.py class UserPublicShell(DetailView): model = User template_name = 'users/public_shell.html' urls.py: urlpatterns = [ path('<int:pk>/public_shell/', UserPublicShell.as_view(), name='public_shell'), The view is showing the public page of a user.This user is not the logged in user in my app. My problem is that I can't give my view only the posts which this user(the user whom the logged -in user is seeing) has written. -
Django: Send data (pandas dataframe) to another app using html link
I have the app: index and I'm using a pandas dataframe named data wich I must send to another app (clean_data) index view: context ={'data' : Data } return render(request,'index.html',context) in my index html template I have a link <a href="{% url 'clean_data:clean_data_v' %}">Clean Data</a> Finally I want to pass "data" from index to clean_data how can I do it? -
How to create two users for same sub category
I have 4 Users(2 X CP_USER, 2 X CP_SCRNS) and two subgroups(Login stats and Application stats) but two of then belong to one group and another 2 belong to another group. Here is the screenshot. Database How to separate two group and display in the html page in the same box.Here is the referenceHere is the reference how the index page shouls look like. . Here is my models page: from django.db import models from datetime import datetime Create your models here. class Kpi_Data(models.Model): kpi_key = models.CharField(max_length=200,default="") kpi_date = models.DateField(blank=True,null=True) kpi_value = models.CharField(max_length=200,default="") kpi_Group = models.CharField(max_length=200,default="") kpi_subgroup = models.CharField(max_length=200,default="") kpi_delta_ind = models.CharField(max_length=200,default="") Here is my views.py file from django.shortcuts import render from django.http import HttpResponse from .models import Kpi_Data from django.template import loader Create your views here. def home(request): return render(request,"myApp/index.html") def info(request): ac = Kpi_Data.objects.all() template = loader.get_template('myApp/info.html') Context = { 'ac': ac, } return HttpResponse(template.render(Context, request)) Thanks in advance. -
How Django search for the module/apps in project folder
This question is related to the following questions. How to import urls from apps in django main urls file Actually I have the following project structure. I want to ask why I have to use complete path link to point the apps in INSTALLED_APPS or even anywhere in the django files. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'climemanage.clients', ] Why I can't use just import climemanage.clients (or any other import statement) and use clients in INSTALLED_APPS ? Same for the urls.py file I have to use the complete path as climemanage.clients.urls the following. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('clients/', include('climemanage.clients.urls')), ] Why not just clients.urls ? -
i have problem creating to different user authentication for two different apps in django
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'db_app1': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite1', }, 'db_app2': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite2' } } i want to create two database set for app1 and app2 where they should have a different authentication database for app1 and app2 -
How do you get libfaketime to work from inside of a Django server?
I am trying to use libfaketime to trick a program (tbl2asn) from expiring. This program is called within a Django view. The Django server sits within a docker container and the following environment variables are set through docker-compose: environment: LD_PRELOAD: "/path/to/libfaketime.so.1" DONT_FAKE_MONOTONIC: 1 FAKETIME_DID_REEXEC: "true" When I use docker exec to get into the container and run python from the command-line, libfaketime works perfectly. However, when it is called from the Django view it does not change the date and the program fails to execute. The code being called from within the view: import os from libfaketime import fake_time import subprocess with fake_time('2018-01-01 00:00:01'): print(datetime.datetime.now()) print(os.environ) subprocess.run([command]) This produces the following output: 2020-12-01 14:00:18.037169 environ({'PATH': ..., 'HOSTNAME': ..., 'LD_PRELOAD': '/path/to/libfaketime.so.1', 'DONT_FAKE_MONOTONIC': 1, 'FAKETIME_DID_REEXEC': 'true', 'HTTPD_PREFIX': '/usr/local/apache2', 'HTTPD_VERSION': '2.4.46', 'HTTPD_SHA256': ..., 'HTTPD_PATCHES': '', 'HOME': '/root', 'LC_CTYPE': 'C.UTF-8', 'TZ': 'America/New_York', , 'RUN_MAIN': 'true'}) And also produces an error when running the subprocess command ([tbl2asn] This copy of tbl2asn is more than a year old. Please download the current version.) -
not able to access organisation's LDAP server through python-ldap
The actual requirement is that I have to achieve LDAP authentication for my organisation's internal web application which is being built on Django but not able to do so by far. Therefore, I have decided to check if i'm able to establish the connection using the python-ldap module. the details of the ldap server that I have: server1 = dc3.something-software.com server2 = dc5.something-software.com domain = SOMETHING and the python code: def main(server="ldap://something.dc5.something-software.com", who="", cred=""): try: l = ldap.initialize(server) l.simple_bind_s(who, cred) if l: print("Successfully connected") except Exception as e: print(e) return True and the error is {'result': -1, 'desc': "Can't contact LDAP server", 'ctrls': []} Im working on a windows operating system and I have tried the answers suggested for other similar questions though they've been mostly addressed for *NIX operating systems. Thanks. -
React: Production build looks different from development build
I have a React/Django app that's behaving differently when built for production that it does when run on the development server. The development version is how I want it to look. There are a number of issues with the CSS. Text is a different font, and a some Bootstrap/Reactstrap features are ignored. See example screenshots below. I think the issue has to do with the order in which css files are processed by the dev server, versus how Django serves the built app, by collecting the files in the /build dir created by the build script into the Django /staticfiles dir. I'm mystified how this would selectively apply classes to the same component, however. (See below - the offset of the jumbotron text is different, while the column size is the same) Here's a screenshot of the home page in the production build, either served locally by Django or remotely on Heroku. (npm run build or npm run build-local - see package.json file below) And here is how it looks on the local dev server: (npm run start) In particular, the offset-md-5 class is ignored on the production build, while the rest of the classes aren't, col-md-5 for example applies … -
How to receive POST data asynchronously in a view?
I am pretty new to django and I am struggling to find a solution to my problem. I am currently working on implementing a third-party payment system on my django website. The problem occurs while trying to get POST data from the payment site. After succesful test-payment, by clicking "Return to seller's site" button I am getting redirected back to my own page with POST request "status=ok". After that, I should receive POST request to url I've added on the payment's site user profile (the same url that I'm getting redirected to). I've been trying to print that data with: @csrf_exempt def payment_result(request): print(request.POST) return render(request, "payment_result.html") but I am getting only: <QueryDict: {'status': ['OK']}> Which is POSTed along with clicking "Return to seller's site" button. The other POST request (with necessary payment data) is not related to the button - it executes asynchronously. I've checked that the payment website is properly sending data with POST request by adding https://webhook.site/ url to seller user profile. What should I do to make it work? Thank you for all the answers. -
How to extract base64 extension without using lib imghdr
I have a view that works perfectly for receiving base64 images. My problem is that in some rare cases it doesn't recognize the sent jpg image. It looks like None. Looking on the internet I saw that the problem is the lib imghdr. I tried to use OS lib to extract the extension and even use the lib pillow, but I couldn't. Does anyone have any tips? Here is an example of how I use imghdr: def get_file_extension(self, file_name, decoded_file): import imghdr extension = imghdr.what(file_name, decoded_file) if extension == "jpeg": extension = "jpg" return extension -
Django Payfast API Errors - Cancelling Subscription (GET/PUT Request)
I am attempting to cancel subscriptions with the payfast api through a website. I have read through this question but as you can see, no solution is provided and it is not Django specific. That answer does mention that you should not use CORS which I took to mean that the server itself should send the request and so I am using the following Django view: def cancel_payfast(request, token): timestamp = datetime.now().astimezone().isoformat() signable_fields = {"merchant_id":str(conf.MERCHANT_ID), "version":"v1", "timestamp":timestamp,} text = urlencode(signable_fields, encoding='utf-8', errors='strict') signature = md5(text.encode('ascii')).hexdigest() r = requests.put('https://api.payfast.co.za/subscriptions/%s/cancel?testing=true'%token, data = {'merchant_id':conf.MERCHANT_ID,'version':"v1",'timestamp':timestamp,'signature':signature}) return HttpResponse(r) The return provided by Payfast is {"code":401,"status":"failed","data":{"response":"Merchant not found.","message":false}} but I have confirmed that the Merchant ID I am using is correct (Payfast sandbox). I decided to try the perhaps simpler task of getting a ping to work, using the same code but replacing "requests.put" with "requests.get" and "cancel" with "ping" but then I get an error from Google(?) saying: "400. That’s an error. Your client has issued a malformed or illegal request. That’s all we know." I will continue to try to fix this, any help is appreciated. -
Is there any way to exclude some field of InlineModel in django admin?
I have two models Gift and Checkout, each Gift has Checkout_id as a foreign key. In the Checkout section of my Django admin, I want to show Checkout properties and related Gifts. Here's what I did: class GiftInline(admin.TabularInline): model = Gift exclude = ('sender_session_token') class CheckoutAdmin(admin.ModelAdmin): list_display = ('id', 'amount', 'retailer_id', 'is_paid', 'requested_at', 'paid_at') inlines = [GiftInline,] admin.site.register(Checkout, CheckoutAdmin) But I want to exclude some fields in the inline view. what can I do? -
Saving form data from a FormView to session
I am trying to capture the POST request data for each field and store it in the session so that I can use the data in another view. But I am getting errors in the other view because the session variables are returning 'None'. Before, I had written the code using a non-class based view and fetched the values with request.POST.get('name') and this worked. What should I be doing here? class TripsView(FormView): """ A view to show all trips and receive trip search data """ template_name = "products/trips.html" form_class = SearchTripsForm def form_valid(self, form): """ Takes the POST data from the SearchTripsForm and stores it in the session """ trip_choice = form.cleaned_data["destination"].id self.request.session["destination_choice"] = trip_choice self.request.session["searched_date"] = "26-12-2021" self.request.session["passenger_total"] = form.cleaned_data[ "passengers" ] return super(TripsView, self).form_valid(form) def get_context_data(self, **kwargs): """ Adds to the context the Product objects categorized as trips """ context = super().get_context_data(**kwargs) context["destinations"] = Product.objects.filter(category=3) return context def get_success_url(self): """ Overides the success url when the view is run """ return reverse("selection") -
Django 'Query' object has no attribute 'contains_column_references'
I am new in Django and i am having trouble on how to configure this error, so that is why i decided to post a question of some of my code, i hope you guys help me on this problem. did i miss or i did wrong in my code? please bear with me. thanks. Error 'Query' object has no attribute 'contains_column_references' Traceback Traceback: File "/home/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/unidaweb/unidaproject/Homepage/views.py" in updateperiod 2289. V_insert_data.save() File "/home/lib/python3.6/site-packages/django/db/models/base.py" in save 741. force_update=force_update, update_fields=update_fields) File "/home/lib/python3.6/site-packages/django/db/models/base.py" in save_base 779. force_update, using, update_fields, File "/home/lib/python3.6/site-packages/django/db/models/base.py" in _save_table 870. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/lib/python3.6/site-packages/django/db/models/base.py" in _do_insert 908. using=using, raw=raw) File "/home/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/lib/python3.6/site-packages/django/db/models/query.py" in _insert 1186. return query.get_compiler(using=using).execute_sql(return_id) File "/home/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql 1334. for sql, params in self.as_sql(): File "/home/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in as_sql 1278. for obj in self.query.objs File "/home/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in <listcomp> 1278. for obj in self.query.objs File "/home/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in <listcomp> 1277. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/home/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in prepare_value 1208. if value.contains_column_references: Exception Type: AttributeError at /updateperiod/ Exception … -
Python3: Pydub export function returns NoneType
Consider the following code: from pydub import AudioSegment from django.core.files import File def slice_audio(start, duration, audio_file): ''' Returns sliced mp3 audio file. ''' start = int(start) * 1000 # Convert to miliseconds duration = int(duration) * 1000 # Convert to miliseconds end = start + duration fade_in = 100 fade_out = 500 segmented = AudioSegment.from_file(audio_file) sliced = segmented[end:].fade_in(fade_in).fade_out(fade_out) return File(sliced.export(format="mp3")) slice_audio(10, 10, 'myfile.mp3') The problem i currently facing is the that return value is NoneType. Now if i change the return code to return File(sliced.export('newFile.mp3', format="mp3")), a file is indeed produced but fails to wrap in the File(). Thus having a NoneType returned My django model field: audio_snippet_file = models.FileField(null=True, upload_to=upload_Music_AudioSnippets) -
How to add filtering for function based views in Django Rest Framework
I'm trying to add filters to my function-based views. Using Class Based Views I was able to add filters to views. But I'm curious if I can add filtering to this function based views. I need to filter subject by it's name through a web search. How I can achieve that @api_view(['GET']) @permission_classes([IsAuthenticated]) def TeacherSubject(request): teacher = TeacherProfile.objects.get(user=request.user) subject = Subject.objects.filter(author=teacher).order_by('-id') paginator = PageNumberPagination() paginator.page_size = 5 result_page = paginator.paginate_queryset(subject, request) serializer = SubjectSerializer(result_page,many=True) return paginator.get_paginated_response(serializer.data) -
Bad Request on File upload
I have setup my python project using nginx and gunicorn as described in this tutorial https://djangocentral.com/deploy-django-with-nginx-gunicorn-postgresql-and-lets-encrypt-ssl-on-ubuntu/ so far everything works perfectly fine. My project is in /root/project_folder/ I want to upload files via the admin page, but I get a bad request error 400. The media folder I want to add the files to is /var/www/my_domain/media (owned by the group www-data). This is also properly configured since I can see the images when I move them manually into that folder. Do you guys maybe have any idea why the issue may be ? the main problem is when uploading I need to save the image to the media root: /var/www/domain/media/images/dad/ProfilePicture/offline_screen.png But when I send request to view the image the web server returns the following: /media/var/www/domain/media/images/dad/ProfilePicture/offline_screen.png The upload_to path needs to be images/dad/ProfilePicture/offline_screen.png for correct request but then the image is uploaded to the wrong folder Any ideas ? Thanks in advance! -
how to store third party access token to database to my profile model from views.py django
i'm trying to store a session id and an access token from a third party website's API to my users profiles i've been trying for days and searching but i couldn't find anything like this i tried to import profiles instances so that i can save the data to the users profiles instances but i didn't find out how , here is my code #views.py from bs4 import BeautifulSoup import xml.etree.ElementTree as ET from django.contrib.auth.decorators import login_required import urllib.parse from django.views.generic import View from users.models import Profile from django.contrib.auth.models import User def profile_view(request): RuName= 'driss_aitkassi-drissait-crm-SB-ijuzzy' r= { 'RuName': RuName } response = api.execute('GetSessionID', r) print(response) res =response.text tree= ET.fromstring(res) #here is my session id from the website's api for node in tree.iter('{urn:ebay:apis:eBLBaseComponents}GetSessionIDResponse'): SessionID= node.find('{urn:ebay:apis:eBLBaseComponents}SessionID').text #i tried this : s=Profile(session_id=SessionID) s.save() # and also tried this # and also this: Profile.objects.update(session_id=SessionID) Profile.objects.model.save() here is the Models.py file: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User,related_name='profile' , on_delete=models.CASCADE) token = models.TextField(max_length=500, blank=True) session_id=models.TextField( max_length=500, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) please help me with this or just point me at … -
Boolean field is not updated on ajax call to a DRF viewset
As title says, boolean field is not updated on PATCH request to a DRF viewset. It returns 200 and correct data: {id: 18, score: "", questions_answered_amount: 3, is_completed: true,........} and all values are proper, despite this boolean is_completed, which value remains false. My model: ... is_completed = models.BooleanField(default=False) ... The viewset: class UserPassedTestViewSet(viewsets.ModelViewSet): queryset = UserPassedTest.objects.all() serializer_class = UserPassedTestSerializer permission_classes = [permissions.IsAuthenticated] @action(detail=False, methods=['patch'], permission_classes=[permissions.IsAuthenticated]) def add_option(self, request): option_id = request.POST.get('option_id') relation_id = request.POST.get('relation_id') option = Option.objects.get(id=option_id) relation_object = UserPassedTest.objects.get(id=relation_id) if not relation_object.questions_answered.filter(id=option.question.id).exists(): relation_object.questions_answered.add(option.question) relation_object.selected_options.add(option) relation_object.questions_answered_amount = F('questions_answered_amount') + 1 relation_object.save() else: existing_option = relation_object.selected_options.get(question_id=option.question.id) relation_object.selected_options.remove(existing_option) relation_object.selected_options.add(option) return JsonResponse({'success': 'added'}) Ajax call: $.ajax({ headers: { 'X-CSRFTOKEN': token }, url: 'http://127.0.0.1:8000/api/v1/userpassedtest/' + relation_id + '/', type: 'patch', dataType: 'json', data: {'is_completed': 'True'}, success: function(data) { console.log(data) } }) I have tried changing it to just true, to not be a string, or to 1 but it doesn't work.