Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Template Form Fields show in a Disorder way
I am working on Django Form so basically I have four form fields like: First Name: Last Name: Address: Contact Info: this form data came into Django Template and Render but display these field not in proper order. Every time I refresh page form field order changes. Example: On first page load its like Last Name: First Name: Contact Info: Address: On Refreshing the page order changes like Address: Last Name: Contact Info: First Name: here is my Django template form code which render the form in Tempalte: {% for fields in formset %} <div class="row"> <div class="col-md-12"> <label class="col-4 control-label">{{fields.label}} </label> {{fields}} </div> </div> {% endfor %} But I want to Display these fields in proper Order. First Name: Last Name: Address: Contact Info: -
ImportError: cannot import name 'hex_regex'
I'm working on adding django-location-field. However when I add the following code from django.contrib.gis.geos import Point from location_field.models.spatial import LocationField address = map_fields.AddressField(max_length=200, blank=True) location = LocationField(based_fields=['city'], zoom=7, default=Point(1.0, 1.0)) the same as it's ReadMe tutorial it throws an error python3 manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7efbe781bd90> Traceback (most recent call last): ... from django.contrib.gis import gdal File "/home/samuel/.local/lib/python3.6/site-packages/django/contrib/gis/gdal/__init__.py", line 28, in <module> from django.contrib.gis.gdal.datasource import DataSource File "/home/samuel/.local/lib/python3.6/site-packages/django/contrib/gis/gdal/datasource.py", line 41, in <module> from django.contrib.gis.gdal.layer import Layer File "/home/samuel/.local/lib/python3.6/site-packages/django/contrib/gis/gdal/layer.py", line 6, in <module> from django.contrib.gis.gdal.feature import Feature File "/home/samuel/.local/lib/python3.6/site-packages/django/contrib/gis/gdal/feature.py", line 4, in <module> from django.contrib.gis.gdal.geometries import OGRGeometry, OGRGeomType File "/home/samuel/.local/lib/python3.6/site-packages/django/contrib/gis/gdal/geometries.py", line 52, in <module> from django.contrib.gis.geometry import hex_regex, json_regex, wkt_regex ImportError: cannot import name 'hex_regex' I've tried checking online for any issue similar to this dealing with this package and haven't found any. -
Django forms not uploading in the template
Django forms not rendiring in the index page but when I created a new html file then it worked forms.py class UserRegisterForCourse(forms.ModelForm): class Meta: model = RegisterForCourse fields = ['first_name', 'last_name', 'subject', 'phone'] view.py def about_course(request): if request.method == 'POST': form = UserRegisterForCourse(request.POST) if form.is_valid(): form.save() subject = form.cleaned_data.get('subject') messages.success(request, f'you have been successfully registered for {subject}') return redirect('index') else: form = UserRegisterForCourse() return render(request, 'goal/index.html', {'form':form}) in index.html <form action="{% url 'about' %}" method="POST" role="form"> {% csrf_token %} {{ form }} </form> any idea? It needs to work in index page what am i missing? -
How to delete an entry from object in django
I am learning Django and I have some problem in query: I have this code class Publication(models.Model): title = models.CharField(max_length=30) def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) def __str__(self): return self.headline In this code, with a Article objects I can add many Publication entry. How can I use query to delete an entry from Article object ? -
How to serve static files securely using google app engine with django?
Currently my website runs on google app engine with Django and my static files are served using google cloud storage. I had explored the documentations and I could not find a easy way to serve my static files securely. Let say i am logged in as a user into Django site. I only want the logged in user to see the picture and other user can't see the picture. Currently the picture is serve using a link to the google cloud storage and the access are made public. However, that means that anyone with that link can view that picture. How do i make sure that only the logged in person with the link can view the image instead of everyone with the link can view it, is there any way to do it with google app engine standard, google cloud storage and Django? I also know that google cloud storage can have some form of access control but how do i link that part with Django users? -
Django RotatingfileHandler is not creating new log files
I am using django logging to create log files for my project, i want to create new log files whenever existing log file size reaches to 1mb. Here i am using RotatingFileHandler, it creates new log files when size of existing logfile is 1mb but when i stopped my server and deleted all log files and run again, only one log file is created which is 'logfile.log' even when this file size reaches to 1mb no new files are created. settings.py LOGGING = { 'version' : 1, 'disable_existing_loggers' : False, 'formatters' : { 'verbose' : { 'format' : '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style' : '{', }, 'simple' : { 'format' : '{levelname} {message}', 'style' : '{', }, }, # 'filters' : { # 'special' : { # '()' : 'project.logging.SpecialFilter', # 'foo' : 'bar', # }, # 'require_debug_true' : { # '()' : 'django.utils.log.RequireDubugTrue', # }, # }, 'handlers' : { # 'console' : { # 'level' : 'INFO', # 'filters' : ['require_debug_true'], # 'class' : 'logging.StreamHandler', # 'formatter' : 'simple', # }, 'file' : { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'C:\\Users\\gsc-30310\\PycharmProjects\\Django-RestAPI-MongoEngine\\env\\RestUserAPI\\logs\\logfile.log', 'maxBytes' : 1024*1024, 'backupCount' : 10, 'formatter' : 'verbose', }, # 'mail_admins' : { # 'level' … -
installing gdal package for django-location-field and python3
I'm trying to get django-location-field installed on django version 2.1.2 using python3. I installed it and added location_field.apps.DefaultConfig to settings, then an error pops up for a missing package gdal. Error python3 manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7efbf9f56d90> Traceback (most recent call last): ... File "/home/samuel/Documents/code/DECOMAGNA/decomagna/inventory/models.py", line 3, in <module> from django.contrib.gis.geos import Point ... from django.contrib.gis import gdal ... File "/home/samuel/.local/lib/python3.6/site-packages/django/contrib/gis/gdal/prototypes/ds.py", line 9, in <module> from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal File "/home/samuel/.local/lib/python3.6/site-packages/django/contrib/gis/gdal/libgdal.py", line 43, in <module> % '", "'.join(lib_names) django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. Trying to install it throws an error for the package. pip3 install GDAL Collecting GDAL Using cached https://files.pythonhosted.org/packages/e5/57/7f0536cd46bebb30e709b8cd3bcebf9c3d4acc4ad5e9d7bfc73cd39c09a9/GDAL-2.3.2.tar.gz Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info/GDAL.egg-info writing pip-egg-info/GDAL.egg-info/PKG-INFO writing dependency_links to pip-egg-info/GDAL.egg-info/dependency_links.txt writing top-level names to pip-egg-info/GDAL.egg-info/top_level.txt writing manifest file 'pip-egg-info/GDAL.egg-info/SOURCES.txt' Traceback (most recent call last): File "/tmp/pip-build-84b30dz9/GDAL/setup.py", line 153, in fetch_config p = subprocess.Popen([command, args], stdout=subprocess.PIPE) File "/usr/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: … -
Access basket from view called with unit test in Django Oscar
How do I attach a Django Oscar basket that has been created in a unit test to the request object? # views.py from django.contrib.auth.mixins import LoginRequiredMixin from rest_framework.response import Response from rest_framework.views import APIView class BasketAPIAddView(LoginRequiredMixin, APIView): """ Update basket via REST API. """ def delete(self, request, format=None): # # cannot access `request.basket` here # return Response({}) # tests.py from django.contrib.auth import get_user_model from django.urls import reverse from oscar.test.factories import create_basket from rest_framework.test import APITestCase User = get_user_model() class BasketAPITests(APITestCase): """ Basket view test cases. """ def test_remove_basket_line(self): basket = create_basket() basket.owner = User.objects.create_user('user', password='pass') basket.save() self.client.login(username='user', password='password') self.client.delete(reverse('delete-basket')) -
Huge Difference in result when calculating distance b/w two points using longitude-latitude
I am attempting to calculate the distance between two Positions using SRID(32148) Here are my two points Point-1: Lat:46.489767 Long:-119.043221 Point-2: Lat:47.610902 Long:-122.336422 This website states that the distance in miles b/w these two points is 173.388 however from the code below the result I am getting is 0.002161632093865483 This is the code that I am using employeeloc = modelEmployee.objects.filter(user__first_name="adam")[0].location employerloc = modelEmployer.objects.filter(user__first_name="adam")[0].location meters = employerloc.distance(employeeloc) #Caluclate in miles dobj = Distance(m=meters) mi = dobj.mi This is a little more detail with debugging results attached Any suggestions on why my result is so different ? -
How to make query to get last element of each group in Django ORM?
I have kinda Truck table in my Postgresql DB. I write a new data every minute. And I want to get latest element of each group by serial. But problem is my database is so huge and making query takes long time. Now I have 470000 row data. I tried make query: rec_ = Trucks.objects.filter(serial='tsr1801').distinct('serial').order_by('serial', '-id') It is responding so slow. And I tried other methods shown as below, but these queries are also working slow. 1) https://stackoverflow.com/a/19930802/7456750 Mine: Trucks.objects.annotate(max_id=Max('id')).filter(id=F('max_id')) 2) https://stackoverflow.com/a/17887296/7456750 Mine: Trucks.objects.values('serial', 'payload', 'datetime').annotate(id=Max('id')) Is there any way to get latest element of each group, which works fast? +-----+-------------+------------+---------------------+ | Id | Serial | Payload | Datetime | +-----+-------------+------------+---------------------+ | 1 | tsr1801 | 24432 | 2018-11-01 12:00:00 | +-----+-------------+------------+---------------------+ | 2 | tsr1802 | 20234 | 2018-11-01 12:01:00 | +-----+-------------+------------+---------------------+ | 3 | tsr1802 | 21234 | 2018-11-01 12:01:00 | +-----+-------------+------------+---------------------+ | 4 | tsr1801 | 24332 | 2018-11-01 12:02:00 | +-----+-------------+------------+---------------------+ | 5 | tsr1801 | 21532 | 2018-11-01 12:03:00 | +-----+-------------+------------+---------------------+ | 6 | tsr1802 | 19234 | 2018-11-01 12:02:00 | +-----+-------------+------------+---------------------+ | 7 | tsr1801 | 18040 | 2018-11-01 12:04:00 | +-----+-------------+------------+---------------------+ | 9 | tsr1801 | 27452 | 2018-11-01 12:05:00 | +-----+-------------+------------+---------------------+ -
Set initial default language between two language in django
I have a two language and I have also set two language in the setting file LANGUAGES = ( ('bn', _('Bengali')), ('en', _('English')), ) LANGUAGE_CODE = 'bn' And the middleware is MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I also include urls in the pattern like bellow urlpatterns += i18n_patterns( ...................... ................. ) for default language bn I have add a line in homepage view request.session[translation.LANGUAGE_SESSION_KEY] = settings.LANGUAGE_CODE # LANGUAGE_CODE is **bn** If I go the homeurl like 127.0.0.1:8000 it redirects to 127.0.0.1:8000/en/ But I want to see like 127.0.0.1:8000/bn/ Anyone help to so that I my home redirect url is 127.0.0.1:8000/bn/ instead of 127.0.0.1:8000/en/ -
How to resolve ImportError: No module named urls
I get this error whenever I run my code: File "...", line 6, in <module> from django.urls import reverse ImportError: No module named urls So I look at that file and check the line and it says that this has an error: from django.urls import reverse I don't know where the error is coming from because when I delete the line of code, it returns me this error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb I also tried adding MySQLdb in the interpreter but this time, it gives me this error: Non-zero exit code (1) -
How to use Python to find out what site is made with
How can we know that How to make Python script to find out what site is made with.. For example wordpress or joomla or django or laravel and etc -
Need to know the way to access to my Reply table?
Here is my models.py py file. from django.db import models from django.conf import settings from django.urls import reverse class Article(models.Model): '''Modelling the article section.''' title = models.CharField(max_length=200) body = models.TextField() author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) def __str__(self): '''Return string representation of the model.''' return self.title def get_absolute_url(self): '''Return the url of this model.''' return reverse('article_detail', args=[str(self.id)]) class Comment(models.Model): '''Modelling the comment section.''' article = models.ForeignKey( Article, on_delete = models.CASCADE, related_name = 'comments' ) comment = models.CharField(max_length=150) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): '''String representation of the model. ''' return self.comment class Reply(models.Model): ''' Modelling the reply section. ''' comment = models.ForeignKey( Comment, on_delete = models.CASCADE, related_name = 'replys' ) reply = models.CharField(max_length=100) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): ''' String representation of the model. ''' return self.reply I need to access my Reply table in the Detail View template(Using generic view class DetailView). I have tried so far the following command in the template. article.comments.replys.all Its not able to retrive any data from Reply table. Thanks in advance. -
Update Table using django
i have table i want to update the table without redirecting into another page using django ajax.please help me.i am new to this web development. I tried this below link, still it is not working https://www.abidibo.net/blog/2014/05/26/how-implement-modal-popup-django-forms-bootstrap/ Thank You -
Uploading directly to S3
I tried very hard to implement this tutorial on my Django project but didn't succeed. I think that the function I use to sign the post is not working properly. This my function : def sign_s3(request,*args, **kwargs): S3_BUCKET = getattr(settings, 'FILEMANAGER_AWS_S3_BUCKET_NAME') file_name = request.GET.get('file_name') file_type = request.GET.get('file_type') s3 = boto3.client('s3', config = S3ClientCfg(signature_version = 's3v4'), aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, ) # s3 = get_aws_s3_client() presigned_post = s3.generate_presigned_post( Bucket = S3_BUCKET, Key = file_name, Fields = {"acl": "public-read", "Content-Type": file_type}, Conditions = [ {"acl": "public-read"}, {"Content-Type": file_type} ], ExpiresIn = 3600 ) response_dict = { 'data': presigned_post, 'url': 'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, file_name) } mimetype = 'application/json' return HttpResponse(json.dumps(response_dict), mimetype) Actually, when I look into the web console I see : Cross-Origin Request Blocked. (Reason: CORS request did not succeed) -
ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() error?
Im running a populating script which i learned through a tutorial but idk why am i getting this error I'm a novice so any help would be really appreciated from faker import Faker from first_app.models import AccessRecord, Webpage, Topic import random import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') django.setup() fakegen = Faker() topics = ['search', 'social', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t enter code here def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(top_name=top, url=fake_url, name=fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg, date=fake_date)[0] if __name__ == '__main__': print('populating script') populate(20) print('poulated') -
Widgets in inlineformset_factory
Hey i managed to make a inlineformset_factory but my widget in the Parent Model are not working although i have specified them in the ModelForm . My forms.py : class PostForm(forms.ModelForm): post = forms.CharField(widget=CKEditorWidget()) class Meta: model = Post fields = ['title', 'author','picture','post','draft','publish'] class PostVocabForm(forms.ModelForm): class Meta: model = PostVocab exclude = () PostVocabInlineFormSet = inlineformset_factory( Post, PostVocab, extra=1, exclude=(), ) My CKEditorWidget is not working .... My views.py: class PostPostVocabCreate(CreateView): model = Post form_class = PostForm # fields = ['title', 'author', 'picture', 'post', 'draft', 'publish'] def get_redirect_url(self, pk): return reverse_lazy('blog:post_detail', kwargs={'slug': pk}, ) def get_context_data(self, **kwargs): data = super(PostPostVocabCreate, self).get_context_data(**kwargs) if self.request.POST: data['postvocabs'] = PostVocabInlineFormSet(self.request.POST) else: data['postvocabs'] = PostVocabInlineFormSet() return data def form_valid(self, form): context = self.get_context_data() postvocabs = context['postvocabs'] with transaction.atomic(): self.object = form.save() if postvocabs.is_valid(): postvocabs.instance = self.object postvocabs.save() return super(PostPostVocabCreate, self).form_valid(form) I guess that my widget from the Parent model (Post) was overwritten while using a inlineformset_factory... -
How to do Real time communication between Django server and my device, using django rest framework
I am creating an IoT project with a simple switch on and off event that is sent by the user to Django serve. And my device also connected to the Internet. Here I want to get data to the device when the user does any action for the device using the Django Rest framework. Getting data real-time using Django rest framework. Here the device is raspberry PI. Is this possible? If yes Please give me any reference. -
python social auth: get email from Google OAuth2
I configured the login with google in a Django project. I'm able to get the name and last name but the user is saved with an empty email. I configured the scope in this way: SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'profile', 'email' ] But the email continues saving as "". Am I writing the scopes in bad way? -
Pass FormView to DetailView
I am attempting to include Celery in my project so that it asynchronously creates the Hashtag object. However, I need to check if the Hashtag object has been created yet by Celery. To do so, I have overridden get() in SearchResultsView with: if Hashtag.objects.filter(search_text=self.search_text).exists():. Specifically, I am unsure why search_text=self.search_text doesn't work? Perhaps, it's required that I override get_context_data in the FormView to pass the search_filter data to the DetailView? Alternatively, I should use self.get_object() in get() before using the if statement? Models.py class Hashtag(models.Model): search_text = models.CharField(max_length=140, primary_key=True) Views.py class HashtagSearch(FormView): model = Hashtag form_class = SearchHashtagForm def get_success_url(self, search_filter, **kwargs): return reverse('mapping_twitter:results', kwargs={'pk':search_filter}) def form_valid(self, form): search_filter = self.get_tweets(form) iterate_tweets.delay(search_filter) return HttpResponseRedirect(self.get_success_url(search_filter)) def get_tweets(self, form): search_filter = self.request.POST.get('search_text').lower().lstrip("#") return search_filter class SearchResultsView(DetailView): model = Hashtag template_name = 'mapping_twitter/results.html' def get(self, request, *args, **kwargs): if Hashtag.objects.filter(search_text=self.search_text).exists(): self.draw_histogram(request) return super(SearchResultsView, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(SearchResultsView, self).get_context_data(**kwargs) return context -
django-import-export How to format the exported excel's cell?
Is there any way I can format the exported excel file? When i export the files, the column is too small to fit the words. Im quite new to this so any help would be much appreciated. Exported excel file looks something like this, the title cell is too small to fit the words. If django-import-export is unable to do this, then is there any other methods to export database information as excel and is able to format the files? Im quite new to this so any help would be much appreciated. There's actually someone who asked a similar question but there's no answer. Is there a way to manage the column/cell widths when exporting to Excel with django-import-export? Some of my code in admin.py class LogResource(resources.ModelResource): date = Field(attribute='date', column_name='Date') dtime = Field(attribute='dtime', column_name='Departure Time') pilot = Field(attribute='pilot', column_name='Pilot') cpilot = Field(attribute='cpilot', column_name='Co-Pilot') purpose = Field(attribute='purpose', column_name='Purpose of Flight') others = Field(attribute='others', column_name='Others') class Meta: model=Log exclude=('id',) class LogAdmin(ExportActionModelAdmin, admin.ModelAdmin): resource_class = LogResource list_display = ('date', 'dtime', 'purpose', 'pilot', 'cpilot') list_filter = ('date', 'purpose', 'pilot') In views.py def logentry_form_submission(request): date = request.POST["date"] dtime = request.POST["dtime"] pilot = request.POST["pilot"] cpilot = request.POST["cpilot"] purpose = request.POST["purpose"] others = request.POST["others"] log_info = … -
Celery not connecting to redis server
I have a django 2.0.5 app using celery==4.2.1, redis==2.10.6, redis-server=4.0.9. When I start celery worker, I get this output: -------------- celery@octopus v4.2.1 (windowlicker) ---- **** ----- --- * *** * -- Linux-4.18.16-surface-linux-surface-x86_64-with-Ubuntu-18.04-bionic 2018-10-31 17:33:50 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: MemorabiliaJSON:0x7fd6c537b240 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery But in my django settings I have: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_IMPORTS = ('memorabilia.tasks', 'face_recognition.tasks', ) My celery.py looks like: # http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.apps import apps os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MemorabiliaJSON.settings.tsunami') app = Celery('MemorabiliaJSON') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()]) The same code (shared through my git server) works on my development machine, although the redis server is a bit older - v=2.8.4. The development machine is Ubunut 14.04, and the laptop is Ubuntu 18.04. By works, I mean this is the celery output on … -
Server error with Apache, Gunicorn, and Django
I am getting a server error with trying to reverse proxy to Gunicorn. My virtual host file looks like this: <virtualhost *:80> <Location /myApp> ProxyPreserveHost On ProxyPass "http://127.0.0.1:8090/" ProxyPassReverse "http://127.0.0.1:8090/" </Location> </virtualhost> And I'm running Gunicorn like this from within my Django project directory: gunicorn -b 127.0.0.1:8090 -w 3 myApp.wsgi Basically I'm wanting to reverse proxy requests to Gunicorn because I can't use mod_wsgi as it can't be compiled for the version of python I am running on my distro of Linux. -
POST request to simple Django view (hosted on Heroku using gunicorn) leads to H18 Server request interrupted error
I have a simple Django view I'm using to (very roughly) test making POST requests with an attached audio file. The view is simply: @csrf_exempt def create_from_audio(request): return HttpResponse("accepted") But in my heroku logs I see: 2018-10-31T23:55:02.018787+00:00 heroku[router]: sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/polls/create_from_audio" host=XXX request_id=e3608c6e-8c91-440a-ade4-b854e1f72f07 fwd="174.62.90.138" dyno=web.1 connect=0ms service=163ms status=503 bytes=199 protocol=https Here is the code for sending the request: let url = URL(string:"...")! let session = URLSession.shared var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("audio/m4a", forHTTPHeaderField: "Content-Type") request.httpBody = data let task = session.dataTask(with: request) { data, response, error in if let error = error { NSLog("send error: \(error.localizedDescription)") self.showLoading(message: "error sending", error: true) } else { guard let response = response as? HTTPURLResponse else { return } NSLog("send complete, response: \(response.statusCode)") if let pendingMessage = self.pendingNewMessage { self.conversation.messages.append(pendingMessage) self.refreshUI() } } } task.resume() (I realize in a production environment it would be better to upload directly to s3, but in my case I'm simply trying to test the rough speed of uploading the files with a barebones implementation.)