Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to redirect to new page Django
I am new to Django. I am building a multiple page website via Django. on the main page I am using an onclick event and passing the data to views.py via AJAX. the issue is that in the command prompt everything is running smoothly. the function to which Ajax call was made is being called. the data is being fetched but the URL is not changing. If we copy the URL from new URL from cmd and paste it in browser window, it is working the way it is suppose to work. Can someone tell me what might the issue. -
where the Filed class import from in the serializers.py of restframework
The source code of rest_framework/serializers.py is class BaseSerializer(Field): But It does not declare where the Field import in this file. -
Django compare two queryset and append custom object
I have two models class Position(models.Model): ... job_seekers = models.ManyToManyField(settings.AUTH_USER_MODEL) class Applicants(models.Model): position = models.ForeignKey(Position, on_delete=models.CASCADE) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) I am trying to append a custom variable "selected" to my queryset to track users who appear in both the job_seekers ManytoMany field and the Applicants model using the following code. views.py position = get_object_or_404(Position, pk=self.object.pk) applicants = Applicant.objects.filter(position=position) result_list = position.job_seekers.annotate(selected=F(applicant__user)) so I can highlight selected users in my templates with something like {% if applicant.pk == applicant.selected %} How can I do this without having to change the database structure? Thanks -
Why my Django admin is not loading with css?
I have developed a web app in Djnago and deployed it then I found out that admin page is not loading with CSS. I was gettting the admin page with css in local server but not when I deployed it. [django-admin pic][1] [1]: https://i.stack.imgur.com/alHIF.png Even after using python manage.py collectstatic It's not loading with css. Here is my settings.py code from pathlib import Path import os BASE_DIR = Path(__file__).resolve(strict=True).parent.parent Here is the static files linkage part: STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'first_app/media') I am not able to figure out why it's not linking the css part even after the above code Django version: 3.1 Python version : 3.8.3 Please could anyone help me out in this Thank you -
Different input and output serializers for django class-based views
I'm currently writing views to list the objects that I have. But I want to have some custom query parameters so that I can filter the querysets in the get_queryset() function. So I created a serializer for the query parameters like this: class IceCreamFilterSerializer(serializers.Serializer): start = serializers.DateField() end = seralizers.DateField() Then for the views I used method_decorator to add the query parameters to my views like this: @method_decorator(name='list', decorator=swagger_auto_schema( manual_parameters=[ openapi.Parameter('start', openapi.IN_QUERY, type=openapi.TYPE_STRING), openapi.Parameter('end', openapi.IN_QUERY, type=openapi.TYPE_STRING) ] )) class IceCream(ListModelMixin, GenericViewSet): serializer_class = IceCreamSerializer def get_queryset(self): filter_data = IceCreamFilterSerializer(data=self.request.query_params) start = filter_data['start'] end = filter_data['end'] qs = IceCream.objects.filter(created__range=[start, end]) return qs So I have two different serializers for the query parameters and for the output data. I need to differentiate the input and output serializers, but I have multiple views with this functionality. So I want to create a Mixin that manages the serializers so I can inherit it in my views. However I'm not sure what to write in the Mixin. Do I override the get_serializer_class? I have read this SO thread but I don't think this is what I want. Can you guys point me to the right direction? I'm kinda new to this Mixin thing. Any help … -
Django - Datatables ajax error with rest framework
I'm trying to use rest in conjunction with Datatables to display a large list with server-side processing. On the datatable html template i get an empty table with an error "DataTables warning: table id=bib - Ajax error. For more information about this error, please see http://datatables.net/tn/7"" urls.py from . import views as v from rest_framework import routers router = routers.DefaultRouter() router.register(r'Bibrest51', v.BibViewSet) urlpatterns = [ path('home/', include(router.urls)), path('home/', v.home, name='home'), path('', v.home, name='home'), views.py class Get_bib(viewsets.ModelViewSet): queryset = Bibrest51.objects.all() serializer_class = BibSerializer home.html <table id="bib" class="table table-striped table-bordered" style="width:100%" data-server-side="true" data-ajax="/home/Bibrest51/?format=datatables"> <thead> <tr> <th data-data="autor" class ="text-center all">Autor</th> <th data-data="ano" class ="text-center all">Ano</th> <th>Título</th> <th data-data="tipo" class ="text-center not-mobile">Tipo</th> <th data-data="tema" class ="text-center not-mobile">Tema</th> </tr> </thead> <tbody> </tbody> </table> JS: <script> $(document).ready(function() { $('#bib').DataTable(); }); </script> models.py class Bibrest51(models.Model): cadastro_id = models.AutoField(primary_key=True) autor = models.CharField(db_column='Autor', max_length=255) ano = models.CharField(db_column='Ano', max_length=255) titulo = models.CharField(db_column='Titulo', max_length=255) referencia = models.CharField(db_column='Referencia', max_length=255) serializers.py from rest_framework import serializers from .models import Bibrest51 class BibSerializer(serializers.ModelSerializer): class Meta: model = Bibrest51 fields = ['autor', 'ano','tipo','tema'] -
Sending large dictionary via API call breaks development server
I am running a django app with a postgreSQL database and I am trying to send a very large dictionary (consisting of time-series data) to the database. My goal is to write my data into the DB as fast as possible. I am using the library requests to send the data via an API-call (built with django REST): My API-view is simple: @api_view(["POST"]) def CreateDummy(request): for elem, ts in request.data['time_series'] : TimeSeries.objects.create(data_json=ts) msg = {"detail": "Created successfully"} return Response(msg, status=status.HTTP_201_CREATED) request.data['time_series'] is a huge dictionary structured like this: {Building1: {1:123, 2: 345, 4:567 .... 31536000: 2345}, .... Building30: {..... }} That means I am having 30 keys with 30 values, whereas the values are each a dict with 31536000 elements. My API request looks like this (where data is my dictionary described above): payload = { "time_series": data, } requests.request( "post", url=endpoint, json=payload ) The code saves the time-series data to a jsonb-field in the backend. Now that works if I only loop over the first 4 elements of the dictionary. I can get that data in in about 1minute. But when I loop over the whole dict, my development server shuts down. I guess it's because the memory is … -
The current path, imageupload, didn't match any of these, Page not Found Django
I am new to Django and I am trying to build an image classifier app, I just tried building the app but I am getting this error, how may I resolve it? Page not found (404) Request Method: GET Request URL: http://localhost:8000/imageupload Using the URLconf defined in imageclassifier.urls, Django tried these URL patterns, in this order: imageupload ^$ [name='home'] admin/ The current path, imageupload, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. These are all changes I made in my app: This is the views.py file in imgUpload app from django.shortcuts import render # Create your views here. def home(request): return render(request, 'home.html') This is the urls.py file in imageUpload app from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('^$', views.home, name ='home'), ] And this is the urls.py in the Imageclassifier folder: """imageclassifier URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') … -
Error on deploying django app to Heroku -- TypeError: argument of type 'PosixPath' is not iterable
This is my first django project and I get this error when trying to deploy. It would be really appreciated if someone could help me with this. TypeError: argument of type 'PosixPath' is not iterable Error while running '$ python manage.py collectstatic --noinput'. $ python manage.py collectstatic --noinput remote: 122 static files copied to '/tmp/build_92e98a8b/staticfiles'. remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 329, in run_from_argv remote: connections.close_all() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 225, in close_all remote: connection.close() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 190, in close remote: if not self.is_in_memory_db(): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 280, in is_in_memory_db remote: return self.creation.is_in_memory_db(self.settings_dict['NAME']) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db remote: return database_name == ':memory:' or 'mode=memory' in database_name remote: TypeError: argument of type 'PosixPath' is not iterable remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: … -
Using social-auth-app-django for Azure Active Directory authentication and DRF
It could be my approach is just entirely wrong and if so, being corrected would be greatly appreciated. Basically, I need to authenticate company users of the /admin portal in development against the company's Azure Active Directory. They are the only ones who should be able to access it. There are two approaches, as it was explained to me: OAuth for Servers: usually used when the app needs to access user data when they are not logged in. OAuth for Browser Apps: usually used when the app needs to access user data while they are logged in. Based on this, I went with 1, and decided to give python-social-auth, social-auth-app-django and the Microsoft Azure Active Directory a try. The examples are pretty old and it seems like I'm just missing something in the documentation to get it working. I'm using DRF, and aside from /api/admin (the Django Admin Portal), no static assets are being served by Django at all. The ReactJS FE is an entirely separate service. So an oversimplification of what should happen is: User navigates to https://example.com/ ReactJS automatically sends request to https://example.com/api/users/auth/aad/login User is presented with Microsoft login screen This is all I have so far: # … -
Getting comments for a post by certain users in Django using Postgre
I have two models Post and Comment. My users are able to build friendships with one another. I want to write a method that from a certain queryset of posts if the user's friends have commented on that post it will by consuming as less memory as possible. My models are: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(validators=[MaxLengthValidator(1200)]) author = models.ForeignKey(Profile, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') author = models.ForeignKey(Profile, on_delete=models.CASCADE) body = models.TextField(validators=[MaxLengthValidator(350)]) created_on = models.DateTimeField(auto_now_add=True) now assuming I have a list of user id's which are friends with request.user By: friends = Friend.objects.friends(request.user) and I have a queryset of posts: posts = Post.objects.select_related("author").filter(author__in=friends).order_by('-date_posted') I can get the comment id of each post by: post.comments.values('id').select_related('author').filter(author__in=friends).order_by('-created-on')[:2] However, if I want to do this for hundreds of post it will be extremely expensive. How can I get the last two comments by a users friends from each post as fast as possible by using the least memory? -
Serializer for fetchiing data from multiple classes
Environment is Python and Django3 I want to make api which retrieve the data from multiple model class. I have models like this , each CountryStat has Country. class Country(models.Model): code = models.CharField(max_length=3,unique=True) name = models.CharField(max_length=50) class CountryStat((models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE,null=True) date = models.DateField(null=True,blank =True) stat = models.IntegerField() Now I want to get the latest Coutry Stat for each Country. So I made the serializer for Country class CountrySerializer(serializers.ModelSerializer): latest_stat = serializers.SerializerMethodField() class Meta: model = Country fields = ('id','code','latest_stat') def get_latest_stat(self,obj): # how can I get the latest stat from CountryStat model ???? Is this the correct idea or how can I make it?? -
How to adding PDF for Admin to view Orders
I have tried to add the option to view order through PDF in the admin panel but I am getting error which I do not know the reason for nor how to fix it. This is what I did step by step. The issue is now that I have tried restart everything but I am still getting the error and can't get the server to start. $ pip install weasyprint django-import-export then I added it in the installed apps 'import_export', Here is the admin.py def order_pdf(obj): return mark_safe('<a href="{}">PDF</a>'.format(reverse('orders:admin_order_pdf', args=[obj.id]))) order_pdf.short_description = 'Order PDF' class OrderAdmin(ImportExportActionModelAdmin): list_display = ['id', order_pdf] here is the views.py @staff_member_required def admin_order_pdf(request,order_id): Order = get_object_or_404(order,id=order_id) html = render_to_string('order/pdf.html',{'order':Order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) # weasyprint.HTML(string=html).write_pdf(response,stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]) weasyprint.HTML(string=html).write_pdf(response,stylesheets=[weasyprint.CSS(settings.STATIC_ROOT)]) return response here is the url.py path('admin/order/(?P<order_id>\d+)/pdf/$', views.admin_order_pdf, name='admin_order_pdf') Here is the traceback Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\commands\runserver.py", line 95, in … -
How do I add Reverse for 'account_login'
Error during template rendering. In template /Library/Framework/Python.framework/versions/3.8/lib/python3.8/site-packages/allauth/templates/base.HTML, error at line 29 Reverse for 'account_login' not found. -
ImportError: cannot import name 'EMPTY_VALUES' from 'django.forms.fields'
I installed djangocms in existing django project, following the instructions: http://docs.django-cms.org/en/latest/how_to/install.html but when I run py manage.py cms check or py manage.py migrate I have this error: File "C:\Users\usuario\Envs\env_cuid_lab\lib\site-packages\cms\forms\fields.py", line 4, in from django.forms.fields import EMPTY_VALUES ImportError: cannot import name 'EMPTY_VALUES' from 'django.forms.fields' (C:\Users\usuario\Envs\env_cuid_lab\lib\site-packages\django\forms\fields.py) -
How can I make a search form working with "Name Surname"
Basically the issue is that at the moment my search bar is working if I search the exact "Name" or the exact "Surname", however, I would like it to work also if a user searches "Name Surname" or even if the user misspells the name or the surname but at least one of the two is correct. def search(request): query = request.GET.get("q", None) qs = DeathAd.objects.all() if query is not None: qs = qs.filter( Q(nome__icontains=query) | Q(cognome__icontains=query) ) context = { "object_list": qs, } template = "search.html" return render(request, template, context) -
websolr/heroku/django: How to set up solr as a separate service
I am trying to deploy my Django app on Heroku that uses calls to solr to field user queries. I added websolr as an addon to Heroku, but the websolr docs only describe how to configure clients like Django-Haystack. Since my app has users searching a static index and not Django models that need to be updated, and I already have schema.xml, solrconfig.xml, etc. and a json file to index that I know works, I don't want to try to recreate this using Django models for no reason. How do I get websolr to run solr based on these files that I provide instead of embedded to my app through a client? -
Can't log into a commandline created superuser using Django but account gets created
I have created a superuser that i can't log into, using the docker-compose.yml commands: sh -c "sleep 5 && #<snip> echo A-fj... create superuser acct... && echo DJANGO_SUPERUSER_PASSWORD=$DJANGO_SUPERUSER_PASSWORD && echo DJANGO_SUPERUSER_EMAIL=$DJANGO_SUPERUSER_EMAIL && echo DJANGO_SUPERUSER_USERNAME=$DJANGO_SUPERUSER_USERNAME && python manage.py createsuperuser --noinput --username $DJANGO_SUPERUSER_USERNAME --email $DJANGO_SUPERUSER_EMAIL && echo Z-fj... create superuser acct... done. && #<snip> sleep 5 " The environment variables display perfectly, and an account gets created that i can see in the db using dBeaver. When i manually add a second user via "$python manage.py createsuperuser" dialog, i end up with an account that i can log into. When i copy the password from User2 to User1, i can then log into User1 using User2 password, so it seems to be a password thing. When i compare the passwords from User1(orig) and User2(new), they look to be different formats... see the screenshot. I'm not sure, but thinking it may be a clue to the problem... Password1 is shorter and has no sections where Password2 is longer... Password1: !GSU8f8hmNOl1oJBfe1Epk7ocJiXXWQQp3G0mh9TC Password2: pbkdf2_sha256$120000$IAkHkB3ME9aB$p0hrZPkLeSWK0IafqVQ1dEtR5kgBol7WnU7QELoo6KE= I've tried a few different passwords, just in case, but no go -
How can we build robust follow system in website by djnago?
Well if you are django user and build follow system on website than please answer that with code for new students who start learning django like me. Many many thanks in advance who will answer this question. -
Trying to load a ML model in Django in order to classify user submitted images
I have made a small image classifier that I want to use in my website. I have it working locally. My view is something a long the lines of from .predict import classify def index(request): if request.method == 'POST': form = MyImageClass(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data context = classify(cd) return render(request, 'my_html.html', context) ... Where the problem is in predict.py, I have def classify(cd): loaded_model = tf.keras.model.load_model(filepath=r'C:\Django Projects\my_project\my_app\trained_model') ... return context As I said, the above works, but I would like to be able to load the model with a relative file path instead. I have tried both saving as a SavedModel and as an h5 file as done here. When I run tf.keras.model.load_model('my_model.h5') (say in main.py) in python, I have no problem with the file being in the same directory as the file main.py, but if I have the same code as part of predict.classify, I get OSError: SavedModel file does not exist at my_model.h5/{saved_model.pbtxt|saved_model.pb} while using my website via py manage.py runserver. I'm guessing the issue might have to do with static files? I'm not too sure. Any help would be greatly appreciated. -
Only show in Django Admin the facilities that belong to the customer for which the work order is being created
In myApp I have a Client who owns different ClientFacility. I also have a Project which is done for a Client. In addition I have Orders that belong to a Project (and indirectly to a Client). The Orders for a Project will be performed only on ClientFacility owned by the customer associated to the Project. I was trying to understand the filtering of many to many on this question but I couldn't because I don't know how to get my project_number dynamically In myApp admin section (http://127.0.0.1:8000/admin/myApp/), every time I create an Order, I would like to show only the ClientFacilities associated with the Client of the Project the Order belongs to. How can I do this and on which .py of myApp? Right now the ManyToManyField displays every single ClientFacility on my database which is not adequate. If the way in which I have established the relationships between my models is not correct it is fine, I want to learn. Please provide some guidelines, links, examples, etc instead of saying this is all wrong and it has to be changed. This is my code: class Project(models.Model): project_number = models.IntegerField(unique=True,primary_key=True) project_name = models.CharField(max_length=400) client = models.ForeignKey("Client", on_delete=models.CASCADE,verbose_name = "Customer of … -
Django (Models): Automatically pick and return a value by the choice option
I'm building a simple sys which selects a link by given value. So imagine a user is posting a post and he has to select the type of the post for example (old, new, classic). And this is what I've got right now: MarkerIcons = ( # We can choose between: ('0', _('https://i.imgur.com/U8ddIZs.png')), # POLICE CAR2 (InUse) ('1', _('https://i.imgur.com/ec2VbzA.png')), # POLICE RAID ('2', _('https://i.imgur.com/kM9Ppou.png')), # PASSENGER_CONTROL # Camera's ('3', _('https://i.imgur.com/VDUPhLx.png')), # TRIPOD ('4', _('https://i.imgur.com/MpiJ8st.png')), # SPEED CAMERA & other img - https://i.imgur.com/EbItaVR.png # Extra's- ('5', _('https://i.imgur.com/w00r7kC.png')), # ACCIDENT ('6', _('https://i.imgur.com/fykUX9D.png')), # TRAFFIC JAM ('7', _('https://i.imgur.com/ooZDKug.png')), # CONSTRUCTION_WORK ('8', _('CAR_STOPPED')), # ('9', _('OTHER')), # ('10', _('UNKNOWN')) # ) This is what I'm trying to use to automatically return the link from the choices. marker_icon = models.CharField(choices=MarkerIcons, blank=False, null=False, max_length="40", default='0') What's the correct method to select and insert the link of the choices to the Database? I want to do something like this: If the CharField default or given value is - "2", I set the current model Charfield value to 'https://i.imgur.com/kM9Ppou.png' But this does not work as it should, In the previous attempts I was using IntegerField, but I realized that IntegerField couldn't store link because it's a string. This … -
Mocking returns magicmock object instead of return value python django?
I am trying to mock an external HTTP request but for some reason instead of the return value, it returns a magic mock object.Also,can someone guide me on how I can avoid passing actual headers and pass some mock object for headers. This is what I have tried so far app1/utils/ def send_sms(url,headers,data): response = requests.post(url, headers=headers, data=data) content = response.content return content app1/tests @patch('app1.utils.requests') def test_at_sms(self,mock_obj): data = { 'username': 'sandbox', 'to': '+28292992929', 'message': 'Hello', } fake_data = {'hello':'world'} mock_obj.return_value.content.return_value = fake_data headers = {'apikey': 'aydkdjkfdjdfjf', 'content-type': 'application/x-www-form-urlencoded', 'accept': 'application/json'} r = send_sms('https://api.sandbox.africastalking.com/version1/messaging', headers, data) self.assertEqual(r,fake_data) This is what I receive AssertionError: <MagicMock name='requests.post().content' id='139645974661872'> != {'hello': 'world'} -
ModuleNotFoundError: No module named 'my_app’, app already in INSTALLED_APPS
I’m trying to deploy my Django app through Heroku but I’m getting a ModuleNotFound error after running a production environment with gunicorn wsgi path. My app is included in settings.py and it was working fine while in the development environment. But now I’m getting errors for deployment. I have problems with how my project is structured, thus Procfile does not leave in the same directory as manage.py, and I believe this could be the issue. Any hint or help is more than appreciated. Directory structure >FINALPROJECT(root) > .vscode > project5 > brainSkills > migrations > static > templates apps.py models.py urls.py views.py > project5 _init_.py settings.py wsgi.py _init_.py manage.py > venv .env .gitignore Procfile README.md requirements.txt Procfile web: gunicorn project5.project5.wsgi wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project5.project5.settings') application = get_wsgi_application() setting.py import os from pathlib import Path from dotenv import load_dotenv INSTALLED_APPS = [ 'brainSkills', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ROOT_URLCONF = 'project5.urls' WSGI_APPLICATION = 'project5.wsgi.application' Error after gunicorn project5.project5.wsgi or Heroku local 5:32:28 PM web.1 | File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module 5:32:28 PM web.1 | return _bootstrap._gcd_import(name[level:], package, level) 5:32:28 PM web.1 | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 5:32:28 PM web.1 | … -
Requests is not working in one of my DJANGO project
I am having trouble with requests package and I tried my best to resolve this problem. Problem- requests is not working in one of my Django Projects. It returns 403 Forbidden. But the same code is working on my other Django Project (Same laptop with same internet connection, but different virtual environment). So, because of this I am not able to use requests package in one of my existing Django Project. Here is the code: This is the demo code which I will run on two Django Project with two different virtual environment. import requests from bs4 import BeautifulSoup from django.shortcuts import render # from .models import RequestData def home(request): data = [] urls = [ "https://api.github.com/search/repositories", "https://www.dataquest.io", "https://www.python.org", "https://api.github.com/events" ] for url in urls: r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') if soup.title: data.append(str(soup.title)) else: data.append("No Title") return render(request, "requester/index.html", {'data': data}) Here is my HTML part: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% for dat in data %} <li>{{dat}}</li> {% endfor %} </body> </html> Here are my responses from both the Django project. First (Which have problem) Second(Without any problem) Also, I tried with different versions of …