Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
jQuery parents() selector failing
I have an anchor, and I have attached an onClick callback to it, so once it is clicked, an AJAX request is fired which calls a view that deletes the image from the database. It should also remove <div class="image-preview"> altogether, too, however that is not happening for some reason. When I tested div removal code in JSFiddle, it works. The image is successfully getting removed from the database and delete_view is involved in the process. I have also tried to console.log from inside the success callback and I can see a debug message. console.log($(this).parents('.image-preview')); returns Object { length: 0, prevObject: Object(1) }, thus I think the selector is failing. What could be the reason? HTML: <div id="information"> <div class="image-previews"> <div class="image-preview"> <img src="/media/tmp/None/IMG_20190507_144128.jpg" width="80" height="54"> <p><a id="115" class="delete-temp-image-link">delete</a></p> <label><input type="radio" name="main" value="IMG_20190507_144128.jpg">main</label> </div> </div> <div id="div0"> <div>Name: IMG_20190507_144128.jpg</div> <div>Size: 3.03MB</div> <div>Type: image/jpeg</div> <div class="progressNumber">100%</div> </div> </div> jQuery: var $deleteClicked = function(event) { var url = Urls.deleteTempImage(event.target.id); $.ajax({ url: url, data: { 'id': event.target.id }, success: function (data) { console.log('spam'); $(this).parents('.image-preview').remove(); } }); } $(document).on('click', '.delete-temp-image-link', $deleteClicked); view: def delete_view(request, id): img = get_object_or_404(TemporaryImage, id=id) img.delete() return HttpResponse('successfull') -
Choice field in Django registration forms look inactive, but works
So the thing is that I added custom user model models.py class CustomUserModel(AbstractUser): pass Morasko = "Morasko" Piatkowo = "Piątkowo" district_choices = [ (Morasko, "Morasko"), (Piatkowo, "Piątkowo"), ] district = models.CharField(max_length=15, choices=district_choices, default=district_choices[0]) Field 'district' is supposed to be a choice field with two options. Here is custom registration form I am using. forms.py class NewUserForm(UserCreationForm): district = forms.ChoiceField(widget=forms.RadioSelect, choices=CustomUserModel.district_choices) class Meta(UserCreationForm): model = CustomUserModel fields = ('username', 'email', 'district', 'password1', 'password2') def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.district = self.cleaned_data['district'] if commit: user.save() return user My html registration file: register.html {% extends "map_neigh/home.html" %} {% block content %} <div class='container'> <div id='inner'> <br> <form method="POST"> {% csrf_token %} {{form.as_p}} <button class="btn btn-primary" type="submit">Register</button> </form> <br> <br> If you already have an account <a href="/login"><strong>log in.</strong></a> </div> </div> {% endblock %} Choice field actually works - users are saved in DB with clicked district, but it looks inactive and I have no clue why. Clicking it doesn't change the appearance, if I hove over one of options pointer doesn't change neither. Below screenshot of the registration form. -
django spotify api python http post 500 error
Hello I am trying to make a django website using the spotify api, so I am trying to get some simple example code working using the spotipy python library, but keep getting a http post 500 whenever my spotipy code is called. Right now if you click a button on the website it makes a post request to one of my endpoints, which calls a python function and is supposed to return text. This is the code in the python function: import spotipy def spotifyleastplayed_py(request): print("spotifyleastplayed_py()") if request.method == 'POST': print("0") sp = spotipy.Spotify() print("1") results = sp.search(q='weezer', limit=20) print("2") print(results) data = "temp spotifyleastplayed_py() Return Data" return HttpResponse(data) #HttpResponse(json.dumps("{test:bobo}")) When the function is called, my console outputs the following error message: [06/Oct/2019 21:49:03] "GET /spotifyleastplayed HTTP/1.1" 200 1992 spotifyleastplayed_py() 0 1 [06/Oct/2019 21:49:07] "POST /spotifyleastplayed_py/ HTTP/1.1" 500 6326 Do I need to add the spotipy url to django somewhere so the library can make calls successfully? It seems like its failing to make the http request to spotipy. -
Django: want to loop through _set for pk values only
I'm stuck trying to figure out how to filter my template values with the detail view PK. I have a detail view for my employee. I wish to display my employee's subjects, where I then wish to filter the subjects with the evaluations that have been made for the subject. I've gotten so far that I can show my subject names, and show all the evaluations for each subject. However, I don't want to show ALL of them I only want to show the ones that exist for the current employee (detailView PK). As you can see in my template, I'm using _set to make the relation, but I have no clue on how to filter the PK into that equation. Example, what I want: Subject 1: Evaluationname - employee Johnny Evaluationname - employee Johnny Example, what I currently have: Subject 1: Evaluationname - employee Johnny Evaluationname - employee Chris I don't want Chris's evaluation, I only wish to filter the primary key, so in this case Johnny's evaluations. Template {% for subject in subject_list %} <a href="">{{ subject.subejctname }}</a> {% for evaluation in subject.evaluation_set.all %} <div> <p>{{ evaluering.ma }} | {{ evaluering.ma.firstname }} | {{ evaluering.ma.lastname }}</p> </div> {% … -
Recommended C-panel for hosting django web application
So my goal is to run django app(WSGI) on C-panel, my traffic would be 100-200 persons max per day ,I have found a website https://ifastnet.com but I'm not quite sure, what would you recommend? -
Unable to convert bytes stream into image django views
this is a new question as i didn't received any answer to my old one, i have made some tests after some recommendations I am actually struggling on converting a bytes received from LDAP for the thumbnail picture of the user and saving it into the profile model, This is the code that i have actually xuser = CustomUser.objects.filter(id=request.user.id).first() user = xuser.last_name def save_avatar(user, thumbnail): profile=UserProfile.objects.create(user=user) buffer = io.BytesIO() buffer.write(thumbnail) image_file = InMemoryUploadedFile(buffer, None, 'test.png', 'image/png', buffer.getbuffer().nbytes, None) profile.image.save('image', image_file) try: thumbnail = result[0][1]['thumbnailPhoto'][0] save_avatar(user, thumbnail) print('* %s: %d' % (xuser.username, len(thumbnail))) except Exception as e: print(' %s: error: %s' % (xuser.username, str(e))) With this am able to store the image but i have as name only 'image' without the extension i don't know what i have to do next, and if this code should give me something back, if this will help this the format that i have after retrieving the value of the thumbnail attribute: b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12\x13\x0f\x14\x1d\x1a\x1f\x1e\x1d\x1a\x1c\x1c $.\' ",#\x1c\x1c(7),01444\x1f\'9=82<.342\xff\xdb\x00C\x01\t\t\t\x0c\x0b\x0c\x18\r\r\x182!\x1c!22222222222222222222222222222222222222222222222222\xff\xc0\x00\x11\x08\x00`\x00`\x03\x01!\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1c\x00\x00\x01\x04\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x01\x03\x06\x07\x00\x04\x05\x08\xff\xc4\x00:\x10\x00\x01\x03\x03\x02\x03\x05\x06\x04\x03\t\x00\x00\x00\x00\x00\x01\x00\x02\x03\x04\x05\x11\x06!\x121a\x07\x14AQq\x13"2\x81\xa1\xc1#BR\x91\x15$r5C\x82\xa2\xb1\xb2\xc2\xd1\xe1\xff\xc4\x00\x19\x01\x00\x02\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x05\x04\xff\xc4\x00\x1d\x11\x01\x01\x01\x00\x03\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x11!\x12"1\xff\xda\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00\xb3\x02 \x10\x04\x02\\&E\xc2\xcc 3\t0\x80B\x85\x00$ !\x00\xe0\x08\xc0H\xca\x02,&LP\xbb\xd6\xbem1\x11Y-\xf2\\\xe4$\x83)\xcb"\x1e\x87\x9b\xbdF\xddTu\xb9\x99\xedO\x18\xbb\xbeCt\x1a\xf2\xae9\xf8/\xd6gQ\xc3\x8c\x9a\x9aw\x99X\xde\xaen2\x07Q\x9c)\xa43ES\x04s\xc1#%\x86F\x871\xec9\x0e\x07\x91\x05,o;\x9e\xc1\xbe=b\xf9DP\xa9\xa0\x12\x84\x84\x19\xc0\x11\x00\x90\x10\x08\xb0\x99!z\xf6\xe9$r[\xec\xac\xda*\xde9*\x1c\x0e\t\x8d\x98\xf7=\x1cy\xf4\x18\xf1Z\xf6\xc0\xc7G\x82\xdc\x11\xcb\x03\x92\xcf\xed_w#C\xa9\x9f1i\xcb\x88\x02"Z\xd3\x9f4\xc6\x85\xac}%\xe2\xba\xccO\xf2\xcfgz\xa6g\x83\x0eq#GL\x90q\xea\x8e\xad\xf3~\x1fk>\xe3\xd4\xf0\xa1!h3\x82P\x90\x80p\x04a \x12\xa6\x15\xce\xb9"MM\x03\xa2s^\xf8h\xdc\xc2?C\x8b\xb3\xbf\xa8!E(\xefwjz\xa6\x96T\xcb;G\xc6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d2\x05y\xdb\xb4\xdb\xa9\xb9\xeb\x8a\xe0\x1f\x98\xa9qM\x1f\x90\xe1\x1b\xff\x00\x98\x94\x12\x1aJ \x80U/\xd2u\xfct\xaf\xa4q\xf7\xa2<M\xfe\x93\xff\x00G\xfdU=\x89\xee\x17p_6\x91\xf1\x90@U\xe5\xfa\xaf\xbd\xdd\xe7~r\xd6\x1e\x00}?\xf7+\x9f\xad?\xabWv/\xf3\xe3\x96P\xb8\xec\xbb\x9c`\xe2\xdf*\xe9\xecr\xf6\xea\x9bMe\x9eW\x12\xeaG\tb\xcf\xe8q\xdc|\x9d\xbf\xf8\x928\xb5f\x98S\xc1$\xee\xf8bay\xf4\x03?e\xe4\xea\xaa\x87\xd5\xd4\xcbS!\xcb\xe6{\xa4q\xea\xe3\x9f\xbad\xd6;\x10\x8c\x14\x02\xe7e\xb9j\xac\xee7(f\xce\x1a\x1d\x87\x7fI\xe6\x96\xe7\xb9\xb0\xf3|\xb2\xa6\xd7*\xf6\xd1\xdb$\xa8\x0e\x04\xb5\x98oW\x1eJ\xba.$\xe4\x9c\x9f5\xcf\xd6\x9eKW\xf6/\xd9\x02J\x07\xbbb\xba\x1c\xe1iS\x8e\xca\xae]\xc7[S\xc2\xe3\x86VF\xf8\x0f\xae8\x9b\xf5o\xd5\x06\xbf\xae\xbb\xd9\xab\xc7\x9d4\xbf\xec+\xca \xfb\xad\xf4\t\x90\x1epr\x94 \x0b)\t@oT\xdd%\xaa\xb5\xc1L\xec\xfe\x13\x8f\x11\xf3\x1e\x0b\x9e\xa3\x9c\xfeg\x89k_\xab\xe8JnC\xb2h\xb1\xab\xa1e\xac4\x17\xcb}Xw\x0f\xb0\xa9\x8eL\xf9\x00\xe1\x9f\xa2\r\xff\xd9' i really need some help with this if anyone have a suggestion or something from what i can start i will be really grateful -
why my "def __str__(self)" function isn't working in django
from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) ***def __str__(self): return self.title***[(InteractiveConsole)[1] when i enter Article.objects.all() this line, after that it should show titles i have in my database. But why it's just showing ? although I have written def __str__(self): properly. -
how to configure redirect in DeleteView
when i try to delete some comment it first take me to the comment_delete_confirm.html, then redirect to the page what linked in success_url = '/blog/'. Problem become when i change success_url to something like 'post-detail' (becose i want after comment_delete_confirm return to the post), it cannot find this page, becose in the brauser url it looks like that: '127.0.0.1:8000/blog/post/18/comment_delete/post-detail' this is my views.py and urls.py files: class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment success_url = 'post-detail' # only the author can delete his post # if not author try to delete post it gives 403 forbidden def test_func(self): comment = self.get_object() if self.request.user == comment.user: return True return False urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('post/<int:pk>/comment/', add_comment, name='comment-create'), path('post/<int:pk>/comment_update/', comment_update, name='comment-update'), path('post/<int:pk>/comment_delete/', CommentDeleteView.as_view(), name='comment-delete') ] -
Nginx + Django serve static files to local location
I have a Django app and I want to set the path of static files, to a local path, for example: c:/static/test The Nginx settings for the location is something like: server { listen 80; server_name sitename or ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/blah/blah_blah; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } is it ok to replace root /home/blah/blah_blah; with c:/static/test? To make it clear, I have a website that I want to upload big files to a local server (local path in the user's PC). Thanks -
What is an equivalent Django's save function in Symfony?
What is an equivalent Python's save function in Symfony models?. Django def save(self, *args, **kwargs) self.slug_field = slugify(instance.username) What would it look in Symfony? -
Transpose data from model objects for django-datatables-view
I have data in the following (simplified) format: MetricData(models.Model) with following fields: id, metric, date, facility, value Now I want to create a table with the following format (execute the script to get the indented output table): <table style="width:100%"> <tr> <th>Date</th> <th>Facility 1</th> <th>Facility 2</th> <th>Facility 3</th> </tr> <tr> <td>03/2019</td> <td>1.0</td> <td>1.5</td> <td>2.5</td> </tr> <tr> <td>04/2019</td> <td>1.5</td> <td>1.5</td> <td>2.0</td> </tr> </table> As you can see, the number of facilities which is dynamic (new ones can be added to the database), are the column headers. For each facility there will be metric data in the database. All examples from django-datatables-view I find are basically using models directly and one model entry is converted to one table row. -
Django - Multiple dependent form
I have extended the Django User model creating a 1-to-1 dependency with the class Profile. There will be many profiles playing in the same Community. And a Profile can be playing in different Communities at the same time. I did this with a Many-to-Many field "members" in the Community Model. This is shown below. (I have reduced the irrelevant code) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Extend Users Here class Community(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=50) members = models.ManyToManyField(Profile, through='Membership') def get_members(self): return "\n".join([str(m) for m in self.members.all()]) class Membership(models.Model): community = models.ForeignKey(Community, on_delete=models.CASCADE) player = models.ForeignKey(Profile, on_delete=models.CASCADE) When a new profile is created I would like it to be inmediately associated with a Community. Therefore, in the user registration form I would like to ask him if he wants to join an existing community or create a new one. I believe I need something as "Multiple Form" but I would appreciate help in what exactly do I need and how I can look for information about it. Thanks! -
Import another javascript module in django admin custom javascript file
I have created a separate JavaScript file to wrap common Ajax code (jQuery) and import it in other JavaScript files. But it gives the error SyntaxError: import declarations may only appear at top level of a module. My code as follows. Two files are in the same directory. ajax_call.js function make_ajax_request(requestUrl, requestData, callback_function) { $.ajax({ type: 'GET', url: requestUrl, data: requestData, success: function(response) { try { var jData = JSON.parse(response); if (jData['status'] == 'success') { callback_function(jData); } else { console.log(jData['error']); } } catch (error) { console.log('Parse error in response.') } } }); } change.js import { make_ajax_request } from './ajax_call.js' var $ = django.jQuery; $(document).ready(function() { //code to call the function } admin.py class Media: js = ('admin/js/jquery.init.js', 'js/admin/ajax_call.js', 'js/admin/change.js',) -
Python django authenticate delete
I'm having some problems with the delete method on my project. When I run on postman link to delete the post, it's deleting it, so it works, but I want to make it only if user is_staff to delete this post. This is the code. from django.db import models from django.utils.text import Truncator from django.contrib.auth.models import User from threads.models import Thread class Post(models.Model): """ Model to represent the post in a thread """ content = models.TextField() thread = models.ForeignKey( Thread, on_delete=models.CASCADE, related_name='posts' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name='posts' ) class Meta: ordering = ['created_at'] def __str__(self): truncated_content = Truncator(self.content) return truncated_content.chars(30) -
python django django.shortcuts render is searching for html in wrong directory
For me django.shortcuts render is searching for html in wrong directory: C:\Users\benra\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\blog\home.html but it should be searching for it where the project is C:\Users\benra\django_project\blog\templates\blog how do I fix this? from django.shortcuts import render def home(request): return render(request, 'blog/home.html') def about(request): return render(request, 'blog/about.html') -
How can solve this : Django pyinstaller wont start app exe
i have install python v 3.4 and django 1.8 , pyinstaller 3.5, i try convert django app to app.exe for windows. pyinstaller --name=mysite mysite/manage.py All ok. ./dist/mysite/mysite.exe runserver localhost:8000 server start ok, but wont start app.exe window. any solution? -
Could anyone please write the code in django to get a csv file as an input from user and then displaying number of rows and columns in it [on hold]
Please help me with the contents of template,views, URL(outer and inner) file. I just want to create a simple web application in django where i get a user input in the form of a csv file(I also want to put a check so that the file should only be a .csv) and then simply displaying the number of rows and columns in that file to the user. Thank you in advance. -
Reward Points to Currency Conversion
I am currently building a Django app where a user gets a point referrals. And these points could be converted to "real" money which can later be used for "shopping" real items on specific stores BUT cannot be withdrawn as cash. My problem is the conversion part of the points. For example: the equivalent of 1 point is $30. I am really new to these kinds of applications and also new in using python so please bear with me. How should I approach this then? Should I store the $30 to a "wallet" in my database after it was converted? Or should I use a 3rd party to process the conversion and the payment of the users whenever they use the "money" to shop? I am open to any suggestions besides these things that I have in mind. And honestly, I barely have enough knowledge to execute these things, but I am currently studying it. Your inputs will help a lot. Thank you. -
Django Error: "You are trying to add a non-nullable field 'author' to entry without a default"
I was trying to make migrations after adding an author field in my models.py file but Django asked me this: You are trying to add a non-nullable field 'author' to entry without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py My Models.py File: from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User class Entry(models.Model): title = models.CharField(max_length=50, default=timezone.now) date = models.DateTimeField(default=timezone.now) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('diary:index') def __str__(self): return self.title I wanted to add the user who's currently active as the author, so I did this on my views.py file: class EntryCreate(CreateView): model = Entry fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.author return super().form_valid(form) What Should I Do To Avoid This? Thanks In Advance! -
Trouble getting the localhost using webdriver selenium 3.141.0 for firefox 69.0.1
I'm trying to test my django application using selenium and Mozilla Firefox 69.0.1 on Ubuntu 16.04, but I get an error message: "selenium.common.exceptions.WebDriverException: Message: Reached error page". It seems like Firefox cannot establish a connection to the server 127.0.0.1:8000. I built a virtual environment where everything is installed (python 3.5.2, django 2.2.6, selenium 3.141.0, urllib3 1.25.6, etc.). I downloaded geckodriver 0.25.0, which is installed in /usr/local/bin/. I ran the following code: from selenium import webdriver browser = webdriver.Firefox() browser.implicitly_wait(10) browser.get("http://127.0.0.1:8000") browser.quit() I also tried: from selenium import webdriver firefox_capabilities = DesiredCapabilities.FIREFOX firefox_capabilities["marionette"] = True browser = webdriver.Firefox(executable_path="/usr/local/bin/geckodriver", capabilities=firefox_capabilities) browser.implicitly_wait(10) browser.get("http://127.0.0.1:8000") browser.quit() But it did not work. The first piece of code works when I use "https://www.python.org/" instead. I suppose there is a problem with the local host, but I cannot figure out what is wrong though. -
Ouput ping status on django template
I have a model that contains domain names which I need to ping. I was able to create the view but I couldn't figure out how to output it on the template. def pingDomain(request, page): domain = Table.objects.filter(page) try: subprocess.check_call(['ping', '-c', '1', "domain"]) except subprocess.CalledProcessError: host_online = False else: host_online = True context = { 'online': host_online } return render(request, 'home.html') the model class Table(models.Model): page = models.URLField(verbose_name=None) and this is how I call it on the template {{t.page.status.url}} Can anyone guide me? -
Getting error response in ajax from my Django view
i am getting the error in ajax from my view in Django and I cannot figure out why : // AJAX GET $(document).ready(function(){ // AJAX GET $('#btnx').click(function(){ console.log('start'); $.ajax({ type:"GET", url:"profile_bit", dataType:"json", data: {'counter': 'counter'}, success: function(data) { console.log('ok')}, error: function(data){ console.log('why?') // << I keep getting this }}) }) }); // django view , my url is all good too def profile_bit(request): if request.is_ajax(): data ={ 'key': 'value', } return HttpResponse(json.dumps(data), content_type='application/json') else: return Http404 I would like to get a success response so I could just continue to work with my DB. Thx so much -
OperationalError at /add-to-cart/test-product-4/ table core_order has no column named shipping_address_id
after i changed class BillingAddress To class Address. and tried these stages Deleted all the migration records from your app's migration directory. Also Deleted the db.sqlite3 file. And Then, I did following commands python manage.py makemigrations core python manage.py migrate After migrated, Instead of showing data inserted ,it is shown No migrations to apply. in Terminal PS C:\Users\Dell\project5> python manage.py makemigrations core Migrations for 'core': core\migrations\0001_initial.py - Create model Address - Create model Coupon - Create model Item - Create model Order - Create model Refund - Create model Payment - Create model OrderItem - Add field items to order - Add field payment to order - Add field shipping_address to order - Add field user to order PS C:\Users\Dell\project5> python manage.py migrate Operations to perform: Apply all migrations: account, admin, auth, contenttypes, core, sessions, sites, socialaccount Running migrations: No migrations to apply. PS C:\Users\Dell\project5> when i click add to cart button, it shown error as OperationalError at /add-to-cart/test-product-4/ table core_order has no column named shipping_address_id -
request.FILES is empty
I have a form with an <input type="file"> for selecting images to upload, and once upload button is clicked, a POST XMLHttpRequest is sent which calls the upload_view that should save the images on the server. However, my request.FILES is empty for some reason. When I console.log(document.getElementById('fileToUpload').files I can see the files there. And my request.POST looks like this: <QueryDict: {'fileToUpload': ['[object FileList]'], 'csrfmiddlewaretoken': ['bOjUFzTnMVbHOWOQURj2egJuRizsVJIBMSfQra4yuz7MX3DOEaRPHbMVnY8xyIsU']}> My view: def upload_view(request): key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}' for file in request.FILES.getlist('fileToUpload'): TemporaryImage.objects.create(image=file, key=key) return HttpResponse('complete') My JS: function uploadFile() { var fd = new FormData(); fd.append("fileToUpload", document.getElementById('fileToUpload').files); var value = []; document.getElementsByName('csrfmiddlewaretoken').forEach(function(x) { value.push(x.value); }) fd.append('csrfmiddlewaretoken', value[0]); var xhr = new XMLHttpRequest(); xhr.open("POST", Urls['upload-view']()); xhr.send(fd); } My form: <form id="form1" enctype="multipart/form-data" method="post"> {% csrf_token %} <label for="fileToUpload">Select a File to Upload</label> <input type="file" multiple="multiple" name="fileToUpload" id="fileToUpload"> <input type="button" onclick="uploadFile()" value="Upload"> </form> -
Custom 500 error getting blank page sometimes
When I try to test the custom 500 error page. If the test works, the I get a blank page with nothing on it ("Internal Server Error") in my error logs. If an error occurs, I get custom error page. In views: def handler500(request): response = render_to_response("errors/500.html") response.status_code = 500 return response def my_test_500_view(request): # Return an "Internal Server Error" 500 response code. return HttpResponse(status=500) In Urls.py: my path is : path('test500/', views.my_test_500_view, name='test500') Also: handler500 = 'myapp.views.handler500' If I actually create an error like by removing the import line for the HttpResponse from the my_test_500_view above, the custom 500 error page actually loads and I get this error on the server, i.e. the actual error. NameError: name 'HttpResponse' is not defined What's wrong with my test that it returns a blank page. Is my 500 page actually working? I think it's not working right, since I got a email warning from google search about failure of 500 error page and I often get this error: TypeError: view must be a callable or a list/tuple in the case of include(). Please help, what's going on.