Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Linking Django wepages
I am currently creating a python application using the Django web framework. In the app users can login and create personal goals. These goals are stored in a database and users are able to view them. I am having trouble linking the webpages within the app. When i try to click onto another webpage I am getting an AttributeError telling me that their is know Reverse for 'goal_create' not found. 'goal_create' is not a valid view function or pattern name This is how I am trying to implement the app: Models //The information that i am storing in the DB class Goal(models.Model): title = models.CharField(max_length=1000) body = models.TextField() created_data = models.DateTimeField(auto_now_add=True, auto_now=False) updated_data = models.DateTimeField(auto_now_add=False, auto_now=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.title Views //the list of goals that the User will see on the webpage. def goal_list(request): goals = Goal.objects.all().order_by('created_data') return render(request, 'goals/goal_list.html', { 'goals': goals }) @login_required def goal_create(request, *args): if request.method == 'POST': form = forms.CreateGoal(request.POST, request.FILES) if form.is_valid(): goal_create = Post(CreateGoal.title.data, CreateGoal.text.data) # save article to db //Returns the list of goals after it has been created. return redirect('goals:goal_list') else: form = forms.CreateGoal() return render(request, 'goals/goal_create.html', {'form': form}) Urls app_name … -
Django, can't login in admin panel
I created user in django shell and tried to authenticate it, but can't. That return nonetype. Also, I check that is_superuser, is_stuff, is_active is True >>> from django.contrib.auth.models import User >>> from django.contrib.auth import authenticate >>> User.objects.create(username='user', password='password', email='someemail') >>> User.objects.all() >>> <QuerySet [<User: admin>, <User: user>]> >>> admin >>> user = authenticate(username='user', password='password') >>> user >>> user.is_active Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'is_active' >>> type(user) <class 'NoneType'> >>> admin = authenticate(username='admin', password='wa23sd54fg') >>> admin <User: admin> >>> admin.is_active() Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'bool' object is not callable >>> admin.is_active True >>> user = User.objects.get(pk=2) >>> user <User: user> >>> user.is_active True >>> user.is_superuser True >>> user.is_staff True When tried log in with use in admin panel, that take error: "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." -
Using trusted connection with username and password for MS SQL in Django
I'm trying to connect to a MS SQL Server database in a Django app using pyodbc. I need to use a trusted connection with my username and password, is there a way of defining all of those attributes in the settings.py DATABASES object? When I define USER and PASSWORD I get the following error: django.db.utils.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'my_user'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 13 for SQL Server]Invalid connection string attribute (0); [28000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'my_user'. (18456); [28000] [Microsoft][ODBC Driver 13 for SQL Server]Invalid connection string attribute (0)") When I leave the USER and PASSWORD fields blank I can connect to the database but can't access all the tables that I need due to permissions. Thanks! -
Templates working local but not on pythonanywhere.com
I have a working project in django when I run it local works perfectly but not when I run it on pythonanywhere.com. I get a simple template, is not the same. How do I make it run perfectly on pythonanywhere.com? Do i have to do something in the code or in pythonanywhere web app settings? Thanks! My code: settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) APPS_DIR = os.path.join(BASE_DIR, 'lab_access_control') DEBUG = False INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'lab_access.apps.LabAccessConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(APPS_DIR, 'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(APPS_DIR, 'static'), ] -
How to replace   with white space
I'm using this to remove {{i.content|truncatewords:30|striptags|safe|cut:"&nbsp;"}} but it leaves no spaces between words. I want to replace each &nbsp; with a white space. -
django rest framework: getting two post request in the back end
I have an Angular app posting registration message to my django back-end, however, when I click on register button on the page, I got tow post request in the django logging, like this [17/Apr/2018 22:13:47] "OPTIONS /user/register HTTP/1.1" 200 0 [17/Apr/2018 22:13:47] "POST /user/register HTTP/1.1" 500 27 [17/Apr/2018 22:13:47] "POST /user/register HTTP/1.1" 201 91 Chrome dev tool - Network It is just annoying when testing locally, but when I deploy this on a ubuntu server(with uwsgi and nginx), the back-end seems to crash. I am not sure if this is the problem, I am just checking every possibility that I can think of. BTW: I am using sqlite, it is because of the transaction? Angular registration.component.js import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core'; import { NgForm } from "@angular/forms"; import { HttpClient } from "@angular/common/http"; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.scss'] }) export class RegisterComponent implements OnInit, AfterViewInit { formData = {} as any; isHide: boolean; constructor( private http: HttpClient, ) { this.isHide = true; } formErrors = { 'email': '', 'userName': '', 'password1': '', 'password2': '', 'phone': '' }; validationMessages = { 'email': { 'required': '邮箱必须填写.', 'pattern': '邮箱格式不对', }, 'userName': { 'required': '用户名必填.', 'minlength': '用户名太短', }, … -
Django - getting a list of foreign key (related) objects
Having a model: class Combination(models.Model): changed_by = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='combinations') how do I get a list/queryset of all users, that created such a Combination? -
how to change admin view to user view
changing the admin application to user application i am working on the following Django project https://github.com/AlexPnt/django-calendar this app works only on the admin view. and i want to make it in the users view. i want to make a simple scheduling application where we need not to go to admin page and can do scheduling directly without any login. is it possible? can anyone help me -
Scaling Django File Uploading
I have recently created a Inline form Set to manage files uploading. My objective is hosting my files on AWS. I have a model House. The model has a related Model HouseDocument where files related to a house are stored. HouseDocument has House as a ForeigKey. This is the view : def manage_files(request, house_slug): house = House.objects.get(slug=house_slug) HouseDocumentInlineFormSet = inlineformset_factory(House, HouseDocument, fields=('document',)) if request.method == "POST": formset = BookInlineFormSet(request.POST, request.FILES, instance=house) if formset.is_valid(): formset.save() return HttpResponseRedirect(house.get_absolute_url()) else: formset = BookInlineFormSet(instance=author) return render(request, 'manage_books.html', {'formset': formset}) I'm not seeking a code example. I seek advice on how big web applications handle file uploading when they have a lot of concurrent users ? Any useful documentation ? Does Django IO blocking makes file upload complicated ? -
DB inserts in a Django app gradually get slower as more inserts are executed
I am inserting a large amount of rows to a Postgresql db using Django ORM bulk_create(). I have the following code: entries = [] start = time() for i, row in enumerate(initial_data_list): serializer = serializer_class(data=row, **kwargs) serializer.is_valid(raise_exception=True) entries.append(MyModel(**serializer.initial_data)) if i % 1000 == 0: MyModel.objects.bulk_create(entries) end = time() _logger.info('processed %d inserts... (%d seconds per batch)' % (i, end-start)) start = time() entries = [] Measured execution times: processed 1000 inserts... (16 seconds per batch) processed 2000 inserts... (16 seconds per batch) processed 3000 inserts... (17 seconds per batch) processed 4000 inserts... (18 seconds per batch) processed 5000 inserts... (18 seconds per batch) processed 6000 inserts... (18 seconds per batch) processed 7000 inserts... (19 seconds per batch) processed 8000 inserts... (19 seconds per batch) processed 9000 inserts... (20 seconds per batch) etc., the time keeps growing as more insertions are made. Some observations: When the request is finished, and I execute an identical request, the measured times look pretty much identical: Start from decently low, and begin growing from there. No process-restart between the requests. The effect is the same, whether I'm doing individual insertions using serializer.save(), or bulk_create(). The execution time of the bulk_create() line itself keeps about the same, … -
Multidimensional array model Django
TLDR: trying to send a 2d array with django rest and it fails, why? So here is my situation. I am creating a ingest tool to take in data, that is created by someone else. Part of this data is a 2d array or a list of lists, whatever strikes your fancy. Something like this being a list of lists of floats in this case Data = [[1,2,3,4,5,6],[1,2,3,4,5,6]] I am trying to use a Django rest service to do this because thats what i have been using for everything else i have done. Anyway this data type is given to me in a json format along with other datatypes Which i will show as well. On the model side of this i have a model of the main dataType that data would go into which looks like this class dataType(models.Model): data = ArrayField(ArrayField(models.FloatField(blank=True, null=True), null=True), null=True) data1 = ArrayField(models.FloatField(blank=True, null=True), null=True) ... other data Now data is the one i am having issues with. data1 will work fine as long as its just singular dimensional array(list). when i run the code with this i get an error saying this Expected a list of items but got type \\"str\\"."]}' even though … -
If I've uploaded my Django app on Heroku, what is the architectural structure?
Heroku instructs that gunicorn be used to start the server, but from my understanding, gunicorn is an interface/gateway. Which web server is being used? Why was it that I never had to configure any part of this when deploying on Heroku? I'm essentially curious what the architectural structure is of the typical Django app deployed on Heroku. -
New Django app initial DB migrations of an existing database
I have an existing database filled with a bunch of data. I want to migrate to Django so I went ahead and created the necessary models with python manage.py inspectdb. I haven't changed anything besides removed the managed = False since I want Django to manage the tables (mistake perhaps for initial migration?). So now that the models are ready, how can I generate the first migration file so that I can start changing the fields to generate additional migrations (renaming a field here and there). I understand python manage.py migrate will handle the creation of Django-specific models but does not actually create any migration files? Some sources indicate the first migration file should be run with --fake so it's not applied. Will the next migration files remember to run the first one as fake and only apply the next ones? -
TemplateSyntaxError - Invalid filter: 'translate'
In my angularJs application, with django backend, I'm using angular-translate to handle multilingual work. It is working fine for AngularJs (html and controller) files, but for login file, that is rendering as template from django, it is giving exception TemplateSyntaxError at /login Invalid filter: 'translate' Here is exception detail; This is html where I'm trying to use translate Username key is defined in related language json file, that is referenced in configuration file of loginApp like this; angular.module('loginApp') .factory("asyncLoader", asyncLoader) .config(config); config.$inject = ['$translateProvider']; function config($translateProvider) { $translateProvider.fallbackLanguage('en'); $translateProvider.useLoader('asyncLoader'); } asyncLoader.$inject = ['$q', '$timeout', '$http']; function asyncLoader($q, $timeout, $http) { return function(options){ var defferred = $q.defer(), translations; var resturl = "static/loginApp/lang" + options.key + ".json"; $http.get(resturl, {cache:false}).success(function(translations) { defferred.resolve(translations); }).error(function(translations){ defferred.reject(translations); }); $timeout(function (){ defferred.resolve(translations); },2000); return defferred.promise; }; } This whole setting is working file with login controller file, but when I use it in html, it throws template rendering error. this is how I'm rendering login.html' as template in my django appviews.py` def LoginTemplate(request): return HttpResponse(get_template('login.html').render()) I don't know what I'm missing, Any kind of help will be appreciated. -
Why does gettatr transform a boolean into a string?
I have a model with a boolean field: @python_2_unicode_compatible class Invoice(models.Model): ... is_paid = models.BooleanField(default=False) ... def __init__(self, *args, **kwargs): super(Invoice, self).__init__(*args, **kwargs) self.__tracked_fields = ['is_paid'] for field in self.__tracked_fields: setattr(self, '__original_%s' % field, getattr(self, field)) I'm trying to track the change in this field before saving: def set_original_values(self): for field in self.__tracked_fields: original = '__original_%s' % field original_value = getattr(self, original) setattr(self, field, original_value) return self.__dict__ def has_changed(self): for field in self.__tracked_fields: original = '__original_%s' % field if getattr(self, original) != getattr(self, field): return True return False def save(self, *args, **kwargs): self.full_clean() if self.has_changed(): if not self.can_be_confirmed(): self.set_original_values() return super(Invoice, self).save(*args, **kwargs) But when testing, I get specific results. self.assertFalse(self.invoice.is_paid) AssertionError: 'False' is not false And if I try to check the type after getattr, I get the result: <class 'str'> What could be the problem? -
date picker not supporting in django template table column
date picker for form field , placed in an template was not supporting.. Here's the code forms.py: class GuestFacultyCourseOfferForm(BaseGuestFacultyCourseOfferForm): teaching_mode = forms.ModelChoiceField(queryset=TeachingMode.objects.all()) location_mode = forms.ModelChoiceField(queryset=LocationMode.objects.all()) # class_start_date = forms.DateField(required=True,) classstartdate = forms.DateField(label='Date',required=True) template code: This is the script code for date picker which was given for form field "classstartdate". <script type="text/javascript" src="{% url 'admin:jsi18n' %}"></script> <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css"> <script type="text/javascript" src="{% static 'admin/js/jquery-new.js' %}"></script> <script type="text/javascript" src="{% static 'admin/js/jquery-ui.min.js' %}"></script> <script type="text/javascript" src="{% static 'admin/js/jquery-validate.js' %}"></script> <script> $(document).ready(function() { $( "#id_classstartdate" ).datepicker({ changeMonth: true, changeYear: true, minDate:0, buttonImage: "{% static "admin/img/icon_calendar.gif" %}", buttonImageOnly: true, buttonText: "Select date", showOn:"both", }); }); </script> --> this is body code where i have given form fields in table: <form method="post"> {% csrf_token %} <table id="formset" class="form"> <thead> <tr> <th>TEACHING MODE</th> <th>LOCATION MODE</th> <th>CLASS START DATE</th> </tr> </thead> {% for form in formset_assign_faculty.forms %} <tr class="{% cycle row1,row2 %}"> <td>{{ form.teaching_mode}} {{ form.teaching_mode.errors.as_ul }}</td> <td>{{ form.location_mode}} {{ form.location_mode.errors.as_ul }}</td> <td>{{ form.classstartdate}} {{ form.location_mode.errors.as_ul }}</td> </tr> {% endfor %} </table> </form> -
Django nested serializer not serializing inner model
im trying to add a custom action to my ViewSet in Django2, using django-rest-framework. Problem is that my serializer is not serializing nested model and thus giving me error: { "labels": [ { "non_field_errors": [ "Invalid data. Expected a dictionary, but got Label." ] }, { "non_field_errors": [ "Invalid data. Expected a dictionary, but got Label." ] } ] } I have two models which have M:N relationship. Label model: class Label(models.Model): name = models.CharField(max_length=30, help_text='Name of Label') desc = models.CharField(max_length=200, help_text='Description of Label') def __str__(self): return self.name LabelSet model: class LabelSet(models.Model): labels = models.ManyToManyField(Label, blank=True, help_text='ManyToMany field of corresponding labels') name = models.CharField(max_length=30, help_text='Name of Label Set') desc = models.CharField(max_length=200, help_text='Description of Label Set') def __str__(self): return self.name Machine Model: class Machine(models.Model): name = models.CharField(max_length=30, help_text='Name of machine') desc = models.CharField(max_length=200, help_text='Description of machine') location = models.ForeignKey(Location, null=True, blank=True, on_delete=models.CASCADE, help_text='ID of machine location') labelset = models.ForeignKey(LabelSet, null=True, blank=True, on_delete=models.DO_NOTHING, help_text='ID of set of labels relevant for this machine') def __str__(self): return self.name Serializers: class LabelSerializer(serializers.ModelSerializer): class Meta: model = Label fields = '__all__' class LabelSetSerializer(serializers.ModelSerializer): qs = Label.objects.all().values() labels = LabelSerializer(qs, many=True) class Meta: depth = 1 model = LabelSet fields = ('name', 'desc', 'labels') Custom action in … -
Merge two/objects querysets with Django
I have the following piece of code. I'm using it to return json so Datatables can render it. I pass in query parameters. def map_query(type_, type_model, type_pk, query_data, request): type_results_query = None problem_data = get_model_query_data(query_data, Problem) problems_filtered = Problem.objects.filter(**problem_data) if request.POST: model_query_data = get_model_query_data(query_data, type_model) type_results_query = Chgbk.objects.filter(**model_query_data) print(type_results_query) return type_results_query So type_results_query returns data I want. But Problem model has a foreign key on it which links to key on table. I want to get the data from the Problem table into the Chgbk query as well, sort of the two objects merged but I cannot figure out how to do this and it is driving me crazy. -
django start server error with title auth_group' doesn't exist
guys i puled my project from github and i installed all required packages but after makemigrations or runserver commands i get error like below. tying to comment 'social_auth' and social_django ... and command like python3 manage.py migrate --fake myprojectname zero or python3 manage.py migrate --fake social_auth zero or reinstalling packages dont work for me any idea??? error : ..... ...... db.query(q) File "/home/mohammadreza/www/html/academy/uenv/lib/python3.6/site-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1146, "Table 'academy.auth_group' doesn't exist") this is installed app INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework_jwt', 'rest_framework.authtoken', 'social_django', 'rest_social_auth', 'api.v1.blog', 'api.v1.store', 'api.v1.accounts', 'api.v1.manager', ] requirment file: amqp==2.2.2 appdirs==1.4.3 asn1crypto==0.24.0 billiard==3.5.0.3 cached-property==1.3.1 celery==4.1.0 certifi==2018.1.18 cffi==1.11.5 chardet==3.0.4 cryptography==2.1.4 cycler==0.10.0 defusedxml==0.5.0 Django==2.0.4 django-braces==1.12.0 django-cors-headers==2.1.0 django-filter==1.1.0 django-ranged-response==0.2.0 django-redis==4.9.0 djangorestframework==3.7.7 djangorestframework-jwt==1.11.0 gevent==1.2.2 greenlet==0.4.13 gunicorn==19.7.1 idna==2.6 isodate==0.6.0 kiwisolver==1.0.1 kombu==4.1.0 lxml==4.1.1 Markdown==2.6.11 matplotlib==2.2.2 mysqlclient==1.3.12 numpy==1.14.2 oauthlib==2.0.7 olefile==0.45.1 opencv-python==3.4.0.12 Pillow==4.1.1 pycparser==2.18 PyJWT==1.5.3 pyparsing==2.2.0 pytesseract==0.2.0 python-dateutil==2.7.2 python-memcached==1.59 python3-openid==3.1.0 pytz==2017.3 redis==2.10.6 requests==2.18.4 requests-oauthlib==0.8.0 requests-toolbelt==0.8.0 rest-social-auth==1.2.0 six==1.11.0 social-auth-app-django==1.2.0 social-auth-core==1.7.0 urllib3==1.22 vine==1.1.4 whitenoise==3.3.1 zeep==2.5.0 -
Django DoesNotExist at /admin/login/ while working with Django forms-builder
I was using my http://localhost:8000/admin perfectly before but then I installed django-forms-builder package and created a form. Since then I was getting this error while trying to access /admin. DoesNotExist at /admin/login/ Site matching query does not exist. Then I opened setting.py and set SITE_ID = 1. This fixed the /admin problem but now when I go to http://localhost:8000/forms/test it says Now when I comment the SITE_ID=1 in settings.py this forms works normally but then I can't access /admin. Please guide me where I am making trouble? -
unable to access Django server running on ubuntu instance AWS
I have Django project running on AWS with following configuration ALLOWED_HOSTS = ['*'] python manage.py runserver 0.0.0.0:8000 aws security group configured to TCP 8000 to allow access from anywhere but am getting timeout when i access server using public ip xxx.xxx.xxx:8000 even tried with public dns but not connecting to django.when i check netstat its fine tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN i tried after allowing port but no succcess sudo ufw allow 8000 when i validate with port checker for xxx.xxx.xxx:8000 is seems to be open but curiously my apache2 at 80 is accessible using ip address -
Django. Modal in another modal
Hi I have problem with modal in bootstrap 4 in django 2.03. I want to open modal (to create new object) in another modal(with list of this objects), and after closing the second modal i need to reload content in the first one. For now i can only open second modal and after close it i closing first one. Also after create object, modal is redirect to new page with object, not to the previous modal. Base template fragment: <a class="btn btn-primary btn-sm" id="modal1" onclick="abrir_modal('{% url 'Project:MilestoneDictionaryListView' %}')" data-toggle="modal" data-model-name="#Modal" style="color: white"> Add milestone</a> {% include 'modal.html' %} Modal.html: <div class="modal" id="Modal" tabindex="-1" role="dialog"></div> <script> function abrir_modal(url) { $('#Modal').load(url, function () { $(this).modal('show'); }); return false; } function hide_modal() { $('#Modal').modal('hide'); return false; } </script> First modal content <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h3>Select milestone</h3> </div> <a class="btn btn-primary btn-sm" id="modal1" onclick="abrir_modal('{% url 'Project:MilestoneDictionaryCreateView' %}')" data-toggle="modal" data-model-name="#Modal" style="color: white">New milestone</a> <div class="modal-body"> <!-- milestone table--> <div class="table-condensed table-sm "> <table class="table "> <thead style="background-color: #f8f9fa"> <tr> <th>Name</th> <th>Customer name</th> <th>Type</th> <th>Status</th> <th></th> </tr> </thead> <tbody> {% for p in milestone_dictionary_form %} <tr> <td>{{ p.name }}</td> <td>{{ p.description }}</td> <td>type</td> <td>{{ p.get_status_display }}</td> <td><a href="" class="btn btn-primary btn-sm" style="color: … -
Upload and Process the json file at run time in django
I'm newbie to django.I want to upload json file on in UI and process that json file on run time(i.e without storing it on database).For that I have created an upload form.Now I want process the json. So how can I access that json file? -
uploading files using FormData ajax jquery, formData not able to get any data
I have been trying to get this thing work for days now but have not been able to. The ajax call I have- $('#form-submit').click(function() { // Disabling buttons while processing form $('#form-submit').prop('disabled', true); $('#form-cancel').prop('disabled', true); var form = $(this).parent().parent(); var formData = new FormData(form); for (var pair of formData) { console.log(pair[0]+ ', ' + pair[1]); } $.ajax({ url: "", type: "POST", data: formData, dataType: "json", cache: false, contentType: false, processData: false, async: false, success: function(data) { if (!(data['success'])) { // Replace form data $('#{% if not form_id %}form-modal{% else %}{{ form_id }}{% endif %}-body').html(data['form_html']); $('#form-submit').prop('disabled', false); $('#form-cancel').prop('disabled', false); $(window).trigger('init-autocomplete'); } else { alertbox('Form saved', '', 'success'); $('#form-submit').prop('disabled', false); $('#form-cancel').prop('disabled', false); setTimeout(function () { location.reload(); }, 2000); } }, error: function (request, status, error) { alertbox('AJAX Error:', error, 'danger'); } }); Have tried each and every combination listed online- not working :( The request payload thing in the networks tab under chrome tools is empty with just ------WebKitFormBoundaryAhVaAGAzEEjzPkQY If I put data:form.serialize(); it works but the file upload doesn't. -
Custom middleware returning redirect loop
I have referred to the code shared on this website http://onecreativeblog.com/post/59051248/django-login-required-middleware to make a login required middleware. import re from django.conf import settings from django.urls import reverse from django.shortcuts import redirect from django.contrib.auth import logout EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') path = request.path_info.lstrip('/') if not request.user.is_authenticated(): if not any(url.match(path) for url in EXEMPT_URLS): return redirect(settings.LOGIN_URL) I have looked into stackoverflow and tried almost every solution but in vain. Settings url LOGIN_REDIRECT_URL='/blog/index/' LOGIN_EXEMPT_URLS= ( r'^blog/signup/$', r'^blog/logout/$', ) Any help would be appreciated! Thanks in advance.