Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to build a real time Chat application using Django Channels, Daphne and Apache 2.2?
I am trying to use Django Channels with Daphne and Apache 2.2.15 on CentOS 6.10 for a real time chat application. I want to forward all WebSocket requests from Apache to Daphne. But the module mod_proxy_wstunnel is not supported in Apache 2.2. It's not possible to switch to Apache 2.4 because of project restrictions. Is there any way to build a Chat application using Django Channels and Apache 2.2? -
Make Django Form Validation For Reservation
i make a reservation system, which has form validation, This should check whether the the bus on that date is already booked or not, but, unfortunately there still error on this code.. so here my code : forms.py class BookingForm(forms.ModelForm): class Meta: model = Booking fields = '__all__' tempReDate = date(1,1,1) # temp local variable def clean_start(self): start = self.cleaned_data['start'] # cheacking if date for this bus is free res_all = Booking.objects.all() for item in res_all: if start >= item.start and start <= item.end and item.resourceId == self.instance.resourceId: raise forms.ValidationError("This date already reserved by same bus, choose other date or other bus") #set variable to send for next funtion: clean_EndDate self.tempReDate = start return start def clean_end(self): #check if EndDate is empty if not self.data['end']: #set numbers days of reservation 1 if no end date self.instance.numOfDays = 1 return None # if start date is empty if self.tempReDate == date(1,1,1): raise forms.ValidationError("Must Choose start date") # if start date is not empty else: start = self.tempReDate end = self.cleaned_data['end'] # cheackig start date is not lower than end date if end < start: raise forms.ValidationError("start date cannot be later than end date") # cheackig if reservation is no longer than … -
DRF registration and login without "password2" and "username"
I'd like to customize the registration and login using the dj-rest-auth library. I have a CustomUser model and do not want username nor password2 (password confirmation) when registering. Instead, I'd like registration to require only these fields: first_name last_name email password And login to be simply: email password What are the step to customize registration with dj-rest-auth? custom user model: from .managers import CustomUserManager class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email -
Django - html submit to view to api call to html page
So I am as Green as they come and am attempting the following. Our Work Management app has an average API but a very poor customer portal. I am attempting to produce at least a prototype of what I want and have been using Django (for the first time) I think I am almost there but have got myself all tangled. Being a newbie the Documentation does not enlighten me much. From one of the web pages the user enters a job number and clicks submit. I need that job number to complete my API call then I want to display the job information in job.html After a few days (like 5) I have the job number passing to the view and see the JSON data in the terminal but cannot get it to display in job.html I am getting this error AttributeError at /job/ 'dict' object has no attribute 'headers' Request Method: POST Request URL: http://127.0.0.1:8000/job/ Django Version: 3.2.dev20210111104520 Exception Type: AttributeError Exception Value: 'dict' object has no attribute 'headers' Exception Location: c:\users\davidp\django\django\middleware\clickjacking.py, line 33, in process_response Python Executable: C:\Program Files\Python38\python.exe Python Version: 3.8.2 I had the job page working when I manually entered a job number to the … -
What is a good design pattern for batching API calls in response to a webhook? [Django]
Background I am developing a Django application to receive order information fired off by a WooCommerce webhook and manipulate data in our CRM through their API. Problem Our CRM has a limit on daily API calls. Currently, my application makes 3 API calls in response to each instance of the webhook firing to authenticate, find the id of records matching the incoming order, and manipulate that record. I'd like to queue order information as it comes in from the webhook and process it in batches to reduce the number of API calls. I'm a bit lost on how to design this queueing system. I have some basic ideas and I've been looking into Redis and Celery as possible libraries to use, but I haven't been able to find any instances of this exact problem. Any advice or resources for designing an approach would be super helpful! -
Why Does My Django UpdateView Dosen't Work
My UpdateView doesn't Work I Tried i think the code doesn't reach the form_valid this is my views.py class PollUpdateView(UpdateView): model = Poll fields = ('Question',) template_name = 'question_edit.html' pk_url_kwarg = 'poll_id' context_object_name = 'polls' def form_valid(self, form): polls = form.save(commit=False) polls.updated_by = self.request.user polls.updated_date = timezone.now() polls.save() return redirect('home') and my models.py class Poll(models.Model): Question = models.CharField(max_length=100,unique=True) created_by = models.ForeignKey(User,related_name='created_by',on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(User,related_name='+',on_delete=models.CASCADE,null=True) updated_date = models.DateTimeField(null=True) def __str__(self): return self.Question -
Why do my Celery Remote Control functions hang?
I am attempting to use Celery's Remote Control functionality to revoke tasks. Most of the time the function I attempt to use app.control.revoke(task_id) just hangs and does not produce a result. There were a few times it worked but 95% percent of the time it hangs. The same is true for app.control.ping I am using Celery version 4.2.1 and Kombu 4.6.8 (attempted upgrading Kombu to 4.6.11 with no change) on Heroku with cloudamqp for RabbitMQ. See below for the stacktrace from when I do a keyboard escape. File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 69, in handle self.run_shell(shell=options['interface']) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 61, in run_shell raise ImportError ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.6/site-packages/celery/app/control.py", line 253, in ping timeout=timeout, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/celery/app/control.py", line 454, in broadcast limit, callback, channel=channel, File "/app/.heroku/python/lib/python3.6/site-packages/kombu/pidbox.py", line 346, in _broadcast matcher=matcher) File "/app/.heroku/python/lib/python3.6/site-packages/kombu/pidbox.py", line 307, in _publish with self.producer_or_acquire(producer, chan) as producer: File "/app/.heroku/python/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/app/.heroku/python/lib/python3.6/site-packages/kombu/pidbox.py", line 267, in producer_or_acquire with self.producer_pool.acquire() as producer: File "/app/.heroku/python/lib/python3.6/site-packages/kombu/resource.py", line 83, in acquire R = self.prepare(R) File "/app/.heroku/python/lib/python3.6/site-packages/kombu/pools.py", line 62, in prepare p … -
Geolocation Django XMLHttpRequest not working inside of Javascript call. Do I need CSRF token?
My call from JS to my django views is not working at all and I am not sure why. Is it because I need a csrf token? If so, how do I even incorporate into the JS? My code in html is like this {% extends '_base.html' %} {% load static %} {% block title %}Location{% endblock title %} {% block content %} <button id = "find-me">Find Storages Near Me</button><br/> <div id="mapid"></div> {% endblock content %} JS function geoFindMe() { // get the coordinates on success function success(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; // send user data into backend reqeust const request = new XMLHttpRequest(); // post is more secure request.open('POST', '/find_nearby_storage'); request.onload = () => { alert('HTTP request back!'); } } document.querySelector('#find-me').addEventListener('click', geoFindMe); urls.py path('find_nearby_storage/', find_nearby, name='locate'), views.py def find_nearby(request): # get user location if request.method == 'POST': print("hello from the reqeust") return HttpResponseRedirect(reverse('home')) else: return HttpResponseRedirect(reverse('about')) -
How to limit FK choices based on kwargs input in Django for a form
I have a form which is for creating a booking slot. In the booking slot model there is a foreign key model to the location for that slot. #forms.py class BookingSlotForm(ModelForm): class Meta: model = BookingSlot fields = ['date','start_time', 'end_time', 'location'] #views.py class CreateBookingForm(CreateView): template_name = 'app_book/create_bookings.html' form_class = BookingSlotForm #urls.py urlpatterns =[path('create/<int:club>/', CreateBookingForm.as_view(), name="create_booking")] I want to be able to use the club id (given in the URL) to limit the choices for locations for a booking slot. For example, a club called Lambda can only see courts 4, 5 and 6 and not courts 2, 3 or 1. I have looked into "limit_choices_to" but I don't think this is the right way to do this. Help would be much appreciated -
CreateView/UpdateView to include related ForeignKey in form
I have a one-to-many relationship between two models using ForeignKey as usual, e.g.: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books') I wanted to use the elegant generic CreateView and UpdateView to create/modify authors. When doing so, I would like to simultaneously edit their book list and even add books. I was hoping I could simply do: from django.views.generic.edit import CreateView from .models import * class AuthorCreate(CreateView): model = Author fields = ['name', 'books',] but it doesn't seem to be that easy and I get the exception Unknown field(s) (books) specified for Author. Is there an elegant way of doing this without writing my own view/formset? How are you dealing with such a use-case in your projects? PS: Bonus points if there is a similarly elegant solution for ManyToManyField relations. PPS: Within admin I have already found how to achieve this: class Book_InlineAdmin(admin.TabularInline): model = Book extra = 1 class Author_Admin(admin.ModelAdmin): inlines = (Book_InlineAdmin,) admin.site.register(Author, Author_Admin) -
Django URL duplication Bug
I'm developing a little application in Django and I need to add a contact form. U know, the typical send mail form. Everything works right, but when I was testing the nav bar I notice that, when I click the same route two times the route is douplicated http://127.0.0.1:8000/Contacto/Contacto Is really funny to see but I began to despair. My question is, is there any way to avoid this bug? This is how I declared the path in urls.py : path('Contacto/', views.contactPageRender, name="Contacto") This is the function that render the .html file: def contactPageRender(request): return render(request,"contact.html") And this is the html tag that drives to the URL: <nav class="navbar navbar-expand-lg navbar-light fixed-top" style="background-color: #bebebe;"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a href="Contacto" class="nav-link">Contacto</a> </li> </ul> </nav> -
Custom Wagtail admin page with fields of different models
My goal is to register and create only one Wagtail admin page where I can create/edit/see objects of the Question model, but also with the possibility of adding other fields from the other models that are related to this one through foreign keys (given that creating an instance of Question model also can create an instance of the QuestionVersion and AnswerVersion models, as shown in the models.py file: ... class Question(models.Model): filepath = models.CharField(max_length=255, null=True, blank=True) slug = models.CharField(max_length=255, null=True, blank=True) order = models.CharField(max_length=255, null=True, blank=True) category = models.ForeignKey('wiki.Article', on_delete=models.SET_NULL, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return "{}".format(self.id) class QuestionVersion(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) slug = models.CharField(max_length=255, blank=True, null=True) title = models.TextField(max_length=255) description = models.TextField(null=True, blank=True) categories = models.ManyToManyField(Article, null=True, blank=True) approved = models.BooleanField(default=False) class AnswerVersion(models.Model): question_version = models.ForeignKey(QuestionVersion, on_delete=models.CASCADE) text = models.TextField() correct = models.BooleanField(default=False) def __str__(self): return self.text ... Right now I am registering/generating 3 pages to do the task in my wagtail_hooks.py (managing the Question model instances): ... class QuestionAdmin(ModelAdmin): model = Question list_display = ('id', 'user') class QuestionVersionAdmin(ModelAdmin): model = QuestionVersion list_display = ('question', 'title', 'description', 'categories', 'approved') class AnswerVersionAdmin(ModelAdmin): model = AnswerVersion list_display = ('question_version', 'text', 'correct') class Admin(ModelAdminGroup): menu_label = … -
why is this json string being implemented incorrectly into a django template?
So I am trying to pass some json data to a variable in a html template which will be able to be accessed globally by the client side code (for responding to an api but that isn't the point) The json is what a react app will use to parse some stored data on the server however when I pass the jsonified string to html it gives a weird result in the javascript ultimately not being able to parse the data: def get_data(request): context = {} # here the json function turns it to a json string fine context["some_data"] = json.dumps({"key": "data"}) return render(request, "ordering/somehtmlfile.html", context) <script> const menu_data = JSON.parse('{{ menu_data }}'); // I found the issue here from inspecting it in chrome // "data" variable is: '{&quot;key&quot;:&quot;data&quot;}' console.log(data); </script> Clearly this is some really weird result. I don't know if I've maybe missed some step or something but my javascript skills are really not up to standard so I'm sorry if this is a really stupid question but any help would be appreciated. -
JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0)
I'm working on a Django app and I'm trying to redirect based on a response from an API, but I can't seem to find a way to get the value of the response. This is the response: { "Body": { "stkCallback": { "MerchantRequestID": "24915-30681242-1", "CheckoutRequestID": "ws_CO_150220211305438433", "ResultCode": 0, "ResultDesc": "The service request is processed successfully.", "CallbackMetadata": { "Item": [ { "Name": "Amount", "Value": 1.00 }, { "Name": "MpesaReceiptNumber", "Value": "" }, { "Name": "TransactionDate", "Value": 20210215130604 }, { "Name": "PhoneNumber", "Value": } ] } } } Need help on passing ResultCode to variable. I have tried def callback(request): response = json.loads(request.body) ResultCode = response['ResultCode'] return render(request, 'callback.html') But it still throws an error, any help would be appreciated. -
Django image url redirect is going through link for HTML template rather than media file?
I have a django app, a template on which contains an image. The problem I know is that the server is trying to display the image via the redirect link from the html template rather than from the media file. Example: <tbody> {% for equipment in inventory_obj %} <tr> <td class="table-blocks">{{ equipment.id }}</td> <td class="table-blocks">{{ equipment.name }}</td> <td class="table-blocks">{{ equipment.total_quantity }}</td> <td class="table-blocks">{{ equipment.location }}</td> <td class="table-blocks"><a href= "{{ equipment.img_reference }}">IMAGE</a></td> <td class="table-blocks"> <a href="/EditInventory/{{ equipment.id }}" id="Edit-Page-Link">Edit</a> </td> </tr> {% endfor%} BUT when I add equipment.img_reference.url - the app returns an attribute error saying that no file was found. The equipment.img_reference also has a problem, when i click on the link, the app opens the image via the HTML app - url is: localhost/ViewInventory/images_uploaded/WIN_20210215_19_54_16_Pro.jpg - when it should be this: localhost/media/images_uploaded/WIN_20210215_19_54_16_Pro.jpg This is the urls.py file for the app and for the project: app: from django.conf import settings from django.conf.urls.static import static from . import views # . is from 'this app' import views urlpatterns = [ path("", views.homepage, name="home"), #name must be same as the function name in the views.py, the path('') in the urls.py of mysite looks for the same path in '' and then renders the … -
Django 3.1 and Django 3.0 Internationalization and localization
Although all the settings files are done as described in the document, meaningless multi-language change cannot be activated. Sample: from django.utils.translation import activate, get_language_info activate('fr') -
WSGIScriptAlias / /home/me/myproject/myproject/wsgi.py throws internal server error
I am having trouble linking my application to the base / (server IP or domain). But my problem is whenever I put this line in my /sites-available/project.conf and restart the apache server, the web page immediately throws from default apache page to internal server error. I want the application to run when type the base domain. This is the errors log: [Mon Feb 15 12:21:03.173931 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] mod_wsgi (pid=78014): Failed to exec Python script file '/home/me/myproject/myproject/wsgi.py'. [Mon Feb 15 12:21:03.173982 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] mod_wsgi (pid=78014): Exception occurred processing WSGI script '/home/me/myproject/myproject/wsgi.py'. [Mon Feb 15 12:21:03.174075 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] Traceback (most recent call last): [Mon Feb 15 12:21:03.174101 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] File "/home/me/myproject/myproject/wsgi.py", line 16, in <module> [Mon Feb 15 12:21:03.174106 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] application = get_wsgi_application() [Mon Feb 15 12:21:03.174112 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] File "/home/me/myproject/venv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Feb 15 12:21:03.174115 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] django.setup(set_prefix=False) [Mon Feb 15 12:21:03.174121 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] File "/home/me/myproject/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup [Mon Feb 15 12:21:03.174124 2021] [wsgi:error] [pid … -
Is it possible to include a Django url in a Pandas dataframe?
I am trying to include a Django URL in a Pandas dataframe but Django templates is not changing the url templatetag for the actual link. Reading here and there this is what I have gotten so far: This is my link that I include on each row: link = "<a href=\"{% url 'account_policies' " + "month=" + "'" + month_number + "' %}>Policies</a>" this is the url that I defined on urls.py: path( "account/<str:month>/policies/", AccountPoliciesView.as_view(), name="account_policies" ) Then I render the DataFrame as an HTML table: context['df'] = df.to_html(index=False, escape=False) Then I render the variable with the safe tag: <div> {{ df | safe }} </div> And when I inspect the element I get this: <td> <a href="{% url 'account_policies' month='01' %}"> Policies </a> </td> It is clickable but Django throws a 404. Is there a way to fix this or another way to do it? -
Cannot login to Admin panel after deploying Heroku
So I deployed a Django rest framework to Heroku and after setting up PostgreSQL, running the migrate command and also creating a superuser, I cannot seem to login into my Django admin panel. Below is my settings.py file. Django settings for ptracker project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost', 'trakkkr.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tracker.apps.TrackerConfig', 'corsheaders', # installed apps 'rest_framework', 'rest_framework.authtoken', ] AUTH_USER_MODEL = 'accounts.Account' 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', ] ROOT_URLCONF = 'ptracker.urls' CELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', … -
How to upload image with ckeditor5 in django project?
Since some features of the ckeditor5 really attract me, so I want to integrate it into my django project. version By following the easiest way (for me maybe), I downloaded zip files version from the online builder so the ckeditor5 in my project looks: structure custom image upload adapter this is my custom image upload adapter, which I found from some blogs write by others class UploadAdapter { constructor(loader) { this.loader = loader; } upload() { return new Promise((resolve, reject) => { const data = new FormData(); data.append('upload', this.loader.file); data.append('allowSize', 10); $.ajax({ url: '/media/uploads/', type: 'POST', data: data, dataType: 'json', processData: false, contentType: false, success: function (data) { if (data.res) { resolve({ default: data.url }); } else { reject(data.msg); } } }); }); } abort() { if (this.xhr){ this.xhr.abort(); } } } editor creation <script> let ckdata; ClassicEditor .create( document.querySelector( "textarea[name='content']") ,{ toolbar: [ 'bold', 'italic','|','link','blockQuote', 'codeblock', 'imageupload','|','numberedList', 'bulletedList', 'insertTable', '|', 'MathType', 'ChemType', '|', 'undo', 'redo', ], // <--- MODIFIED }) .then(editor => { window.editor = editor; ckdata = editor.getData(); console.log(ckdata); window.editor.plugins.get('FileRepository').createUploadAdapter = (loader)=> { return new UploadAdapter(loader); } }) .catch( error => { console.error( error ); //end } ); </script> performance now I'm able to insert image into the … -
Django: How to renew SimpleJWT access token when token are stored in HttpOnly cookies?
I have stored the SimpleJWT access and refresh tokens in HttpOnly cookies. Now, how do I reproduce an access token from the refresh token once it expires? In React I used setTimeout() to request for new access token and it worked just fine. Now that I'm storing these as HttpOnly cookies, how do I check whether the access is valid or not and if not, create and send a new access token as HttpOnly cookie? I have this middleware where I add the tokens from cookie to Authorization middleware, is it possible to renew to token in any such middleware: class AuthorizationHeaderMiddleware: def __init__(self, get_response=None): self.get_response = get_response def process_view(self, request, view_func, view_args, view_kwargs): view_name = '.'.join((view_func.__module__, view_func.__name__)) #print(view_name) if view_name in EXCLUDE_FROM_MIDDLEWARE: return None def __call__(self, request): access_token = request.COOKIES.get('access') if access_token: request.META['HTTP_AUTHORIZATION'] = f'Bearer {access_token}' return self.get_response(request) -
Can I pass a context variable into a Django form?
I can't really seem to find the answer anywhere. Basically, I have data in my view coming from an API that I want to pass into form fields. Is that possible? -
Accessing multilevel json data in Django
I have a problem with one part of json file i need to use. json file looks more or less like that: "name1": { "item1":{ "value1": "value" "value2": "value" ... "name2": [ { "item1":[ { "value1": "value" "value2": "value" ... Values in "name1" can be easily accessible. views.py #response to string r = res.text j = json.loads(r) x = standings["name1"] y = standings["name2"] then i return x to template, and then i can iterate through data like that: {% for key, value in x.items %} but that doesn't work for "name2". "name1" is Dict, "name2" is list. In template i can't access values in name2. I have to show, both "item1" string from "name2", and all values inside "item1". How can i do that? -
Django redirect cors error even with django-corse-headers
In one of my Django views, I use a redirect to an external url like so: from django.shortcuts import redirect ... class SomeApi(generics.GenericAPIView): def post(self, request): if request.user.is_authenticated: #Do some stuff here link = #get some link return redirect(link) return Response(status=status.HTTP_401_UNAUTHORIZED) But the browser (Chrome) complains and gives the following error: Access to XMLHttpRequest at 'https://some.externalurl.com' (redirected from 'http://localhost:3000/api/some/call/') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. However, I have installed django-cors-headers and configured my settings as generally recommended: INSTALLED_APPS = [ ... 'corsheaders', ... ] ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True My front-end is written in React, but I gather this is supposed to be purely a server-side problem. Any suggestions? I have been stuck here for some time now and virtually every answer to Django CORS problems on the web ends in 'just use django-cors-headers'... I'm at a point now where I'm considering returning the url as part of a 200 response and try and redirect from the front-end. -
Deploy on `heroku` failed from different machines
I'm facing an issue with my Heroku deployment, let me explain my current stack : Local Machine 1: Here it's my old local machine which runs the same code base (Postgres/Django) under Docker and I usually used it to deploy on Heroku my app. Local Machine 2: My new laptop build and run exactly the same codebase, everything works locally but when deployed and released on Heroku I'm ending up with Error: Exec format error error without additional information. Build Process: docker login --username=_ --password="$HEROKU_API_KEY" $HEROKU_REGISTRY docker build --build-arg "${HEROKU_REGISTRY}/my_app/web" -f backend/Dockerfile backend docker push "$HEROKU_REGISTRY/my_app/web" Deploy process: heroku container:login heroku container:release web --app my_app