Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to solve this problem in virtual environment?
i want to activate my models in my files, my code in terminal: (env) PS C:\Users\MadYar\Desktop\code.py\learning_log> python manage.py makemigrations learning_logs error: No changes detected in app 'learning_logs' im using django to make a web application and i add models in my settings.py like that: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learning_logs' ] i dont know why it sais no changes detected in app 'learning_logs' -
Django admin interface missing css styling in dokerize django production
The user interface is working well, and all CSS styling and static files are served correctly, but the admin interface is missing CSS styling. I looked at similar posts but in those posts, people had the issue with both the user and the admin interface. My issue is only with the admin interface. Please see my static file settings below from settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Docker File: FROM python:3.8.5-slim WORKDIR /app COPY ./requirements.txt . RUN apt-get update && apt-get install -y gcc openssh-server libev-dev default-libmysqlclient-dev RUN echo PermitRootLogin yes >> /etc/ssh/sshd_config RUN echo root:newadminpasswd | chpasswd RUN pip3 install --no-cache-dir -r requirements.txt COPY . . RUN cp ./.env.example .env EXPOSE 8003 22 # Copy the rest of the code. COPY . /app/ RUN chmod +x start-server.sh ENTRYPOINT ["/app/start-server.sh"] start-server.sh File: echo ".......... start executing collecstatic ........." python3 manage.py collectstatic echo ".......... start executing makemigrations ........." python3 manage.py makemigrations echo ".......... start executing migrate ........." python3 manage.py migrate # python3 manage.py seed_admin_user # python3 manage.py seed_super_user echo "Docker started...." python3 manage.py runserver 0.0.0.0:8003 -
how to link User to Model from CreateView?
I am trying to build an application that allows user Accounts to create, join, leave, update (if they have auth) and delete Groups. The issue I'm running into is figuring out a way to link the two models so that Accounts will display the Groups they've created. users/models.py: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) joined_groups = models.ManyToManyField(Group, related_name='joined_group') created_groups = models.ManyToManyField(Group, related_name='created_group') group/models.py class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, related_name='joined_group', blank=True) I was able to figure out a way to have Accounts join Groups: def join_group(request, pk): id_user = request.user.id group = Group.objects.get(id=request.POST.get('group_id')) account = Account.objects.get(user_id=id_user) if group.joined.filter(id=request.user.id).exists(): group.joined.remove(request.user) account.joined_groups.remove(group) else: group.joined.add(request.user) account.joined_groups.add(group) return HttpResponseRedirect(reverse('group_detail', args=[str(pk)])) And that worked well enough. Accounts could now join Groups and display the Groups they joined. But, how do you add a Group as the Group is being created? views.py: class CreateGroup(CreateView): model = Group form_class = ChaburahGroup template_name = 'create_group.html' How do I add a function to add Groups to an Accounts created_groups after (or as) the Group is created? Sorry if there isn't enough code to go by, if anything else is needed, I'll add it. -
Django backend wont accept get requests from my front end
I'm using React as front end and Django as my backend when i go to the backend URL: localhost:8000 it displays all of the data in JSON and if i use Insomnia/Postman to get and post request it works However the frontend is not working i get Access to XMLHttpRequest at 'http://127.0.0.1:8000/cluster/' 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. I've read other articles on this site, and they all said to add the @csrf_exempt and I already have that and I still get the issues. settings.py CORS_ORIGIN_ALLOW = True CORS_ORIGIN_ALLOW_ALL = True views.py @csrf_exempt def clusterAPI(request, title=''): if request.method=='GET': clusters = reactUICluster.objects.all() clusterSerializer = reactUIClusterSerializer(clusters,many=True) return JsonResponse(clusterSerializer.data, safe=False) elif request.method=='POST': clusterData = JSONParser().parse(request) clusterSerializer = reactUIClusterSerializer(data = clusterData) if clusterSerializer.is_valid(): clusterSerializer.save() return JsonResponse("Added Successfully", safe=False) return JsonResponse("Failed To Add", safe=False) elif request.method=='DELTE': cluster = reactUICluster.objects.get(title=title) cluster.delete() return JsonResponse("Deleted Object", safe=False) axios call inside of my front end const config = { headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS" } }; const axiomCall = async () => { console.log("FF"); const temp = await axios.get("http://127.0.0.1:8000/cluster/", config) setRow(temp) }; Also this article said to … -
Cannot make virtual environment
I have virtualenvwrapper-win installed from the command line. When I try to do virtualenv env (env is the name of my virtual environment I'd like to set up) I get this: 'virtualenv' is not recognized as an internal or external command, operable program or batch file I'm not sure what's wrong. Anyone know how to fix? -
Calling a third party package's management command from a Django view
I am currently using the package 'django-two-factor-authentication' in my Django project and I see the management commands here (https://django-two-factor-auth.readthedocs.io/en/1.14.0/management-commands.html) My client would like to have a specific message for users who have not enabled two factor authentication. How would I call this from a view to check their status? If there is another way to check their status I would be open to that as well. I tried this already: from django.core.management import call_command authed = call_command('two_factor_status fake_email@gmail.com') print('authed response') print(authed) but I get an error message saying that this is an unknown command. If I leave the email out the page doesn't crash and I don't get an error but it prints out "None". -
Django channels AsyncComsumer cannot catch the custome Exception
I'm building a chat app with Django-channels. I use AsyncConsumer. In my consumer, I have method chatroom() that tries to call another method _can_access_room(). In _can_access_room() there's a case it raises a custom Exception (inherit from Exception). But I cannot catch the custom Exception in chatroom(). The log shows that it raised, but WebSocket disconnects. I set a breakpoint on the line that catches the exception but it doesn't stop there. But if I catch the base Exception, it works. Please help, thanks ^^ Here's my code: async def chatroom(self, data: dict): # check room in group or not? if group_from_room_id(data.get('room_id')) in self.groups: await self.chatroom_send(data) else: try: a = await self._can_access_room(data) except CustomException as e: print('ahihi') @database_sync_to_async def _can_access_room(self, room_data: dict): room_id = room_data.get('room_id') chat_room: ChatRoom = ChatRoom.objects.filter(id=room_id).first() if not chat_room: raise custom_exceptions.RoomDoesNotExist Here's log: ... , line 455, in thread_handler return func(*args, **kwargs) File "***********/consumers/chat_room_consumer.py", line 153, in _can_access_room raise custom_exceptions.RoomDoesNotExist common.custom_exceptions.RoomDoesNotExist WebSocket DISCONNECT /ws/chat/winners [127.0.0.1:49452] -
How to build a Django QuerySet to check conditions on two manyToMany fields
I have the following models (simplified): class Resource(models.Model): name = models.CharField(max_length=64, unique=True) class ResourceFlow(models.Model): resource = models.ForeignKey(Resource, related_name="flow") amount = models.IntegerField() class Workflow(models.Model): inputs = models.ManyToManyField(ResourceFlow, related_name="workflow") class Stock(models): resource = models.ForeignKey(Resource, related_name="stock") amount = models.IntegerField() class Producer(models.Model): workflow = models.ForeignKey(Workflow, related_name="location") stocks = models.ManyToManyField(Stock, related_name="location") I would like to test with computation done by the the DB engine if I can start a production. A production can start if I have enough stock: for my Producer's workflow, all inputs ResourcesFlow amount have to be present in the Producer'stocks So the queryset might be one those result: for a given producer return all stocked resources that do not fulfill Workflow inputs amounts conditions for a given producer return inputs resources needed for the workflow that are not in sufficient quantity in its stocks It is possible to do that in Django? -
django server log is full of "NoneType: None" messages
The log of my REST Server app is full of messages saying NoneType: None Is there a way to know where these messages are generated?. I have added this line to the settings.py in order to set the file/line of the errors, but no lunk. logging.basicConfig(format = '%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s', datefmt = '%Y-%m-%d:%H:%M:%S', level = logging.DEBUG) Example of the REST API logs: v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:10] "GET /api HTTP/1.1" 200 22 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:10] "GET /api/person/me HTTP/1.1" 200 1981 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/people HTTP/1.1" 200 514227 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/permission/can-add-travel HTTP/1.1" 200 84 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/permission/can-update-travel HTTP/1.1" 200 87 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/permission/can-delete-travel HTTP/1.1" 200 87 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/permission/can-undelete-travel HTTP/1.1" 200 89 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/countries HTTP/1.1" 200 32773 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/reasons HTTP/1.1" 200 1997 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 15:59:11] "GET /api/states HTTP/1.1" 200 5270 v-ng-dev-server | NoneType: None v-ng-dev-server | [14/Jul/2022 … -
Would this make my code faster? Should I not follow Django's structure best practices and would that affect my website's security?
I don't know what makes my code fast or slow... is it the quantity of lines? How separated between different files it is? What I am trying to do? On a Django website could my website security be compromised because of me not following Django's project structure best practices? (if that would give my code more speed) How could I make my Django website as fast as possible without compromising security? -
How to implement new log_action for LogEntry in admin views
I'm trying to display every actions performed on my models on an admin page, using LogEntry. So far I see actions done through the admin (which is the way LogEntry works by default if I understood well), but I would like to catch actions performed through my VueJS frontend as well. Not sure how to do this properly ! This is my code in admin.py (django 4.0) from django.contrib import admin from .models import * from django.contrib.admin.models import LogEntry, ADDITION, CHANGE class MoniterLog(admin.ModelAdmin): list_display = ('action_time','user','content_type','object_repr','change_message','action_flag') list_filter = ['action_time','user','content_type'] ordering = ('-action_time',) admin.site.register(LogEntry,MoniterLog) -
How to exclude search queries when selecting values in Django?
There is a product filter in which you need to exclude other attributes when choosing a brand. For example, we have color, size, weight, brand. When choosing a brand, we only have certain colors, sizes and weights. How to disable their checkboxes when they are not assigned to the selected brand. My code: [http://jsfiddle.net/Wihomie/vju41bqe/3/][1] -
Issue Installing ODBC Driver 17 for SQL Server for Linux
My end goal is to use Azure SQL Edge (ASQLE) instead of Microsoft SQL Server in a Docker container for a local development instance of an application (since MSSQL doesn't run on ARM). The container running ASQLE seems to be fine, but when I try to start my application I get the following error from the container running the API (which is powered by Django): django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") I have seen this issue a few other times on the web (1, 2) and they all seem to start with ensuring the driver installation, which is what I am having problems with. Following the guide provided by Microsoft, I run the following four commands (on a fresh ASQLE image) and get these outputs: root@7c38f5ceb89c:/$ curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)). 100 983 100 983 0 0 4529 0 --:--:-- --:--:-- --:--:-- 4529 OK root@7c38f5ceb89c:/$ … -
Cloudinary upload image from Django admin panel from two or more databases
everyone. I decide to use Cloudinary for storing images. This is my model field with image: avatar = models.ImageField(upload_to='avatar/', default='avatar/default.png', blank=True) All works fine for me, but I have one little issue. When I uploaded the image from admin panel, cloudinary upload it to my cloudinary folder 'avatar' with some modified name, for example: 'july2022_kda4th' or 'july2022_aidkdk' But when I uploaded this image from admin panel of another database (production), cloudinary upload the image with another name. So, I have two similar images in cloudinary. It's not convenient. How can I fix it? -
Indexing first n characters of Charfield in Django
How to index a specific number of Characters on Django Charfield? -
How to enable basic http auth through Django?
How do you enable basic http auth in Django? According to the Django docs, basic http auth can be enabled directly in Django, requiring no server support. I've added django.contrib.auth.middleware.RemoteUserMiddleware to my MIDDLEWARE list and added django.contrib.auth.backends.RemoteUserBackend to my AUTHENTICATION_BACKENDS list. so I created a simple view: import logging from django.http.response import JsonResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def test_auth(request): print('Request.user: %s' % request.user) print('META:', request.META) print('REMOTE_USER:', request.META.get('REMOTE_USER')) if request.user.is_anonymous: return JsonResponse({"success": False}, safe=False) return JsonResponse({"success": True}, safe=False) and registered it in my urls.py as /test_auth. And then to test, I call it using curl: curl -u "myuser:mysupersecretpassword" -0 -v -X GET http://127.0.0.1:8000/test_auth However, it shows that Request.user: AnonymousUser, implying the RemoteUserBackend is not being called. I've tested my myuser:mysupersecretpassword credentials, and confirmed I can login as that user via the normal Django admin login. I'm using Django 3.2. Why isn't basic auth working with RemoteUserBackend? Is there another step that I'm missing? -
Django: permission required based on roles, but using a single User model
I have a custom user model that looks like this: class SpotUser(AbstractBaseUser): BASIC = 1 ADMIN = 2 QA = 3 RESEARCH = 4 uid = models.IntegerField(primary_key=True) name = models.TextField(blank=True, null=True) email = models.EmailField(unique=True) password = models.TextField(blank=True, null=True) USER_TYPE_CHOICES = ( (BASIC, 'Basic'), (QA, 'Qa'), (RESEARCH, 'Research'), (ADMIN, 'Admin') ) user_type = models.TextField(choices=USER_TYPE_CHOICES, default=BASIC) last_login = models.DateField() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: managed = False db_table = 'users' I would like to add permissions based on the role. For example: Admin and research can update users via backend API, but QA and Basic cannot. Is it possible to implement this feature without using multiple User models? -
Url Error in Multiple Application Django site
My site has 3 application [alpha , store , management] alpha for landing page , login , about , contact and similar pages store e-com like page , management for system admin and management I have urls.py in all my applications And everything runs well first but when try request to in app urls it didn't worked.. Main urls urlpatterns = [ path('admin/', admin.site.urls), path('services',include('store.urls')), path('management',include('management.urls')), path('',include('alpha.urls')) ] First application url for store urlpatterns = [ path('',views.main,name = "main"), path('track',views.track,name="tracker") ] Second application url for management urlpatterns = [ path('',views.main ,name=''), path('staffs',views.staffs ,name='staffs'), path('costumers',views.costumers ,name='costumers'), path('services',views.services ,name='services'), path('delete',views.delete ,name='delete'), path('add',views.add ,name='add'), path('crm',views.crm ,name='crm'), path('ratings',views.ratings ,name='ratings'), path('complainBox',views.complainBox,name = 'complainBox'), path('registrationApproval',views.registrationApproval ,name='registrationApproval'), path('feedbacks',views.feedbacks,name = "feedbacks"), path('contact',views.contact,name = "Contact"), path('datasets',views.datasets,name = "Dataset page"), path('tools',views.tools,name ="Tools page" ), path('services',views.services,name ="services page" ), path('reports',views.reports,name ="reports page" ), path('login',views.login,name="Login page") , path('forgetPassword',views.forgetPassword,name = "Forget password") ] 3rd application url for alpha urlpatterns = [ path('',views.main,name='Main page'), path('about',views.about , name="About page"), path('contact',views.contact,name='contact page'), path('register',views.register,name='Staff registration'), path('patners',views.patners ,name="patner page"), path('alumuni',views.alumuni,name="Alumini page"), path('help',views.help , name = "help page"), path('complain',views.complain,name="Complain page"), path('feedback',views.feedback,name = "feedback page"), path('plans',views.plans,name = "plans and visions"), path('team',views.team,name = "team page") ] management page image When i click to tools or other link it is showing me … -
Django pass form data into another function
So I have a function that I want to use here in the forms or if I can in another python file but call it from this file. I want to access the file or at least the file path to be uploaded with the AssignmentSubmission class then pass it along with some other data into another python function to be processed and saved back to the sqlite database but I have no idea how to do it. My python forms file is below. from django import forms from .models import Course, Assignment, Exam, AssignmentSubmission, ExamSubmission # FORM FOR CREATE A COURSE class CourseCreateForm(forms.ModelForm): class Meta: model = Course fields = ['course_ID', 'course_name', 'course_image', 'teacher_name', 'teacher_details', 'course_description', 'end_date'] def __init__(self, *args, **kwargs): super(CourseCreateForm, self).__init__(*args, **kwargs) self.fields['course_ID'].label = "Course ID" self.fields['course_name'].label = "Course Name" self.fields['course_image'].label = "Image" self.fields['teacher_name'].label = "Teacher Name" self.fields['teacher_details'].label = "Teacher Details" self.fields['course_description'].label = "Description" self.fields['end_date'].label = "End Date" self.fields['course_name'].widget.attrs.update( { 'placeholder': 'Enter Course Name', } ) self.fields['course_ID'].widget.attrs.update( { 'placeholder': 'Enter Course ID', } ) self.fields['course_image'].widget.attrs.update( { 'placeholder': 'Image', } ) self.fields['teacher_name'].widget.attrs.update( { 'placeholder': 'Teacher Name', } ) self.fields['teacher_details'].widget.attrs.update( { 'placeholder': 'Teacher Details', } ) self.fields['course_description'].widget.attrs.update( { 'placeholder': 'Description', } ) def is_valid(self): valid = super(CourseCreateForm, self).is_valid() # … -
why I can't get total number of pages on output after using 'num_pages' property of pagination in django
where i made mistake... why I can't able to get total number of pages on output code which giving error -
How to convert that js function into django views
if (isset($_GET['pricechart'])) { $priceSliderOptions = array( 'minPrice' => '1', //minimal possible price for range slider 'maxPrice' => '350', //maximal possible price for range slider 'sliderPriceFrom' => '12', //default min value for range slider 'sliderPriceTo' => '189', //default max value for range slider 'sliderIncrement' => '1', //increment for range slider 'chartBars' => generateChartBarsExample() //@json (see README.md) ); header('Content-Type: application/json; charset=utf-8'); echo(json_encode($priceSliderOptions)); die(); } //price chart demo functions function generateChartBarsExample() { $maxPrice = 350; //maximal price of product in dataset $increment = 5; //how much euro in one bar of chart $priceTo = $increment; //default value $priceFrom = 1; //default value (should be the same as minPrice for range slider) $numberOfBars = $maxPrice / $increment; //how much bars we show on chart (linear calculation) $cb[] = ['priceFrom' => $priceFrom, 'priceTo' => $increment, 'frequency' => randomFloat()]; //first line without iteraction for ($i=1; $i < $numberOfBars; $i++) { $frequency = mt_rand() / mt_getrandmax(); $priceFrom = $priceFrom + $increment; $priceTo = $priceFrom + $increment - 1; if ($i < $numberOfBars) { $cb[] = ['priceFrom' => $priceFrom, 'priceTo' => $priceTo, 'frequency' => randomFloat()]; } else { $cb[] = ['priceFrom' => $priceFrom, 'priceTo' => $priceFrom, 'frequency' => randomFloat()]; //for last element we just set priceFrom = priceTo … -
add user input value to exported excel in Django import-export library
I am struggling with getting the value that user inserts in the form IN field called number_of_units. How can I pass the user value and add it to the total_price column in exported Excel file? views.py class ProductDetailView(LoginRequiredMixin, FormMixin, DetailView): login_url = 'login' redirect_field_name = 'login' template_name = 'ProductDetailView.html' model = Product form_class = CalculatorForm date_field = "publish" month_format = "%m" def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context['form'] = form return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): number_of_units = form.cleaned_data['number_of_units'] filter_qs = CostCalculator.objects.filter(related_product__slug=self.kwargs['slug']) dataset = CostCalculatorResource().export(filter_qs, number_of_units) form.save() response = HttpResponse(dataset.xlsx, content_type="xlsx") response['Content-Disposition'] = 'attachment; filename=cost_calculator.xlsx' return response def get_success_url(self): return reverse('product', kwargs={'slug': self.kwargs['slug']}) models.py class CostCalculator(models.Model): related_product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='related_product') title_component = models.ForeignKey(CalculatorServiceComponent, on_delete=models.CASCADE, default=1) number_of_units = models.IntegerField(default=0) cost = models.IntegerField(default=0) margin = models.FloatField(default=0.0) rate = models.IntegerField(default=0) @property def total_price(self): return self.cost * self.number_of_units * self.margin resources.py class CostCalculatorResource(resources.ModelResource): related_product__title = Field(attribute='related_product__title', column_name='Product') total_price = Field(attribute="total_price") class Meta: model = CostCalculator fields = ('id', 'related_product__title', 'total_price' ) forms.py class CalculatorForm(forms.ModelForm): number_of_units = forms.IntegerField(help_text='Only numeric values are allowed.', min_value=0) class Meta: model = CostCalculator fields = ('number_of_units',) -
How to solve this error "connection to local host failled " while deploying my django project on heroku
I am making a Facebook app using Django and want to deploy my project on Heroku. While deploying my project I am putting my important data in a .env file using decouple module. My settings.py file looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD' : config('DB_PASSWORD'), 'HOST' : config('DB_HOST'), 'PORT': '5432', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] USE_I18N = True USE_TZ = True STATIC_URL = 'static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Default primary key field type and my .env file looks like this SECRET_KEY=##### DB_NAME=####### DB_USER=######## DB_PASSWORD=####### DB_HOST=######### and I am facing this error: OperationalError at /login connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Request Method: POST Request URL: https://facebook-django-akhil.herokuapp.com/login Django Version: 4.0.6 Exception Type: OperationalError Exception Value: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Exception Location: /app/.heroku/python/lib/python3.10/site-packages/psycopg2/init.py, line 122, in connect Python Executable: /app/.heroku/python/bin/python Python Version: 3.10.5 Python Path: … -
Axios taking long time to fetch response
I am using Axios instance in a React app to fetch data from GET requests. Backend server is deployed on Heroku(Professional Dyno) and written in Django REST framework. Database is deployed on AWS. On postman, APIs are giving response in around 2-3 seconds: Postman Screenshot But in the react app, response time is around 25-30 seconds. React app response time Screenshot Please note that I am calling around 10 different APIs in a single page. Is this affecting the response times? -
datetime ISO-8601 format
I have Django project and I want to use parse_datetime() to get (IOS-8601) formatted not in templates I have this datetime (2022-06-04 15:23:08.367007+00:00) I want it to be like this format (2022-06-04T15:30:00Z) I have tried this like this datetime_test = '2022-06-04 15:23:08.367007+00:00' datetime_test_1 = dateparse.parse_datetime(str(datetime_test)) print(datetime_test_1) I got 2022-06-04 15:23:08.367007+00:00 Is there any way I can get IOS-8601 format like this format 2022-06-04T15:30:00Z