Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get time differance in hours between to date in python(Django)
i was try to subtract two date those are stored in database to get differance in hours. But those values in query sets so i am unable subtract it : like: date1=table.objects.values_list('field1').filter(id=1)) date2=table.objects.values_list('field1').filter(id=2)) timediff= date1-date2 so please give the solution -
How get URL from QuerySet of Django?
# Need: some_method(SomeModel.objects.filter(some_field='some_value')) # returns '?some_field__exact=some_value' — as is on admin pages changelists Is there such a function? Thanks. -
Mysql connecting issue in django 1.9
I am getting the following error when trying to connect mysql db [Fri Mar 31 09:04:54.154874 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] mod_wsgi (pid=16451): Target WSGI script '/home/abhadran/network_python3/netmap/netmap/wsgi.py' cannot be loaded as Python module. [Fri Mar 31 09:04:54.154920 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] mod_wsgi (pid=16451): Exception occurred processing WSGI script '/home/abhadran/network_python3/netmap/netmap/wsgi.py'. [Fri Mar 31 09:04:54.154942 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] Traceback (most recent call last): [Fri Mar 31 09:04:54.154960 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] File "/home/abhadran/network_python3/netmap/netmap/wsgi.py", line 21, in <module> [Fri Mar 31 09:04:54.156034 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] application = get_wsgi_application() [Fri Mar 31 09:04:54.156062 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Fri Mar 31 09:04:54.156125 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] django.setup() [Fri Mar 31 09:04:54.156140 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/__init__.py", line 18, in setup [Fri Mar 31 09:04:54.156170 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] apps.populate(settings.INSTALLED_APPS) [Fri Mar 31 09:04:54.156182 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate [Fri Mar 31 09:04:54.156290 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] app_config.import_models(all_models) [Fri Mar 31 09:04:54.156310 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models [Fri Mar 31 09:04:54.156373 2017] [wsgi:error] [pid … -
Apply pagination on returned paginated data from Ajax call
I am using AJAX call to get data from Django view.py. In View.py I am using Paginator. So I got data only in 1 page other pages are not shown because python get pages before AJAX call. Now how I can show It on template ? ScreenShot of Situation Only showing Page . "instead of next and previous" //AJAX CALL function loadMaps(id) { var field = { id : id }; var field1 = { id : id }; jQuery.ajax('{% url "mapport.maps.product" %}', { data : field, data2 : field1, success: function(response, status, xhr) { showMaps(response.data) console.log(response.data); console.log(response.data2); } }); } function showMaps(data) { //foreach var tbody = $('#tbl-maps tbody'), tr; tbody.html(''); $.each( data, function( key, value ) { tr= $('<tr></tr>'); tr.append('<% 9.times do %><td><input type="checkbox" name="ids" value="'+data[key].id+'"></td><% end %>'); tr.append('<td>'+data[key].name+'<td>'); tr.append('<td><a href="/'+data[key].slug+'">Main Interface</a><td>'); tr.append('<td><a href="/maps/'+data[key].id+'/">Dashboard</a><td>'); tbody.append(tr); }); **View.py** queryset = Map.objects.order_by('name') id = self.request.GET['id'] self.maps = queryset.all().filter(map_type=id) page = self.request.GET.get('page', 1) dictionaries2 = [obj.as_dict() for obj in self.maps] paginator = Paginator(dictionaries2, 1) try: dictionaries2= paginator.page(page) except PageNotAnInteger: dictionaries2= paginator.page(1) except EmptyPage: dictionaries2 = paginator.page(paginator.num_pages) dictionaries = [obj.as_dict() for obj in self.maps] return HttpResponse(json.dumps({ "data": dictionaries2.object_list , "data2" : dictionaries }), content_type='application/json') -
How to release the _jobstores_lock in apscheduler with django framework?
i use django to build a web-app and apscheduler to add a job when start the server and call get_job beore add_job to check exists start_scheduler() history_job_store_init() if platform.system() == 'Linux': if myscheduler.getjob('job1') is None: myscheduler.addjob(func=job1func, trigger='cron', minute=0, id='job1', name='job1') use runserver to start python manage.py runserver 0.0.0.0:9000 but unfortunately, server can't start, no exception, no warning then i use pdb to track what happened it was stucked in get_job function by the code with self._jobstores_lock the last time runserver i press CTRL + C to quit, maybe that moment apscheduler was accessing data through sqlite database, and database was locked as far as i know, django doesn't have a hook to run code on exit, so i can't call the shutdown method in scheduler is there any method to release the lock of database before get_job? thx a lot -
Error while declaring a list of lists in django
I am trying to declare an array in django, however I need one more column, since in my case the array position [0] [0] should be empty for better table display but when I will declare the array in my view Matrice = [[0 for i in range (len (evaluators) +1)] for j in range (len (candidates))] And I refresh the page I get the error: Need 2 values to unpack in for loop; Got 3. The problem is in "len (evaluators) +1" because when I shoot +1 it works perfectly. Why am I not able to declare the array this way? In the shell (python3 mana.py shell) this worked without problems ... views.py from django.shortcuts import render, get_object_or_404 from .models import Candidate, Criterion, Evaluation from django import forms from .forms import CandForm from .forms import EvalForm from .forms import TestForm from django.shortcuts import redirect from django.db import IntegrityError def canditate_list(request): candidates = Candidate.objects.all() eva = Evaluation.objects.all() eval_cand_list = [] #aqui guarda uma lista com os FK candidates convertidos p/ str var = 0 var2 = {'v1':2} context = { 'candidates': candidates, 'eva': eva, 'var': var, 'var2':var2 } return render(request, 'app/candidate_list.html',context) def candidate_detail(request, pk): candidate = get_object_or_404(Candidate, pk=pk) c_name = … -
Added wrong default value in new field and now can't migrate
I added a user foreign field in one of my models and made a migration. I was prompted to add a default value. The default value for user is suppose to be Int, representing the user_id. Instead of adding an Int, I added a string "username". Now I'm stuck with: return int(value) ValueError: invalid literal for int() with base 10: 'testuser' I deleted all the objects associated with the model, and tried migrating, that didn't work, getting same error. (Model.objects.all().delete()) I reverted to a previous migration, that didn't solve the problem, when I migrated, it got the same ValueError. (./manage.py migrate app 0037_auto_20170330_0326) Lastly, I deleted my new foreign field, but that didn't solve the issue either. What other options do I have in such a scenario? My model is very simple: class Chat(models.Model): user = models.ForeignKey(User) #new field that was added message = models.CharField(max_length=50) -
Django nested Transaction.atomic not rolled back
I have two logically connected instance in two different data bases. I want them both to be saved or rollbacked. But if I raise an exception in an outer block - nested Transaction.atomic will not rollback, but why? From documentation: atomic blocks can be nested. In this case, when an inner block completes successfully, its effects can still be rolled back if an exception is raised in the outer block at a later point. def __commit_to_db(self, mesure, mdm_mesure): try: with transaction.atomic(): mesure.save() with transaction.atomic(using='mdm'): mdm_mesure.save() raise Exception('oops') except (KeyboardInterrupt, SystemExit): raise except BaseException as error: MainLoger.log_error(error) return -
In Django ORM, "values" and "annotate" are not working to group by
I have a table like this: Now I want to sum up the meals on each date. I have written the code below. But it doesn't work as I wanted. Code: meals_list = Meal.objects.values('date_of_meal').annotate(mm=Sum('morning_meal'), mdm=Sum('mid_day_meal'), nm=Sum('night_meal')) Output: <QuerySet [{'mdm': 0, 'mm': 1, 'date_of_meal': datetime.date(2017, 3, 23), 'nm': 1}, {'mdm': 1, 'mm': 1, 'date_of_meal': datetime.date(2017, 3, 23), 'nm': 0}, { 'mdm': 1, 'mm': 0, 'date_of_meal': datetime.date(2017, 3, 22), 'nm': 1}, {'mdm': 0, 'mm': 1, 'date_of_meal': datetime.date(2017, 3, 22), 'nm': 1}, {'mdm': 1, 'm m': 1, 'date_of_meal': datetime.date(2017, 3, 21), 'nm': 1}, {'mdm': 1, 'mm': 1, 'date_of_meal': datetime.date(2017, 3, 21), 'nm': 1}, {'mdm': 1, 'mm': 1, 'date _of_meal': datetime.date(2017, 3, 20), 'nm': 1}, {'mdm': 1, 'mm': 1, 'date_of_me al': datetime.date(2017, 3, 20), 'nm': 1}, {'mdm': 1, 'mm': 0, 'date_of_meal': d atetime.date(2017, 3, 19), 'nm': 0}, {'mdm': 0, 'mm': 0, 'date_of_meal': datetim e.date(2017, 3, 19), 'nm': 1}]> It repeats same date multiple times. But I wanted liked this: <QuerySet [{'mdm': 1, 'mm': 2, 'date_of_meal': datetime.date(2017, 3, 23), 'nm': 1}, {'mdm': 1, 'mm': 1, 'date_of_meal': datetime.date(2017, 3, 22), 'nm': 2}, ............ ............ so on........ ]> How can I get my expected output ? -
Difference between 'related_name' and 'related_query_name' attributes in Django?
Can you explain the difference between related_name and related_query_name attributes for the Field object in Django ? When I use them, How to use them? Thanks! -
How improve 2Million data query speed in Django RESful APIs
I have a scientific research publications data of 2 Million records. I used django restframework to write apis for searching the data in title and abstract . This is taking me 12 seconds if I'm using postgres as db, but if I used MongoDB as db, it goes down to 6seconds. But even 6 seconds sounds a lot of waiting for user to me. I indexed the title and abstract, but abstract indexing failed because some of the abstract texts are too lengthy. Here is the django Model using MongoDB(MongoEngine as ODM): class Journal(Document): title = StringField() journal_title = StringField() abstract = StringField() full_text = StringField() pub_year = IntField() pub_date = DateTimeField() pmid = IntField() link = StringField() How do I improve the query performance, what stack makes the search and retrieval more faster?. -
Click event of button not working - jQuery?
I am working with a web application in Django and I have page with a list of records, a search field and a button. When I click on the button a modal opens which has a save button. If I click the save button all that happens is that an alert comes up saying "test". The above works fine before I conduct a search. Once I search for something and the results are loaded on the page, if I click my button and click the save button on the modal, nothing happens, I can't print to the console and I also cannot see my alert message... What could be causing this? I know somewhere I am doing something wrong, but any ideas as to what to look for would be great. My code to handle the click on the save button is (this is stored in a JS file called modalHandlerJS): $(document).ready(function() { $("#saveButton").click(function() { alert("test"); }); }); My modal looks like this: <div class="modal fade" id="modalHandlerJS" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-footer"> <button type="button" class="btn btn-default" id="saveButton">Save</button> </div> <!-- end modal-footer--> </div> <!-- end modal-content --> </div> </div> Note that the button to open my modal is … -
How to check if user is in a certain table
I have my user table in django, and to differ all the users I created two tables, (Teacher and Student). Both tables are getting an fk from user So, in order to make authorization how do I check if one's user is in a certain table. I need to check it this way def test_func(self): return self.request.user.check..if..it..exists..in..table -
Wagtail how to add a extra form fields to admin page edit form and get wagtail rendering
This is what I tried. It works but the extra field text1 is rendered as a plain input field with no label and no cool wagtail rendering. How can I add extra fields to the form and get cool wagtail rendering please? Here is a link to the WagtailAdminPageForm documentation: http://docs.wagtail.io/en/v1.9/advanced_topics/customisation/page_editing_interface.html#customising-generated-forms class Review(models.Model): page = models.OneToOneField( 'wagtailcore.Page', verbose_name=('page'), related_name='review', on_delete=models.CASCADE) text1 = models.CharField(null=True, blank=True, max_length=50) class RandomPageForm(WagtailAdminPageForm): """ Custom form for RandomPage """ text1 = forms.CharField() def __init__(self, data=None, files=None, parent_page=None, *args, **kwargs): super(RandomPageForm, self).__init__(data, files, *args, **kwargs) if self.instance.id: review, created = Review.objects.get_or_create(page_id=self.instance.id) print "set form.text1 to model.text1" self.fields['text1'].initial = review.text1 # !!! Below has no effect self.instance.content_panels = Page.content_panels + [ FieldPanel('body'), FieldPanel('text1'), ] def save(self, commit=True): page = super(RandomPageForm, self).save(commit=False) review, created = Review.objects.get_or_create(page=page) review.text1 = self.data["text1"] review.save() return page class RandomPage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ] base_form_class = RandomPageForm Attached is an image of the plain input box -
Use model attribute as field parameter
I'm trying to create a folder and upload an image to in it. My model is similar to this: class XYZ(models.Model): def code(self): syms = ['@','#','$','%','&','*','+','-'] return ''.join(x+random.choice(syms) for x in [self.name[-2:],self.name[2:]]) def make_folder(self): os.mkdir(os.getcwd()+'/XYZ/'+folder) def save(self): self.make_folder() super(XYZ,self).save(*args,**kwargs) name = models.CharField(max_length=20) folder = property(code) image = models.ImageField(upload_to='HELP_HERE') I've tried using folder, self.folder, property(code) but it says it isn't defined, how do I access this attribute? Is this the correct approach? I've also set in the configs.py my MEDIA_URL and MEDIA_ROOT -
How is HttpResponseRedirectBase class being called when I call HttpResponseRedirect
I am trying to figure out how HttpResponseRedirectBase is being called when I call this return HttpResponseRedirect(next_page, context) I believe this question has more to do with python than Django but I cannot find the answer to this question.I understand that in python the derived class needs to explicitly call the __init__ of the base class in order to initialize it.So far this is what I have seen class HttpResponseRedirect(HttpResponseRedirectBase): status_code = 302 Now my question is how is the initializer of HttpResponseRedirectBase being called here ? I tried simulating the above situation def foo(object) : def __init__(self,par): print "Inside foo constructor" class bar(foo): status_code = 302 b = bar(23) I am not sure how init of foo will be called in this case ? In this case I get the error Traceback (most recent call last): File "python", line 5, in <module> TypeError: Error when calling the metaclass bases function() argument 1 must be code, not str Any help clearing this out would be appreciated. -
Django Admin list_display product list
I new in django and I trying modifying a project to learn. I've two classes in a model ('Order' and 'OrderItem'), the class OrderItem stores all items selected in a client order. models.py class Order(models.Model): STATUS_CHOICES = ( (0, 'Waiting Payment'), (1, 'Completed'), (2, 'Canceled'), ) PAYMENT_OPTION_CHOICES = ( ('deposit', 'deposit'), ('paypal', 'Paypal'), ) user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='User') status = models.IntegerField( 'Situation', choices=STATUS_CHOICES, default=0, blank=True ) payment_option = models.CharField( 'Payment Options', choices=PAYMENT_OPTION_CHOICES, max_length=20, default='deposit' ) created = models.DateTimeField('Created in', auto_now_add=True) modified = models.DateTimeField('Modified in', auto_now=True) objects = OrderManager() class Meta: verbose_name = 'Order' ordering = ('-created',) def __str__(self): return 'Order #{}'.format(self.pk) def products(self): products_ids = self.items.values_list('product') return Product.objects.filter(pk__in=products_ids) def total(self): aggregate_queryset = self.items.aggregate( total = models.Sum( models.F('price') * models.F('quantity'), output_field = models.DecimalField() ) ) return aggregate_queryset['total'] class OrderItem(models.Model): order = models.ForeignKey(Order, verbose_name='Order', related_name='items') product = models.ForeignKey('event.Product', verbose_name='Product') quantity = models.PositiveIntegerField('Quantity', default=1) price = models.DecimalField('Price', decimal_places=2, max_digits=8) class Meta: verbose_name = 'Order Item' def __str__(self): return '{}'.format(self.product) In the django admin I can show all Orders and when I click to see more I see all products on this order, but my problem is, I can't list this products of class OrderItem in my list_display, how can I do that? admin.py … -
How would I direct all traffic that hasn't logged in to django allauth login
Want to direct all un-logged in traffic to the login page. How would I go about doing this? I don't want visitors to be able to see the site at all if they are not logged in. As well, the allauth signup page should not be able to be accessed either. Users will be pre-registered for the site. I'm fairly new to django and would not want to abandon allauth as I have it working. -
Problems extending my Django user model
I have a simple django app, and am trying to set up a custom Django User Model so that I can have users log in with their email field. I think I set everything up well enough, its all fairly straightforward, however when trying to actually run the migrations I get this error: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial Seems weird? I'm having trouble understanding why it's having trouble understanding. Heres the User model Im implementing from __future__ import unicode_literals from django.db import models from django.core.mail import send_mail from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) display_name = models.CharField(_('display name'), max_length=30, blank=True) bio = models.TextField(blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name … -
How to configure nginx to run Wordpress and Django
I've looked at a couple similar question, but they didn't seem to be any help. I've got a vultr.com instance running a Wordpress in the default 1 click configuration. Centos6 if that matters. This is (and I would like it to remain) in the root (www.mysite.com). I would like to have my Django app running in www.mysite.com/crossfaded/. I don't want any downtime for my current server, so there is no domain name associated with the server yet. I'm trying to do this just using the IP. The Wordpress site is working fine. I've been following the guide here as then tried this one, but when I navigate to http://ip.add.re.ss/crossfaded/media/apple.jpg in my browser, I get a 404 from nginx. Going /crossfaded/media/ gives me a 403 from nginx and /crossfaded/invalidpath/ gives me a 404 served by Wordpress, so something is happening with the routing. I did chmod 777 apple.jpg on the off-chance it was a permissions issue, but that didn't do anything. I have a hunch I've got the syntax of the location block muddled, but I'm really not sure. wordpress_http.conf upstream php-handler-http { server 127.0.0.1:9000; #server unix:/var/run/php5-fpm.sock; } server { listen 80 default_server; server_name _; #server_name wordpress.example.com; root /var/www/html/; index index.php; … -
Set primary key of a django model to a custom generated string
I want my model's ID to be set to a hash code that looks something like: u-timestamp-user_email --- example: u-20170330182954email@gmail.com the user_email part is another field of the same model. Currently my model looks like this: def _generateHash(): return datetime.datetime.now().strftime("%Y%m%d%H%M%S") # Create your models here class User(models.Model): MANAGER = 'm' USER = 'u' ROLES = ( (MANAGER, 'Manager'), (USER, 'User'), ) user_name = models.CharField(max_length=200) email = models.CharField(max_length=200) role = models.CharField(max_length=1, choices=ROLES, null=True) hash_code = models.CharField(max_length=500, primary_key=True, default=_generateHash, unique=True, editable=False) def save(self): self.hash_code = self.role+'-'+self.hash_code+self.user_name super(User, self).save() It gets the job done but whenever I update a model instance, instead of updating that certain instance, it creates a new instance. I figured the overriden save() method is the reason for creating the new instance. Is there a workaround for this to achieve the custom primary key? -
Django searching for objects by criteria
I know this question is vague but I am hoping it will promt some interesting responses. I am trying to figure out how to accomplish my next Django project and I am having a hard time. I would like to write a Django app that allows someone to enter their information, for example, their age, gender, marital status, etc. and have it return charitable programs that they may qualify for. So here we go: An organization would create a program and enter in the type of person it is directed towards. Then someone could input their info and have it return what programs they qualify for. The program criteria as well as the user information would be selected by a form ChoiceField. The problem I am having is figuring out how to make the relation between user information and the program criteria. I have a few ideas on how to make this work but I would love to know how a more experienced programmer would handle this task. Any information/opinions is encouraged. Thank you. -
Website doesn't want to work with any API on localhost. Magic
I'v got a huge problem. My website doesn't want to work with any API on localhost. At previous project everything was always fine and I worked a lot with API. So I guess something al local setup does't allow things work, so I hope you help with advice how to debug . Also I ran old project and they raise the same error, so it's definitely something wrong with my OS X. Django 1.8 Application out of any container running on http://127.0.0.1:8000/ . I was trying to set up both VK and Facebook API but init methods don't work. But same code was tested by Facebook support and it worked fine. Details here https://developers.facebook.com/bugs/1258091197620173/ I deleted any other js code, checking everything so it has something to do with my OS X system because I got the same problem with another social network api throught I am pretty much sure settings are fine at both.So I guess Facebook API and VK API do not consider http://127.0.0.1:8000/ as correct and allowed, throughout app domain in their settings is localhost and site url http://localhost:8000/ What could be possibly wrong? Tried all possible variants. It's django app without any container and I quit … -
Django - serving a SPA from static folder
Our django server is our API as well as an operations backend. I'm working on improving our ops backend by writing a Vue SPA that slowly replaces the existing ops backend. I'm frontend and a little lost in intricacies of Django configs. Could someone suggest a sane solution for this problem? I would like for the app to be served out of static folder, and have set: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, '../console/dist'), ) This works and I can see my code when I view source, but only at http://localhost:8000/static/console/index.html 1) this won't work because as a SPA, Vue needs control of routing. From the Django side how can I have /static/console/* use my Vue app? On the Vue end, what do I have to configure in Webpack and Vue-router? 2) despite the fact that I can see my compiled app source, I get errors: Creating Application Cache with manifest http://localhost:8000/static/appcache/manifest.appcache index.html:1 Application Cache Checking event index.html:1 Application Cache Downloading event index.html:1 Application Cache Progress event (0 of 7) http://localhost:8000/favicon.ico index.html:1 Application Cache Error event: Resource fetch failed (4) http://localhost:8000/favicon.ico index.html:1 Uncaught (in promise) TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when … -
Set-Cookie header missing from ajax response in iOS 10.3
My phonegap app communicates with django, so I use the method described in the following article to capture and send csrftoken: https://docs.djangoproject.com/en/1.10/ref/csrf/ This has been working till iOS 10.3. In iOS 10.3, the ajax call gets all response headers except Set-Cookie. I tried adding xhrFields: {withCredentials: true} and crossDomain: true but it makes no difference. Here is the request to get the csrftoken: $.ajax({beforeSend: function(xhr) {xhr.withCredentials = true;}, type: "GET", url: 'url', // the django view has @ensure_csrf_cookie set xhrFields: {withCredentials: true}, crossDomain: true, success: function(data, textStatus, xhr) { // returns null in iOS 10.3 document.cookie = xhr.getResponseHeader("Set-Cookie"); }, }); The same code works fine in iOS 10.2 and we can save the csrftoken from "Set-Cookie" header for later use. iOS 10.3 somehow prevents this "Set-Cookie" response header from appearing in the xhr object, thus we cannot get the csrftoken from server and any subsequent POST action will be forbidden.