Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to automate one-off admin processes tied to releases
Using Terraform and Azure App Services for a Django app, similar to what is described here: https://testdriven.io/blog/deploying-django-to-ecs-with-terraform/. I'm wondering how to best automate the once-per-release actions (such as manage.py migrate)? These would be the "Admin processes running against a release" from Rule 12 of the 12-factor app. If I was doing releases "manually", I would first update the containers and then run docker exec ... my_post_release_actions.sh on any one (but only one) of the containers. Being a total noob with Terraform, I'm temped to bake the logic into the image, using an entrypoint script. But that seems overly complicated, especially if I want to make sure that the code is executed only once per deployment (i.e. only by a single container, whichever gets spun up first). Surely there is a better way? -
I am getting "Not Found: /static/rest_framework/css" errors when I run Django from gunicorn
I have a Django project that works fine when I start it like so: (venv) red@red bastion_query_system % python manage.py runserver and I would like to run it with gunicorn instead. So I start gunicorn like so: (venv) red@red bastion_query_system % gunicorn bastion_query_system.wsgi [2021-03-02 11:30:07 -0800] [98104] [INFO] Starting gunicorn 20.0.4 [2021-03-02 11:30:07 -0800] [98104] [INFO] Listening at: http://127.0.0.1:8000 (98104) [2021-03-02 11:30:07 -0800] [98104] [INFO] Using worker: sync [2021-03-02 11:30:07 -0800] [98105] [INFO] Booting worker with pid: 98105 But when I go to my view's endpoint (/run_psql/) the resulting web page is missing the static content ... ... and the server outputs this ... Not Found: /static/rest_framework/css/bootstrap.min.css Not Found: /static/rest_framework/css/bootstrap-tweaks.css Not Found: /static/rest_framework/css/prettify.css Not Found: /static/rest_framework/js/jquery-3.5.1.min.js Not Found: /static/rest_framework/css/default.css Not Found: /static/rest_framework/js/ajax-form.js Not Found: /static/rest_framework/js/csrf.js Not Found: /static/rest_framework/js/bootstrap.min.js Not Found: /static/rest_framework/js/prettify-min.js Not Found: /static/rest_framework/js/default.js Not Found: /static/rest_framework/js/jquery-3.5.1.min.js Not Found: /static/rest_framework/js/ajax-form.js Not Found: /static/rest_framework/js/csrf.js Not Found: /static/rest_framework/js/bootstrap.min.js Not Found: /static/rest_framework/js/prettify-min.js Not Found: /static/rest_framework/js/default.js There are plenty of questions and answers about Django and static content but none of the answers I have read have solved my particular problem. I have this in my settings.py file: import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / … -
dropdownlist is not showing data in template in django updateview
I am new to django class based view. I using updateview. In template I have one dropdownlist and 1 textbox. Textbox is showing data but dropdownlist is showing 5 empty results. I am using seperately get_inital() or get_context_data() method. Both method showing data in debug mode but not showing data in template dropdownlist. I spend many days for solution but didn't succeed. Model : class AreaColonies(models.Model): area = models.ForeignKey(Area,on_delete=models.CASCADE) ColonyName = models.CharField(blank=True, max_length=100) View : class UpdateAreaColony(UpdateView): model = AreaColonies form_class = UpdateAreaColonies template_name = 'MyApp/EditAreaColony.html' success_url = '/MyApp/AreaColonyLists' def get_context_data(self, **kwargs): a = self.kwargs['pk'] context = super(UpdateAreaColony, self).get_context_data(**kwargs) context['id'] = a area = Area.objects.all() arealist = list() arealist.append((0, '-- Select Area --')) for i in area: arealist.append((i.id, i.AreaName)) areaColonies = AreaColonies.objects.get(id=a) context['area'] = arealist context['ColonyName'] = areaColonies.ColonyName return context def get_initial(self): initial = super(UpdateAreaColony, self).get_initial() a = self.kwargs['pk'] initial['id'] = a area = Area.objects.all() arealist = list() arealist.append((0, '-- Select Area --')) for i in area: arealist.append((i.id, i.AreaName)) areaColonies = AreaColonies.objects.get(id=a) initial['area'] = arealist initial['ColonyName'] = areaColonies.ColonyName # print('Area = ',initial['area']) # print('inital = ', initial) return initial Forms.py class UpdateAreaColonies(forms.ModelForm): class Meta: model = AreaColonies fields = '__all__' Template : {% csrf_token %} {{ form.non_field_errors }} <table> <tr> … -
Qual o significado da barra no final da URL?
Estava tendo problema quando estava criando uma API simples no Django REST Framework, e percebi que quando o objeto existe no banco de dados a URL da API precisava de uma barra no final da URL para funcionar, pois estava retornando um 405 Method "DELETE" not allowed ou Method "GET" not allowed. Passei horas para descobrir que esse era o problema de permissão com esses métodos. Minha dúvida seria qual o significado da barra no final da URL? Quando um objeto existir no BD, porque é necessário colocar uma barra "/" no final da URL? -
If you see valid patterns in the file then the issue is probably caused by a circular import.(its not a typo but caused by circular import)
This is very unusual . The code was running fine but all of sudden this error appeared : The included URLconf 'backend.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. My backend.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('base.urls')), ] My base.urls : from django.urls import path from . import views urlpatterns = [ path('', views.getRoutes, name='getRoutes'), ] My base/views.py from django.shortcuts import render from django.http import JsonResponse from .products import products # Create your views here. def getRoutes(request): routes = [ '/api/products/', '/api/products/create/', '/api/products/upload', '/api/products/<id>/reviews/', '/api/products/top/', '/api/products/<id>/', '/api/products/delete/<id>', '/api/products/<update>/<id>/', ] return JsonResponse(routes, safe=False) I am using django for quite long now never seen this error the exact code was running fine but as I define second func in views the error occurred I remove that func but error doesnt go . I have tried all answer please help -
Django interaction with html
Hi there i was learning how to use Django when i reach a tutorial,where the person call variable of other files(views.py) with this {{}}. Can some explain how this html interacts with the views.oy file. A code example could be this one: {% extends 'accounts/main.html'%} {% load static %} {% block content %} <br> <div class="row"> <div class="col_md_6"> <div class="card card-body"> <form action="" method="POST"> <!-- Esto es una manera de mandar datos de manera segura --> {% csrf_token %} {{formset}} <input type="submit" name="submit"> </form> </div> </div> </div> {% endblock%} Why i can make references like {{formset}}? -
Mocking Django Tests - mocked function still executed
I'm writing a basic Django app that integrates with a third party API. Here is the basic folder structure of the files involved: timecardsite/ __init__.py tests/ __init__.py tests.py services.py views.py ... The services.py file contains various functions that interact with the third party API directly. They typically return dictionaries with the data I need to use in the views. In my tests file, specifically in the class where I test the views, I'm trying to mock the return value of a few of these service functions, so ideally they won't even be called (I test the service functions directly in another class): tests.py from unittest.mock import patch from django.test import TestCase import timecardsite.services as services from timecardsite.models import Account ... class ViewsTests(TestCase): @patch('timecardsite.views.services.get_access_token') @patch('timecardsite.views.services.get_account_info') def test_auth_view_saves_tokens_and_account_info_to_db(self, mock_access, mock_account): # Mock both get_access_token and get_account_info code = generate_random_token() access_token = generate_random_token() refresh_token = generate_random_token() account_id = generate_random_token(length=5) name = 'Example name' mock_access.return_value = { 'access_token': access_token, 'refresh_token': refresh_token } mock_account.return_value = { 'account_id': account_id, 'name': name } self.client.get(f'/auth/?code={code}') self.assertEqual(Account.objects.count(), 1) new_account = Account.objects.first() self.assertEqual(new_account.account_id, account_id) self.assertEqual(new_account.name, name) self.assertEqual(new_account.access_token, access_token) self.assertEqual(new_account.refresh_token, refresh_token) The view where these functions are called: views.py from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse import timecardsite.services as … -
I cant sign in on my website even tho sign up works. Error says Value error
Hey guys I'm just getting an error thrown up at me when I go to sign in on my Django project I was just wondering could anyone help shed some light as to what the error is. Ill include both my views and URLs below. I assume this is where the error must be but I'm unsure so apologies if I have not provided the right code. I will also include my templates. Urls from django.urls import path from phoneshop import views from .views import signupView, signinView, signoutView urlpatterns = [ path('create/', signupView, name='signup'), path('login/', signinView, name='signin'), path('logout/', signoutView, name='signout'), ] views from django.shortcuts import render, redirect from .forms import CustomUserCreationForm from .models import CustomUser from django.contrib.auth.models import Group from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, authenticate, logout def signupView(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') signup_user = CustomUser.objects.get(username=username) customer_group = Group.objects.get(name='Customer') customer_group.user_set.add(signup_user) else: form = CustomUserCreationForm() return render(request, 'signup.html', {'form':form}) def signinView(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('phoneshop:allProdCat') else: return redirect('signup') else: form = AuthenticationForm() return render(request, 'signin.html', {'form': … -
DRF SerializerMethodField not updating the DateTimeField
I have a TaskUpdateSerializer that should be converting received date from format to another then update this date "converted date" but I've noticed that django not complaining or raising any errors when i pass invalid date data to it and also not updating the data name field update works fine except deadline field serializers.py class TaskUpdateSerializer(serializers.ModelSerializer): deadline = serializers.SerializerMethodField(read_only=True) class Meta: model = Task fields = ['name', 'deadline'] def get_deadline(self, obj): deadline = self.context['request'].data.get('deadline') # try to convert deadline if its in Wed, Mar 10, 2021 7:19 PM format try: # convert giving date to datetime in this format Wed, Mar 10, 2021 7:19 PM d = datetime.strptime(deadline, '%a, %b %d, %Y %I:%M %p') # convert it to 2021-3-10 7:48:22 format r = d.strftime("%Y-%m-%d %I:%M:%S") return r # or return "blabla" works fine also except Exception as E: print(E) return obj.deadline views.py class TaskUpdate(RetrieveUpdateAPIView): serializer_class = serializers.TaskUpdateSerializer lookup_url_kwarg = 'task_id' queryset = Task.objects.all() models.py class Task(models.Model): name = models.CharField(max_length=256) started = models.DateTimeField(default=timezone.now, editable=False) deadline = models.DateTimeField() -
Don't see data from django in reactjs frontend
I am new at react. And I am building django + react web-application Full code of the project https://github.com/mascai/django_examples/tree/master/02_django_react When I make request to http://127.0.0.1:8001/api/lead/ i see valid data from Django. But whe I go to http://127.0.0.1:8001 I don't see don't see any data. I think that problem with frontend side. index.js import React, { Component } from 'react'; import { render } from "react-dom"; class App extends Component { constructor(props) { super(props); this.state = { data: [], loaded: false, placeholder: "Loading" }; } componentDidMount() { fetch("api/lead") .then(response => { if (response.status > 400) { return this.setState(() => { return { placeholder: "Something went wrong!" }; }); } return response.json(); }) .then(data => { this.setState(() => { return { data, loaded: true }; }); }); } render() { return ( <ul> {this.state.data.map(contact => { return ( <li key={contact.id}> {contact.name} - {contact.email} </li> ); })} </ul> ); } } export default App; const container = document.getElementById("app"); render(<App />, container); index.html (seems fine) <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Django REST with React </head> <body> <div id="app"> <!-- React will load here --> </div> </body> {% load static %} <script src="{% static "frontend/main.js" %}"></script> </html> -
My Django app does not recognize my MySQL Database
So I have cloned a work project in my Kubuntu operation system, I have been working perfectly in Windows with all of this, but now this error appears when I launch the runserver Django command in Ubuntu: django.db.utils.OperationalError: (1049, "Unknown database 'NLPWords'") I have searched and people say I have to create the database in MySQL, so I did it: mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | NLPWords | | information_schema | | mysql | | performance_schema | | sys | +--------------------+ My database is the NLPWords my Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'NLPWords', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 3306, } } I have downloaded DBeaver to see the tables but I can't manage to see them, and I can't run nor makemigrations nor any other command in my Django app. Help is much appreciated -
"App not compatible with buildpack" error during deployment of django app to heroku
I try to deploy my first django app to heroku. During deployment i get the error: remote: -----> Building on the Heroku-20 stack remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure I met recomendation to update the detect script of builpack and use this: if [ ! -f "$BUILD_DIR/requirements.txt" ] && [ ! -f "$BUILD_DIR/setup.py" ] && [ ! -f "$BUILD_DIR/Pipfile" ]; then exit 1 fi but i don't know where this script is situated and how to get acces to it. Could you tell me, how to use it? -
How to add pagination to APIView class in Django Rest Framework
I need a pagination limit of 10 for the below code, I tried many solutions with offset and page number pagination , but no luck class EmpView(APIView): permission_classes = (permissions.IsAuthenticated,) @swagger_auto_schema( responses={status.HTTP_200_OK: []}, operation_id="emp_comments", ) def get(self, request, *args, **kwargs): user = request.user response = {} community_users = list(Employee.objects.filter(to_user=user).values_list('from_user__id', flat=True)) flag=kwargs['flag'] if flag =='rec': qs = list(EmpComments.objects.filter(user_id__in=community_users, parent_id__isnull=True,comment_text__length__gte=125) recent_comments = get_recent_comments(qs, request.user) response["recently_discussed"] = recent_comments if flag =='top': qs = list(EmpComments.objects.filter(user_id__in=community_users).exclude(upvote__exact=0) top_comments = get_recent_comments(qs, request.user) response["top_comments"] = featured_comments + top_comments return Response(response) -
should I write model as recursion relation for Django-mptt work?
mptt package to create hierarchies questions, I have a problem with it, should I write my model relation as recursion? or It works with other tree structures?? class Question(MPTTModel): question_text = models.TextField() parent = TreeManyToManyField('Answers', blank=True, related_name='children') class Answers(MPTTModel): value = models.CharField(max_length=60) parent = TreeForeignKey('Question', on_delete=models.CASCADE, related_name='children') Then I wanna get children It returns an empty list Question.objects.all().first().get_children() result: <TreeQuerySet []> what should I do? -
DJANGO python error return qs._result_cache[0]
Im new using Django, Im coding for an ecommerce and everything is working as expected but an error raised even when the code is working! Sorry for spanglish: id = request.POST.get('id') tamano = request.POST.get('size') items = request.POST.get('items') precio = request.POST.get('prize') urlFoto = Producto.objects.filter(id=id).values("urlFoto") nombre = Producto.objects.filter(id=id).values("nombre") item = ItemCarrito(id, tamano, items, precio, urlFoto[0]['urlFoto'], nombre[0]['nombre']) print(item) controlCambio=False if request.session.get('lista'): lista = request.session.get('lista') for posicion in range(0, len(lista)) : if lista[posicion].idItem == id and lista[posicion].variante1 == tamano: lista[posicion].unidades = int(item.unidades) + int(lista[posicion].unidades) print("HAY IGUALES") controlCambio=True if controlCambio==False: lista.append(item) else: lista = [] lista.append(item) request.session["lista"] = lista sumaPrecioCarrito(request, precio) return detalleProducto(request, id) The error appears in this line: item = ItemCarrito(id, tamano, items, precio, urlFoto[0]['urlFoto'], nombre[0]['nombre']) And it says: return qs._result_cache[0] IndexError: list index out of range In that line I only create the object ITEM which constructor is: class ItemCarrito: def __init__(self, idItem, variante, unidades, precio, urlFoto, nombre): self.idItem = idItem self.variante1 = variante self.unidades = unidades self.precio = precio self.urlFoto = urlFoto self.nombre = nombre Do you have some ideas of why this error is appearing but everything is working well? -
How do I create number of days to go progress bar on django
Please I've an App I created, and I'm finding it hard to add progress bar count down for days to go before the user get what they Applied for? I used the formula now - start time / end time - now + now - start time all in days, seems to work pretty well but things get awkward when the month number changes... Please any help -
Django admin - users username field shows my email instead of username
I have a User modal with username and email fields. I use postgresql. For every user in the admin panel my email is shown on the Username field on the production version of the app (AWS). Locally this is not the case. In the database the usernames are shown correct. In admin.py I simply have: admin.site.register(User) Does anyone have an idea why this is the case on production and not local? And how to fix this. -
Error: Django Framework : NoReverseMatch at /accounts/create/ 'shop' is not a registered namespace
I seem to be getting the error mentioned in the title: "NoReverseMatch at /accounts/create/ 'shop' is not a registered namespace" This is my base.html file which is saying is the route of the error: Error during template rendering In template C:\Users\conor\djangoprojects\sem4proh01march\phoneshop\templates\base.html, error at line 24 'shop' is not a registered namespace base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/custom.css' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <meta name="description" content="{% block metadescription %}{% endblock %}"> <title>{% block title %}{% endblock %}</title> </head> <body> <div class="container"> {% include 'header.html' %} {% include 'navbar.html' %} {% block content %} {% endblock %} {% include 'footer.html' %} </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> </body> </html> Any help would be greatly appreciated. Thanks in advance. -
How can I make Backends for reset password from auth lib
in reset password form, from auth lib, It has conditions that must be more than 8 characters and .. path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name = "account/forget/password_reset_form.html"), name ='password_reset_confirm'), how can i make backends to save password immediately, No auth conditions -
Delete optional foreign key in Django Admin
I have a model with a foreign key to an instance of "Widget". This model instance can be created only from the creation (Or editing) of an instance of my "Course" model. From here, I can only create a new instance of "Widget" but there is cross icon to delete it, nor the delete button when editing. This is part of my models.py class CoinWidget(models.Model): name = models.CharField(max_length=100) symbol = models.CharField(max_length=10) def __str__(self): return self.name class Course(models.Model): ... widget = models.ForeignKey( CoinWidget, on_delete=models.CASCADE, related_name='course', blank=True, null=True, ) ... And this is part of my current admin.py. @admin.register(Course) class CourseAdmin(admin.ModelAdmin): ... fieldsets = ( ('Course information', { 'fields': (...'widget') }), ... @admin.register(Reward) class RewardAdmin(admin.ModelAdmin): def has_module_permission(self, request): return False I tried with has_delete_permission() method returning True, but when I do this, I can only delete that instance directly in /admin/app/model, what I need is be able to delete directly in the "Course" instance. I'm sorry for my bad english. Suggestions would be appreciated. -
Geodjango/GDAL: SRS 6257 not recognized
I'm using geodjango and am trying to transform coordinate systems using CoordTransform. This works well for nearly all cases. However, I just found one particular shapefile that fails. This shapefile uses "MAGNA-SIRGAS / Medellin urban grid", which for all that I can see is a valid EPSG reference system with code 6257. However, whatever I try I get an error saying that this is an "Unsupported SRS.". When I try other codes, it works just fine. It says "GCS code 6257 not found in EPSG support files". But why would it not be found if it is a valid code? Examples: sr = SpatialReference("WGS84") # all good sr = SpatialReference(4143) # all good sr = SpatialReference(2165) # all good sr = SpatialReference(2043) # all good sr = SpatialReference(6257) # GDAL_ERROR 6: b'EPSG PCS/GCS code 6257 not found in EPSG support files. Is this a valid EPSG coordinate system?' -
Error Django 2.2.9 Query whitout apostrophe
When I make a query like this in my view. filter(address__icontains=city) the sql query show me something like this: .`address` LIKE %Mountain View%) The correct way is like this using 'something' .`address` LIKE '%Mountain View%') -
Error While Deploying Django with Jenkins
I have created a new job in Jenkins. After build getting an error on the console output. Using base prefix '/usr' New python executable in /var/www/project/venv/bin/python3 Not overwriting existing python script /var/www/project/venv/bin/python (you must use /var/www/project/venv/bin/python3) Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/virtualenv.py", line 2327, in <module> main() File "/usr/lib/python2.7/site-packages/virtualenv.py", line 712, in main symlink=options.symlink) File "/usr/lib/python2.7/site-packages/virtualenv.py", line 926, in create_environment install_distutils(home_dir) File "/usr/lib/python2.7/site-packages/virtualenv.py", line 1482, in install_distutils mkdir(distutils_path) File "/usr/lib/python2.7/site-packages/virtualenv.py", line 323, in mkdir os.makedirs(path) File "/usr/lib64/python3.6/os.py", line 220, in makedirs mkdir(name, mode) FileExistsError: [Errno 17] File exists: '/var/www/project/venv/lib64/python3.6/distutils' Running virtualenv with interpreter /bin/python3 Jenkins Exec Commands: rm -rf /var/www/project/*.* touch /var/www/project/debug.log cp -rf /home/centos/build/* /var/www/project/ cd /var/www/project virtualenv -p python3 venv source venv/bin/activate pip3 install -r requirements.txt sudo ln -sf /opt/project/.env /var/www/project/mysite/ python3 mysite/manage.py collectstatic --noinput python3 mysite/manage.py makemigrations --noinput python3 mysite/manage.py migrate --noinput sudo chown -R centos.centos /var/www/project/* sudo /usr/sbin/service httpd restart -
python manage.py makemigrations django doesn't create all the fields
I have one question when I am doing python manage.py makemigrations django doesn't create all the fields for the Todo Model, please help what's wrong here? class Todo(models.Model): task = models.CharField(max_length=255) title = models.CharField(max_length=100), _date = models.CharField(max_length=100), categories = models.CharField(max_length=100), keywords = models.CharField(max_length=100), summary = models.TextField(), description = models.TextField() Migration Model class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Todo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('task', models.CharField(max_length=255)), ('description', models.TextField()), ], ), ] -
Method Not Allowed (POST) when trying to use Selenium
I'm trying to get this django app to work with selenium but it's just not working at all. The code is kind of messy right now since I'm trying to figure out how to do what I need to do (I have to write a web scraping script with Selenium that get's the person's commercial id number in this site from the goverment and once they type it, right under should appear the name and last name of the person corresponding to the id that's available in one of the goverment's api. I honestly have no idea how to do this so I'm trying). The thing now is that I keep getting Method Not Allowed (POST): /constancia-inscripcion and Method Not Allowed: /constancia-inscripcion (405) everytime I submit a random number to the form. I think the error could be anywhere, to be honest, so I need some help to find it. This is my view: from django.shortcuts import render, HttpResponse import requests from django.views import View from selenium import webdriver class ConstanciaInscripcion(View): DRIVER_PATH = 'C:/Users/micae/Documents/python/chromedriver.exe' driver = webdriver.Chrome(executable_path='C:/Users/micae/Documents/python/chromedriver.exe') driver.get('https://seti.afip.gob.ar/padron-puc-constancia-internet/ConsultaConstanciaAction.do') def get(self, request): return render(request, 'app/constancia-inscripcion.html') def cuit(request): information = [] if request.method == 'POST': driver.find_element_by_xpath("//label[@class='cuit']/input[@class='word' and @type='text' and @value='']").click() driver.find_element_by_xpath("//label[@class='cuit']/input[@class='word' and …