Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using include to import all the urls from my django app
I'm learning Django and I think I'm following an old tutorial. What I'm trying to do right now is connect using the urls.py(in main app) all the urls from my other app. First of all, import the library include (and the others that where already). from django.contrib import admin from django.urls import path, include The write the url/path: urlpatterns = [ path('admin/', admin.site.urls), path('Platform_App', include('Platform_App/urls.py', namespace = 'Platform_App', app_name = 'Platform_App')), ] But reading the django information, I tried to do something like this that doesn't work, urlpatterns = [ path('admin/', admin.site.urls), path('Platform_App', include('Platform_App.urls')), ] How I have to do it correctly? Thank very much!!! -
django admin list custom button's click event
admin.py class TestAdmin(admin.ModelAdmin): class Media: js = ( 'js/common.js', ) list_display = ['custom_actions'] def custom_actions(self, obj): return mark_safe( '<a class="button call_alert" href="#" data-msg="A">A</a>&nbsp;' '<a class="button call_alert" href="#" data-msg="B">B</a>' ) custom_actions.short_description = 'Custom Actions' admin.site.register(Test, TestAdmin) js/common.js (function($) { $(".call_alert").on("click", function() { alert($(this).data("msg")); // ★★★ Dose not!!! ★★★ }); })($); error message : Uncaught TypeError: $ is not a function at common.js:2 at common.js:5 How can I get alert message? Is it impossible? Please help.. -
Display Text in Text Area Django
I'm new to Django and looking for a way to display terms and condition paragraphs in the Text area to view them on my home.html. Text for TextArea: To use the Online Services through U.S. Bank, you must: • Be a U.S. Bank customer with an eligible account; • Have and maintain valid log-in credentials (including a personal ID and password) for Online Services, which may be provided and revoked in our sole discretion; • Have and maintain a valid email address; • Agree to electronically accept this Agreement and notices regarding this Agreement; and • Use Online Services in accordance with the terms of this Agreement. Use of certain Online Services may require additional accounts or other eligibility requirements. Any help would be appreciated, Thanks in Advance -
Django Model DateField and input fixture
Model file includes : class Foo(models.Model): bar = models.DateTimeField() Fixture file.json includes: { "model": "app.Foo", "pk": "1", "fields": { "bar": "2018/4/20", } }, when I'm trying to add fixtures with "python manage.py loaddata" result is: django.core.serializers.base.DeserializationError: Problem installing fixture 'C:\Projects\TestProject\app\fixtures\file.json': ['“2018/4/20” value has an invalid format. It must be in Y YYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']: (app.Foo:pk=1) field_value was '2018/4/20' so my question is how can I add date format with "YYYY/MM/DD" to my Model files ? -
django: unexpected file download after redirect when file does not exist
Django==1.11.12 If the file exists, the view function creates StreamingHttpResponse and all is fine. But if the file does not exist, the view function should redirect. The problem is, it does not redirect but instead prompt up to ask to save as a file, which has the content of redirected html. import os from wsgiref.util import FileWrapper import mimetypes from django.http import StreamingHttpResponse from django.shortcuts import render, redirect try: response = StreamingHttpResponse( FileWrapper(open(file_path, 'rb'), chunk_size), content_type=mimetypes.guess_type(file_path)[0]) response['Content-Length'] = os.path.getsize(file_path) response['Content-Disposition'] = "attachment; filename=a_file.xlsx") except FileNotFoundError as e: response = redirect("home") return response -
How to allow to choose a record from a dropdown or create a new one in Django?
I have a form for Trips where the client can select any of the existing flights from a dropdown. How can I allow the creation of a new flight right there, so that the client doesn't need to go the flight creation page if it realizes only when creating the trip that he needs a new flight? I am new to django/python so I don't really know if this is possible. -
Django timezone converting doesn't work on DateTimeField with values_list
I'm trying implement user based timezone to my Django app. I activated user timezone in middleware. In normal queries (like filter(),all()) everything is ok. In response, I can see timezone awarded data like that: {"modified": "2020-03-11T09:59:18.904323+03:00"} In some cases, I need to use values_list() method. Unfortunately response returns without timezone converting like that: {"modified": "2020-03-11T06:59:18.904323Z"} I can convert data inside a loop but I think it is not a good approach.Did anyone meet this problem? My middleware(It is working): class TimezoneMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: tz_str = request.user.time_zone if tz_str: timezone.activate(pytz.timezone(request.user.time_zone)) else: timezone.activate(pytz.utc) request.user.time_zone = pytz.UTC.__str__() else: timezone.deactivate() response = self.get_response(request) return response -
Problem with many to many fieds in DRF create API
when I want to save an instance of my model, many to many fields did not be saved. I tried with below codes: models: class Attachment(models.Model): test = models.TextField() class PlanComment(models.Model): attachment = models.ManyToManyField('Attachment', blank=True) comment = models.TextField() serializers: class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachment fields = ['test'] class PlanCommentSerializer(serializers.ModelSerializer): attachment = AttachmentSerializer(many=True, read_only=True) class Meta: model = PlanComment fields = [ 'id', 'attachment', ] views: class PlanCommentViewSet(viewsets.ModelViewSet): """ API endpoint that allows plan comment to be viewed or edited. """ queryset = PlanComment.objects.all().order_by('-id') serializer_class = PlanCommentSerializer my params: { "attachment": [1], "comment": "Test" } -
register an admin user in django admin panel with only email id and then email account activation/password link to start using the admin panel
I have taken reference from https://github.com/DjangoGirls/djangogirls to create user model that user email instead of username. But at a super admin level, I want to add an email address and set activation flag and then send an email with a password setting link. Once the admin user clicks on the link and activates his account he should be able to login and start using the admin panel. Any guidance would be highly appreciated... Thanks in advance.. -
Parsing XML and saving Large Data to Django DB
I have a Django function that takes in a Nessus file and then parses the data before saving it to the database, my Nessus file typically have about 30k rows and saving this to the database can take as much as 2 hours, I have tried using bulk_create but this breaks the code, meanwhile I use Django 1.11, is there a way I can speed up these large inserts to the database (postgres) Here is my code: def process_nessus_file(*args, **kwargs): process_obj = kwargs.get('file') context = kwargs.get('context') request = kwargs.get('request') file_obj = process_obj.first() file_path = file_obj.file.path context = etree.iterparse( file_path, events=('end', ), tag="ReportHost" ) total_issues = 0 detected_issues = 0 undetected_issues = 0 already_exist_issue = 0 low_risk_count = 0 medium_risk_count = 0 high_risk_count = 0 critical_risk_count = 0 low_new_issue = 0 medium_new_issue = 0 high_new_issue = 0 critical_new_issue = 0 vul_history = [] for event, elem in context: first_identified = None last_seen = None host = elem.get('name') logger.info('Processing issue for host : {}'.format(host)) for child in elem: if child.tag == "HostProperties": for host_prop_tags in child: if host_prop_tags.attrib['name'] == "HOST_START": first_identified = host_prop_tags.text elif host_prop_tags.attrib['name'] == "HOST_END": last_seen = host_prop_tags.text if child.tag == "ReportItem": main_tags = child.attrib child_tags = dict() for ch_tags … -
How to use AppConfig.label to correctly import modules from an app
I have a third party app I have set up in a subdirectory: # myproject/vendor/rock_n_roll/apps.py from django.apps import AppConfig class RockNRollConfig(AppConfig): name = 'rock_n_roll' label = 'rockme' verbose_name = "Rock ’n’ roll" Now, when I import this I can use from vendor.rock_n_roll.models import .... However, I can't seem to use the label in the same way. E.g. from rockme.models import ... results in "module not found". Per the docs the AppConfig.label is unique across the whole project, and I assume is a shorthand way to access the app. Have I misunderstood the purpose? Is there a way to simply use the label as the import path? If not, what is the purpose of the label otherwise for? -
408 status code on checking access logs of django on apache using mod_wsgi in windows
one is php site and other is django project. Php site is working fine but not django project.It is working fine on local runserver but not on apache.I have followed https://www.codementor.io/@aswinmurugesh/deploying-a-django-application-in-windows-with-apache-and-mod_wsgi-uhl2xq09e tutorial for deployment. httpd-vhosts.conf: <VirtualHost *:8086> ServerName localhost ServerAlias localhost DocumentRoot "${INSTALL_DIR}/www" <Directory "${INSTALL_DIR}/www/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost> <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/Users/smac/fbextractor/fbextractor.error.log" CustomLog "C:/Users/smac/fbextractor/fbextractor.access.log" combined WSGIScriptAlias / "C:\Users\smac\fbextractor\fbextractor\wsgi_windows.py" <Directory "C:/Users/smac/fbextractor"> Require all granted </Directory> <Directory "C:\Users\smac\fbextractor\fbextractor"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /media "C:/Users/smac/fbextractor/media" <Directory "C:/Users/smac/fbextractor/media"> Require all granted </Directory> </VirtualHost> settings.py """ Django settings for fbextractor project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '7(7=3n5ib%=@1i6qd!d&%z!!x0ij@yh3&yf#5400e(#%dl@z@)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost','10.147.41.64','10.147.41.44','14.139.55.130','dj.localhost'] # Application definition INSTALLED_APPS = [ 'extract_friends.apps.ExtractFriendsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
Getting FieldError on confirm_ password when trying to create a custom user form
I'm trying to create a custom user creation form for username, password, and confirm password but I'm getting FieldError for confirm_password. The error goes away when I remove it from fields. class RegForm(forms.ModelForm): class Meta: model = User fields = ('username', 'password', 'confirm_password') widgets = { 'username': forms.TextInput( attrs={'class': 'form-control mb-4', 'required': True, 'placeholder': 'Username'}), 'password': forms.PasswordInput( attrs={'class': 'form-control mb-4', 'required': True, 'placeholder': 'Password'}), 'confirm_password': forms.PasswordInput( attrs={'class': 'form-control mb-4', 'required': True, 'placeholder': 'Confirm Password'}), } def clean(self): cleaned_data = super(RegForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "Passwords needs to match" ) -
Django get SUM of function result from all objects
Something tells me this question is going to be very obvious but I've been stuck on it since all the searching I've done basically ends on calculating the sum of all objects which is what context['all_trades'] does. However, I'm looking to calculate the sum of all object results calculated in a function. I hope this is properly worded. If I print out the context this is the result: {'view': <portfolios.views.StatsView object at 0x0000020CC8B0D188>, 'all_trades': 13, 'gross_profit': <function Trade.get_profit_loss_value at 0x0000020CC70598B8>} models.py class Trade(models.Model): class Meta: verbose_name = "Trade" verbose_name_plural = "Trades" user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) ... def get_profit_loss_value(self): ret = self.get_profit_loss_value_or_None() return 0 if ret is None else ret views.py class StatsView(TemplateView): template_name = 'dashboard/stats.html' def get_context_data(self, *args, **kwargs): context = super(StatsView, self).get_context_data(*args, **kwargs) # get # of trades user made context['all_trades'] = Trade.objects.filter(user=self.request.user).count() # get sum of all trades profit/loss context['gross_profit'] = Trade.get_profit_loss_value return context -
Django is showing a method object is not subscriptable when submitting email
I have a website and I would like to allow users to contact us. Thus, when I click on the submit button I am getting the error 'method' object is not subscriptable Bellow is the error: TypeError at /contact/ 'method' object is not subscriptable Request Method: POST Request URL: https://massiwatechnology.com/contact/ Django Version: 2.1.8 Exception Type: TypeError Exception Value: 'method' object is not subscriptable Exception Location: /home/massiwat/mysite/pages/views.py in contact, line 347 Python Executable: /home/massiwat/virtualenv/mysite/3.7/bin/python3.7 Python Version: 3.7.3 Python Path: ['', '/opt/alt/python37/bin', '/home/massiwat/mysite', '/home/massiwat/virtualenv/mysite/3.7/lib64/python37.zip', '/home/massiwat/virtualenv/mysite/3.7/lib64/python3.7', '/home/massiwat/virtualenv/mysite/3.7/lib64/python3.7/lib-dynload', '/opt/alt/python37/lib64/python3.7', '/opt/alt/python37/lib/python3.7', '/home/massiwat/virtualenv/mysite/3.7/lib/python3.7/site-packages'] Server time: Wed, 11 Mar 2020 09:12:21 +0000 #Contact view.py def contact(request): submitted = False if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # full_name=form.cleaned_data['Th'] mail=request.POST.get['email'] subject=request.POST.get['objet'] msg=request.POST.get['message'] send_mail(mail, subject, msg, settings.EMAIL_HOST_USER, ['med.abdillah@massiwatechnology.com'],fail_silently=False) return HttpResponseRedirect('/contact?submitted=True') else: form = ContactForm() if 'submitted' in request.GET: submitted = True return render(request, 'contact.html', {'form': form, 'submitted': submitted}) And bellow is the ContactForm.py: class ContactForm(forms.Form): # nom_complet=forms.CharField(max_length=100, required=True) email=forms.EmailField(required=True) objet=forms.CharField(widget=forms.Textarea( attrs={ "rows":1, "cols":80 } )) message=forms.CharField( widget=forms.Textarea( attrs={ "class":"message two", "rows":5,"cols":80 } ) ) I also would like to know if the configuration bellow for sending a professional email is correct, please. EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST='mail.massiwatechnology.com' EMAIL_PORT='465' EMAIL_HOST_USER='med.abdillah@massiwatechnology.com' EMAIL_USE_TLS=True EMAIL_HOST_PASSWORD='mypassord' Please assist -
Could not send email in djano rest framework
I am developing password reset part of the project. I am using django_rest_passwordreset to get the password reset. I am using mailjet smtp. I could not send the email to the user. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'in-v3.mailjet.com' # EMAIL_PORT = 465 EMAIL_PORT = 587 EMAIL_USE_TLS = True # EMAIL_USE_SSL = True EMAIL_HOST_USER = '5e4329460b3c88f1d24d19c3e7374548aa213da%asasd1asd' EMAIL_HOST_PASSWORD = 'a6c5ab2515d6ae761253a396453530ba$42asasdasdaasdasd' If I change the EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' to the EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' it is printing it to the console. I have no idea why it is not working. the part of the code where I am trying to send an email. @receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): # send an e-mail to the user context = { 'current_user': reset_password_token.user, 'username': reset_password_token.user.firstname, 'email': reset_password_token.user.email, 'reset_password_url': "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key) } # just checking if it works send_mail('Hello from something', 'hello there', 'abdukhashimov@yandex.ru', [reset_password_token.user.email, ], fail_silently=False) # render email text email_html_message = render_to_string('user_reset_password.html', context) email_plaintext_message = render_to_string( 'user_reset_password.txt', context) msg = EmailMultiAlternatives( # title: "Password Reset for {title}".format(title="Some website title"), # message: email_plaintext_message, # from: "noreply@somehost.local", # to: [reset_password_token.user.email] ) msg.attach_alternative(email_html_message, "text/html") msg.send() -
Why the field description of my django model is not null?
I have created a model like this, class fleets(models.Model): fleet_id = models.IntegerField(primary_key=True) fleet_name = models.CharField(max_length=20) description = models.CharField(max_length=40, null=True) And when I observe in the postgresql admin the table I see is like what I want, fleet_id as pk and not null fleet_name not null description null But, why when I want to add some fleet with the django-admin it says is not possible? I forget some parameter? Thank you very much!! -
Django Gunicorn ConnectionHandler has no attribute 'connection_pool'
I've installed https://github.com/zhangi/django_db_pooling with Django 3.0.4 to enable connection pooling with Gunicorn. Due to an error with compatibibility, I've applied the patch in this post https://adamj.eu/tech/2020/02/04/how-to-use-pymysql-with-django/: import pymysql ... DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "testapp", } } # Fake PyMySQL's version and install as MySQLdb # https://adamj.eu/tech/2020/02/04/how-to-use-pymysql-with-django/ pymysql.version_info = (1, 4, 2, "final", 0) pymysql.install_as_MySQLdb() As per the instructions of the django_db_pooling library I've applied the configuration as follows: import os import pymysql from django.core.wsgi import get_wsgi_application from django_db_pooling import pooling pymysql.install_as_MySQLdb() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxxxx.settings") application = get_wsgi_application() pooling.set_pool_size(4) pooling.apply_patch() However, when my project is running in gunicorn and it tries to access the database I get the following errors: Traceback (most recent call last): File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 187, in handle_request respiter.close() File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/django/http/response.py", line 253, in close signals.request_finished.send(sender=self._handler_class) File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/django_db_pooling/pooling.py", line 121, in recycle_old_connections ConnectionHandler.connection_pool[alias].release(conn) AttributeError: type object 'ConnectionHandler' has no attribute 'connection_pool' -
in Vscode, RuntimeError: 'path' must be None or a list, not <class '_frozen_importlib_external._NamespacePath'>
I use Ubuntu and Vscode. In my Django project, I've tried to run "python manage.py process_tasks" command and I got this error below. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/../venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/../venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/../venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/../venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/../venv/lib/python3.6/site-packages/background_task/management/commands/process_tasks.py", line 123, in handle self.run(*args, **options) File "/home/../venv/lib/python3.6/site-packages/background_task/management/commands/process_tasks.py", line 96, in run autodiscover() File "/home/../venv/lib/python3.6/site-packages/background_task/tasks.py", line 317, in autodiscover imp.find_module('tasks', app_path) File "/usr/lib/python3.6/imp.py", line 271, in find_module "not {}".format(type(path))) RuntimeError: 'path' must be None or a list, not <class '_frozen_importlib_external._NamespacePath'> How can I fix this? -
How to custom sort order in djnago like mysql FIELD Function
How to write django queryset custom sort order like mysql field function in django select status from comapnay order by FIELD(status, 'Follow Up', 'Interested - Call back scheduled', 'Need to send details', 'Quotation sent') Comapany.objects.all().order_by(?) -
'teamview' object has no attribute 'get_object'
I have a problem with UserPassesTestMixin, I want to restrict views from viewing people assigned for the manager. It's giving me an error of 'teamview' object has no attribute 'get_object'. Here is my views.py in question: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ListView, CreateView, DetailView from .models import Job, Member from profiles.models import User from django.contrib.auth.decorators import login_required # Create your views here. class jobs(LoginRequiredMixin,ListView): model = Job template_name = 'users/user_jobs.html' context_object_name = 'jobs' def get_queryset(self): return Job.objects.filter(member__member=self.request.user) class createdjobs(LoginRequiredMixin,ListView): model = Job template_name = 'users/manager_jobs.html' context_object_name = 'jobs' def get_queryset(self): return Job.objects.filter(manager__manager=self.request.user) class teamview(LoginRequiredMixin,UserPassesTestMixin,ListView): model = Member template_name = 'users/manage_team.html' context_object_name = 'members' def test_func(self): return self.get_object().manager == self.request.user def get_queryset(self): return Member.objects.filter(manager__manager=self.request.user) class jobdetail(LoginRequiredMixin,DetailView): model = Job class createjob (LoginRequiredMixin,UserPassesTestMixin,CreateView): model = Job fields = ['member','title', 'description', 'file'] def form_valid(self,form): form.instance.manager=manager.objects.get(manager=self.request.user) return super().form_valid(form) def test_func(self): return self.get_object().manager == self.request.user Hope you cna help me out with this TIA. -
Django channels "ERROR Y of N channels over capacity in group subscriptions"
I'm doing load testing with my Django app providing GraphQL Subscriptions using Django channels and a redis Channels layer (django, graphene-django, channels, graphene-subscriptions, channels-redis). As ASGI server I'm using daphne right now. I use nginx as proxy. The periodicity with which the backend publishes messages via GraphQL Subscriptions depends on the periodicity of messages the backend receives via MQTT. I'm increasing the periodicity with which an external data provider publishes messages to the MQTT broker, means the periodicity with which the backend has to process these messages and publish messages via GraphQL Subscriptions. I'm facing the following error: 2020-03-11 08:33:58,464 ERROR 2 of 12 channels over capacity in group subscriptions It seems like this issue is caused by an overload. To me it's not clear what's the performance bottleneck. What's the root cause of this issue? Can I scale the infrastructure to workaround this issue? -
VSCode ignoring breakpoints during debug in python
I'm trying to debug a Django project with VSCode. Everything works fine, I get the output and VSCode footer goes purple (debug mode) but it just ignores the breakpoints. I'm working on WSL (vscode remote) Python 3.6.9 (virtualenv) VSCode 1.43 (using Python and Python for VSCode extensions) This is my launch.json file: { "version": "0.2.0", "configurations": [ { "name": "Django", "type": "python", "request": "launch", "stopOnEntry": false, "program": "${workspaceRoot}/bullfrogloader/manage.py", "args": [ "runserver", ] }, ] } This is an screenshot of vscode running it, just in case you see something weird there: thank you so much guys, I just don't know what else to do. -
How do I run a script every day at 00:00 hrs to hit an django API on Ubuntu machine?
I need information about how to hit a django API running on ec2 on every night 00:00 hours. Thanks in advance. -
Different error between port 80 and 5500 when running site
I'm working on a chat bot system. Every time I write a message and expect a message back, I get an error message. The weird part is that the error message depends whether I run the site on localhost port 80 or 5500. If I run it on localhost (port 80), I get the POST http://localhost/get-response/ 404 (Not Found) If I run it on localhost:5500 I get POST http://localhost:5500/get-response/ 405 (Method Not Allowed) chatbot.js fetch("/get-response/", { //<--- error body: JSON.stringify({'message': message['text']}), cache: 'no-cache', credentials: 'same-origin', headers: { 'user-agent': 'Mozilla/4.0 MDN Example', 'content-type': 'application/json' }, method: 'POST', mode: 'cors', redirect: 'follow', referrer: 'no-referrer', }) .then(response => response.json()).then((json) => { this.messages.push(json['message']) }) urls.py urlpatterns = [ url('', Index), path('get-response/', get_response), ] views.py @csrf_exempt def get_response(request): response = {'status': None} if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) message = data['message'] chat_response = chatbot.get_response(message).text response['message'] = {'text': chat_response, 'user': False, 'chat_bot': True} response['status'] = 'ok' else: response['error'] = 'no post data found' return HttpResponse( json.dumps(response), content_type="application/json" ) def Index (request): context = {'title': 'Chatbot Version 1.0'} return render(request, "AI.html", context) How do I know which error message to go for?