Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why date from data base dont show on home.html Python Django
The problem is that date from database that i have created doesnt show on my html page and i dont understand what is the problem maybe i connected something wrong models.py from django.db import models class table_1(models.Model): datetime = models.DateField() machine_1 = models.IntegerField() machine_2 = models.IntegerField() dryer = models.IntegerField() machine_1_time = models.TimeField() machine_2_time = models.TimeField() dryer_time = models.TimeField() def __int__(self): return self.title settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'data', 'USER': 'postgres', 'PASSWORD': '1221', 'HOST': 'localhost', 'PORT': '5432', } } home.html <h2>1{{ tablet.machine_1_time }}</h2> {{ mytable.machine_1 }} {% for item in tablet %} <h3>{{ item.datetime }}</h3> <!-- Выведите другие поля модели --> {% endfor %} views.py from django.shortcuts import render from .models import table_1 def home(request): tablet = table_1.objects.all() return render(request, 'table/home.html', {' tablet': tablet}) When i runserver there is no data shown at all machine_data.sql create table machine_dara ( datetime DATE, machine_1 INT, machine_2 INT, dryer INT, machine_1_time INT, machine_2_time INT, dryer_time INT ); insert into machine_dara (datetime, machine_1, machine_2, dryer, machine_1_time, machine_2_time, dryer_time) values ('2022-12-31', 55, 77, 35, 84, 91, 63); insert into machine_dara (datetime, machine_1, machine_2, dryer, machine_1_time, machine_2_time, dryer_time) values ('2023-01-14', 67, 69, 79, 80, 50, 64); insert into machine_dara (datetime, machine_1, machine_2, dryer, … -
Django chunked upload
I have a Django app in which the user can upload a tdms file. When I deploy it, this does not work for large files, which is why I want to implement chunked upload through the django-chunked-upload library. I gave it a go, but I really need help. I get this feedback in my terminal: "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 <QueryDict: {'resumableChunkNumber': ['5'], 'resumableChunkSize': ['1048576'], 'resumableCurrentChunkSize': ['1339055'], 'resumableTotalSize': ['5533359'], 'resumableType': [''], 'resumableIdentifier': ['5533359-VibrationLog_2023-05 -05-084134tdms'], 'resumableFilename': ['Vibration Log_2023-05-05 - 084134.tdms'], 'resumableRelativePath': ['Vibration Log_2023-05-05 - 084134.tdms'], 'resumableTotalChunks': ['5']}> [19/Jun/2023 14:50:44] "POST /tdms/api/chunked_upload/?resumableChunkNumber=5&resumableChunkSize=1048576&resumableCurrentChunkSize=1339055&resumableTotalSize=5533359&resumableType=&resumableIdentifier=5533359-VibrationLog_2023-05-05 -084134tdms&resumableFilename=Vibration%20Log_2023-05-05%20-%20084134.tdms&resumableRelativePath=Vibration%20Log_2023-05-05%20-%20084134.tdms&resumableTotalChunks=5 HTTP/1.1" 302 0 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 <QueryDict: {}> [19/Jun/2023 14:50:44] "POST /tdms/api/chunked_upload_complete/ HTTP/1.1" 302 0 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 which seems okay, but the file does not get saved anywhere. This is my models.py: from django.db import models from nptdms import TdmsFile import json import pytdms from chunked_upload.models import ChunkedUpload # Create your models here. class VibrationLogChunkedUpload(ChunkedUpload): name = models.CharField(max_length=100, blank=True, null=True) notes = models.TextField(blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) data = models.JSONField(blank=True, null=True) sample_frequency = models.FloatField(blank=True, null=True, default=8533.33) tdms_file = models.FileField(upload_to='tdms') … -
Custom submit button's name isn't added to request.POST when I add the record in Django admin
Let's say I have model Record with the approved flag class Record(models.Model): approved = models.BooleanField(default=False) I want to add Save and approve button in Record's admin near the Save button. For that I added new imput tag in the submit_line.html: {% extends 'admin/submit_line.html' %} {% load i18n admin_urls %} {% block submit-row %} {{ block.super }} {% if show_save %} <input type="submit" value="Save & approve" name="_save_and_approve"/> {% endif %} {% endblock %} Now I see this button and _save_and_approve appears in the request.POST when I edit the created record, but this name doesn't exist in the request.POST when I try to add a new one. So, the custom button works only when I edit the record. What I'm doing wrong? I use Django 4.1 P.S. Things I've tried so far: tried overriding the change_form.html with adding change_form_template to admin.Model class tried using both templates: change_form.html and submit_line.html tried adding add_form_template to admin.Model class with relation to change_form.html checked all relateed topics -
Displaying images from an EPUB file along with text using ITEM_DOCUMENT in Python
I'm currently working on a Python project where I need to extract text and images from EPUB files and display them together. I'm using the ITEM_DOCUMENT method from the epublib library to extract the text successfully. However, I'm facing difficulties in extracting and displaying images alongside the text. Here's a simplified version of my code: class PDFtoBookCreateView(CreateView): template_name = 'pdf_viewer.html' model = EBook def get_context_data(self, **kwargs): context={} book = epub.read_epub("H:/Hexcoder/sellzzy/new2_developer02/tshirtbundle/static/epub/9781408855713.epub") epub.EpubBook.get_template = new_get_template epubObj= book.get_items_of_type(ebooklib.ITEM_DOCUMENT) epubObjList= list(epubObj) context['finalTextList'] = [xhtml_to_html(i.content) for i in epubObjList] return context I'm able to retrieve the text content using the ITEM_DOCUMENT method, but I'm unsure how to extract and incorporate the images into the display. I've tried exploring the EPub library's documentation, but I couldn't find specific guidance on this matter. Could someone please provide guidance on how I can extract images from the EPUB file using Python, and integrate them into my display alongside the extracted text? Any example code or pointers to relevant resources would be greatly appreciated. Thank you! -
How can I Mock OpenSearch Client in Django unit test
I'm trying to mock OpenSearch client for writing unit tests for those methods using OpenSearch operations i.e. index, delete, etc. I have tried openmock library's decorator but in git workflow test it couldn't connect to OpenSearch client. -
giving user's ip address and display it in admin.py of a django project
how can i give ip address of users and display it in admin.py of django project? I created view of it but i don't know how to display it in admin panel this is my view function : `def get_ip_address(request): user_ip_address = request.META.get('HTTP_X_FORWARDED_FOR') if user_ip_address: ip = user_ip_address.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip def show_ip_address(request): user_ip = get_ip_address(request) return render(request, "output.html", {"user_ip":user_ip})` ...................................................................................................... -
Django App for azure authentication python 3.7
I have a Django web app that runs on Python 3.7 and I want to integrate user authentication with Azure Active Directory in my web app. There is a Django app "django-azure-auth" & "django-azure-auth 1.1.0" but it requires Python >=3.8. Can anyone please suggest to me a Django app that supports Python 3.7? -
how to connect an existing mongdb database which has collection and fields to a website in django frame work
Is there a solution or approach to reuse an existing MongoDB database for a website instead of creating a new one, given that both have the same structure? I want to avoid the hassle of setting up a new database and ensure efficient utilization of resources. The objective is to leverage the existing MongoDB database, which already has the desired structure, for my website. By reusing the database, I can avoid duplicating efforts and maintain consistency in data management. I'm seeking guidance on the logic or code required to accomplish this task. Ideally, I would like to establish a connection to the existing MongoDB database, ensuring that the website can interact with it seamlessly. I want to perform CRUD operations, such as retrieving data, updating records, and executing queries, based on the needs of my website. Furthermore, I need to adapt the retrieved data from the database to suit the requirements of my website. This may involve transforming the data into a format compatible with web pages or other components of the website. Ultimately, I aim to integrate the existing MongoDB database with my website, allowing it to serve as the backend data storage solution. By reusing the database, I … -
How can I create mock a manytomany field for django pytest?
I am trying to create mock data for test in django. I have team model like this: class Team(TimeStampedModel): id: int created: datetime name = models.CharField(max_length=100) members = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="teams", through="Membership" ) And here is the part of test file: class TestTeamListViews: def test_team_list( self, client: Client, mocker, site_admin_user: User, team_with_members: Team ): admin1 = team_with_members.members.get(email="admin1@example.com") mock_teams = [ Team( id=1, name="Test Team", members=admin1, created=datetime.datetime.now(), ) ] This case, I get error: def __set__(self, instance, value): > raise TypeError( "Direct assignment to the %s is prohibited. Use %s.set() instead." % self._get_set_deprecation_msg_params(), ) E TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use members.set() instead. So, I tried class TestTeamListViews: def test_team_list( self, client: Client, mocker, site_admin_user: User, team_with_members: Team ): admin1 = team_with_members.members.get(email="admin1@example.com") mock_teams = [ Team( id=1, name="Test Team", members=Team.members.set(admin1), created=datetime.datetime.now(), ) ] Then, I get error: AttributeError: 'ManyToManyDescriptor' object has no attribute 'set' I googled a lot, but there is no solutions I could found other than using add instead of set. Using add gives same error. Please help me. -
How do i make custom api calls in Ant design's filters/Search in a table columns?
I have a React application where I'm implementing a filter feature for the columns of my table. The goal is to make the search in the back and get an updated datasource that fit the search criteria or filter criteria. However, I'm facing an issue where the API requests continue endlessly, even after implementing a timeout mechanism. here is one of the columns : { title: "Project visibility", dataIndex: "projectVisibility", filters: filterLists.projectVisibilityFilters, onFilter: (value) => { console.log("onfilter method", value); dispatch(setColumnSearchValues("projectVisibility", "filter", value)); if (timeoutId > 500) { clearTimeout(timeoutId); } else { console.log("how many times i am in the else !!"); timeoutId = setTimeout( dispatch( RequestSearchColumns( advancedSearchForm, quickFiltersForm, columnsFiltersForm, currentPage, pageSize ) ), 500 ); } console.log("time taken to reach the back !!", timeoutId); }, onFilterDropdownOpenChange: (visible) => { if (visible) { setTimeout(() => searchInput.current?.select(), 500); } }, render: (value, row, index) => { isUnavailableValue(value); switch (value) { case "Confidential": return ( <div className="custom-width-column w-120"> <div className="blur-layer"></div> <Badge color="red" text={value} /> </div> ); case "Visible": return ( <div className="custom-width-column w-120"> <div className="blur-layer"></div> <Badge color="#52C41A" text={value} /> </div> ); default: if (isUnavailableValue(value)) { return unavailableValue(value); } else { return ( <div className={ row.isConfidential ? "blur-content custom-width-column w-120" : "custom-width-column w-120" }> <div … -
How to not escape a character in a Django ORM?
I use Django, ORM. I don't want the character '%' to be escaped. name='' author='' annotation = 'harry%magic%school' criterion_name = Q(name__contains=cleaned_data['name']) criterion_author = Q(name__contains=cleaned_data['author']) criterion_annotation = Q(name__contains=cleaned_data['annotation']) Book.objects.filter(criterion_name, criterion_author, criterion_annotation) I get '%harry\%magic\%school%': select name, author, annotation from books where name LIKE '%%' AND author LIKE '%%' AND annotation LIKE '%harry\%magic\%school%' I want to get '%harry%magic%school%': select name, author, annotation from books where name LIKE '%%' AND author LIKE '%%' AND annotation LIKE '%harry%magic%school%' How to fix it? -
I am unable to Add to Cart as Anonymous User using session key
I am developing a ecommerce website using Python Django framework. Code is proper and actively working when user login but not working as a guest. I am unable to Add to Cart as Anonymous User using session key. models.py class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) product_qty = models.IntegerField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) session_key = models.CharField(max_length=140, null=True) cart.py from django.http import JsonResponse from django.shortcuts import render, redirect from django.contrib import messages from buyjoi.models import Product, Cart from django.contrib.auth.decorators import login_required def addtocart(request): if request.method == 'POST': if request.user.is_authenticated: prod_id = int(request.POST.get('product_id')) product_check = Product.objects.get(id=prod_id) if (product_check): if (Cart.objects.filter(user=request.user.id, product_id=prod_id)): return JsonResponse({'status': "Product Already in Cart"}) else: prod_qty = int(request.POST.get('product_qty')) if product_check.quantity >= prod_qty: Cart.objects.create( user=request.user, product_id=prod_id, product_qty=prod_qty) return JsonResponse({'status': "Product added successfully"}) else: return JsonResponse({'status': "Only " + str(product_check.quantity) + " quantity available"}) else: return JsonResponse({'status': "No such product found"}) else: request.session['product_id'] prod_id = int(request.POST.get('product_id')) product_check = Product.objects.get(id=prod_id) if (product_check): if (Cart.objects.filter(product_id=prod_id, session_key=request.session.session_key)): return JsonResponse({'status': "Product Already in Cart"}) else: prod_qty = int(request.POST.get('product_qty')) if product_check.quantity >= prod_qty: Cart.objects.create( product_id=prod_id, product_qty=prod_qty, session_key=request.session.session_key) return JsonResponse({'status': "Product added successfully"}) else: return JsonResponse({'status': "Only " + str(product_check.quantity) + " quantity available"}) else: return JsonResponse({'status': "No such product found"}) return redirect("/") def … -
Django and Docker: ModuleNotFoundError: No module named 'widget_tweaks'
I'm trying to use django-widget-tweaks in my web application (using Django and Docker), but it is not being recognized as an installed package. My DockerFile: # Pull base image FROM python:3.10.2-slim-bullseye # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt RUN pip3 install django-widget-tweaks # Copy project COPY . . My settings.py: INSTALLED_APPS = [ 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'openai', ] INSTALLED_APPS += [ 'widget_tweaks', ] The error: Exception in thread django-main-thread: project-web-1 | Traceback (most recent call last): ... project-web-1 | ModuleNotFoundError: No module named 'widget_tweaks' -
Docker in Github actions
I am building a Django application in Docker. In one of my tests, I am calling a function that uses celery[redis] for background task. Currently, I want to make a CI (github actions) that checks linting and tests my app whenever pushed to certain repositories. I am getting this error whenever I try run this workflow: Error -3 connecting to redis:6379. Temporary failure in name resolution. ` name: Django CI on: push: branches: [ "main", "master"] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.9] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | pip install -r requirements.txt - name: Lint with flake8 run: | pip install flake8 flake8 - name: Build and run docker run: docker-compose up --build -d - name: Coverage report env: STRIPE_API_KEY: ${{ secrets.STRIPE_API_KEY }} EMAIL_HOST_USER: ${{ secrets.EMAIL_HOST_USER }} EMAIL_HOST_PASSWORD: ${{ secrets.EMAIL_HOST_PASSWORD }} run: | coverage run manage.py test coverage report - name: Stop containers if: always() run: docker-compose down ` But if I try to pass docker-compose run --rm [service] sh -c "coverage run manage.py test" instead of coverage run manage.py test everything … -
Django Upload File API Endpoint
so I have a view in my Django website that is supposed to accepted uploaded backup files and save a backup record to the database. It's meant to accept http post requests with a file and user credentials so that I can associate backup uploads to each user. I also created a different script entirely to test if this works and it's been fine when I upload small files but keeps failing when I try and upload large files (e.g. 100mb +). I'm not sure if there's a better way to do this or if I'm making a mistake somewhere. views.py: @csrf_exempt def upload(request): if request.method == 'POST': try: file = request.FILES['file'] # check file type before saving. only allow .zip files if not file.name.endswith('.zip'): return HttpResponse("Invalid file type. Only .zip files are allowed.", status=415) # get the user credentials from the request username = request.POST.get('username') password = request.POST.get('password') # authenticate the user user = authenticate(request, username=username, password=password) if user is None: return HttpResponse("Invalid credentials", status=401) saveDir = os.path.join('backups/', user.username) savePath = os.path.join(saveDir, file.name) storage_left = user.profile.max_storage - user.profile.used_storage backup = Backup(user=user, file=file) backup.file.name = savePath backup.save() if backup.filesize > storage_left: response_str = f"Could not upload file {backup.basename}. " \ … -
What are the appropriate configurations for the WSGIDaemonProcess if memory is not being released?
I have a Django application which is hosted using Apache and a WSGI Daemon Process. It fetches large amounts of data from a database, and I have an issue where it won't release the RAM after completing the request if the request was large and/or many requests come in at the same time. I've tried debugging this without touching the server configuration (since I don't have editing privileges on the server and need to request the change), but my last hope is changing the options on the WSGI Daemon process to mitigate the problem. It is currently set to processes=2 threads=5, nothing else is configured. I have read through the documentation of the different configuration options, but I am unsure what an appropriate configuration for my use case would be. The site doesn't see a lot of traffic (probably only used once or twice a day), but when it IS being used, it will have to handle large amounts of data and 100-500 requests in relatively short sucession. So I don't want to set the maximum-requests too low, but since the site doesn't see traffic regularly, the RAM might never be released if the limit isn't reached. Would a restart-intervall … -
__isnull not working in Django ORM in test method
In my test setup: def setUp(self): self.myitem_1 = mommy.make(MyModel, my_field=None) ... In the test: result = MyModel.objects.my_field__isnull().all() self.assertEqual(result.count(), 1) I was expecting is null to work for None, but doesn't count the value. Test fails as 0 != 1 What am I missing? -
Making a that enables 'GET' without token but not posts without tokens
I recently started working with Django backend development, so I'm still struggling with some features. This time, I've encountered a problem that has been quite challenging, and I couldn't find any helpful answers on the web. I'm creating a view that supports both 'GET' and 'POST' requests. The issue I'm facing is that while I need a Bearer token for the 'POST' request, I don't want to require a token for the 'GET' request. Initially, I considered creating a separate view just for the 'GET' request, but that seemed redundant. Then, I came across the 'IsAuthenticatedOrReadOnly' permission class in the Django Rest Framework documentation. I thought this would solve my problem, but even after implementing this verification, the 'GET' endpoint still asks for a token. Could someone please provide me with some insights? Here's my view: from rest_framework.views import Request, Response, status, APIView from .serializers import MovieSerializer from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework.permissions import IsAuthenticatedOrReadOnly from movies.models import Movie class MovieView(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticatedOrReadOnly] def post(self, request: Request) -> Response: serializer = MovieSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(user = request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) def get(self, request: Request) -> Response: movies = Movie.objects.all() serializer = MovieSerializer(movies, many=True) return Response(serializer.data, status=status.HTTP_200_OK) ...and … -
Django generic List View with multiple query search
Hello I'm working with class based views in Django and I want to create a search form for users to find their own favourite products in my app with multiple filters and excludes but I couldn't do it. my code is here if anyone can modify it to make it right please help me out : models.py from django.db.models import models from django.core.validators import RegexValidators class Product(models.Model): num=RegexValidators(r'^[0-9a-zA-Z]*$') title = models.CharField(max_length=100) embed_id = models.CharField(max_length=15, validators=[num]) description = models.TextField(null=True, blank=True) forms.py from django import forms class ProductSearchForm(forms.Form): title = forms.CharField(required=False) embed_id = forms.CharField(required=False) description = forms.CharField(required=False) views.py from django.views.generic import ListView from .models import Product from .forms import ProductSearchForm class ProductListView(ListView): model = Product form_class = ProductSearchForm template_name = 'pages/product/list_products.html' def get_queryset(self): queryset = super().get_queryset() form = self.form_class(self.request.GET) if form.is_valid(): title = form.cleaned_data.get('title') embed_id = form.cleaned_data.get('embed_id') description = form.cleaned_data.get('description') if title: queryset = queryset.filter(title__icontains=title) if embed_id: queryset = queryset.filter(embed_id__icontains=embed_id) if description: queryset = queryset.filter(description__icontains=description) return queryset def get_context_data(self, [**kwargs): context = super().get_context_data(self, **kwargs): context['form'] = self.form_class(self.request.GET) return context I know how to handle this in Function based views, but I want to create its generic.listview. -
Why isn't it recommended to use bare HTTP status codes in a response?
According to the documentation for Django REST Framework, "using bare status codes in your responses isn't recommended". They recommend instead using the objects from the status module (e.g. status.HTTP_404_NOT_FOUND). My question is, where does this recommendation come from? I wasn't able to find any kind of 'official' source for this recommendation. -
Getting a 403 Forbidden message in a Django 4.2 POST request even after including the CSRF token
I am trying to perform a language toggle feature in a website and I am using Django 4.2 and using Django's i18n library in the root level urls.py file. urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += i18n_patterns( path('',apiView.WebsiteHomepageTemplate.as_view(),name="url_homepage_template"), ) In the template file , I am performing the language switch like this : <ul class="dropdown-menu" role="menu" id="language-list"> <li class="" id="language-switcher"> <form action="{% url 'set_language' %}" method="post" name="lang_form"> {% csrf_token %} <input name="next" type="hidden" value="/" /> <select class="selectpicker" id="select_pickr" name="language"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected="selected" {%endif %} data-content='{{ language.code }}}'> {% if language.code == 'en' %} English {% else %} हिंदी {% endif %} </option> {% endfor %} </select> </form> </li> </ul> When I perform the toggle, I get a 403 forbidden message. When I inspect using the dev tools I can see only 2 cookies being used , csrftoken & theme (for changing light and dark mode) till this moment So if I perform the toggle again while being on my custom 403 error page, I am able to toggle to the other … -
How to resolve [Errno -2] Name or service not known error?
I've hosted my Django application on cpanel, and when I try to send notifications to users via email, I receive this problem [Errno -2]. The name or service was unknown, but it worked properly using localhost. Any advice would be greatly appreciated. enter image description here This is my code to send mail to users. I have configured all the details in settings as well. -
How do I resolve HTTPSConnectionPool error, Max retries exceeded with url in python?
requests didn't work as expected def post(self, request): base_url = os.environ.get('AUTH_URL', 'http://localhost') # Make a POST request to the authentication endpoint with the payload headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", 'accept': 'application/json', 'Content-Type': 'application/json', } json_data = { 'username': os.environ.get("GARAJ_USERNAME", "admin"), 'password': os.environ.get("GARAJ_PASSWORD", "admin123"), } response = requests.post(base_url + '/api/token/', json=json_data, headers=headers) # Check the response status code if response.status_code == 200: data = response.json() # Extract the JWT token from the response jwt_token_access = data['access'] # Use the JWT token for subsequent API requests headers['Authorization'] = f'Bearer {jwt_token_access}' auth_url = base_url + '/api/boshqarma/avto/' response = requests.get(auth_url, headers=headers) for x in response.json()['results']: if x["davlat_raqami"] == request.data['avto_raqami']: boshqarma = x["boshqarma"] response = requests.get(base_url + f'/api/boshqarma/boshqarma/{boshqarma}/', headers=headers) tuman = response.json()['tuman'] response = requests.get(base_url + f'/api/boshqarma/bolim/{tuman}/', headers=headers) tuman = response.json()['tuman'] tuman = Tuman.objects.get(tuman_nomi=tuman) data = {'tuman_id': tuman.id} response = Response(data) return response else: return Response("Xato avto raqam") # Make additional API requests with the headers containing the JWT token else: return Response(response) This code block works on using localhost but did't work when it is on server,but returns below error.I manage both servers client and host server too. ConnectionError at /api/check-car/ HTTPSConnectionPool(host='example.uz', … -
success_url working on local but does not on production
I have a django website which uses stripe for payment. Everything seems to work fine on my local terminal and production server. However, my success page on the deployed website returns a Bad Request(400). I'll show the code below. The method that calls the success_url def charges(request, order_id): try: cart_items = CartItem.objects.filter(user=request.user) domain = settings.DOMAIN_NAME if settings.DEBUG: domain = "http://127.0.0.1:8000/" session = stripe.checkout.Session.create( customer_email=request.user.email, payment_method_types=['card'], line_items=[{ 'price_data': { 'product_data': { 'name': cart_item.product.product_name, }, 'unit_amount_decimal': cart_item.product.price*100, 'currency': 'usd', }, 'quantity': cart_item.quantity, 'tax_rates': [tax_rate.id], } for cart_item in cart_items], metadata={ "orderID": order_id }, mode='payment', success_url=domain + 'orders/order_complete?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain + 'orders/order_incomplete?session_id={CHECKOUT_SESSION_ID}', ) # Pass the session ID to the template return JsonResponse({ "id": session.id }) except stripe.error.InvalidRequestError as e: # Handle the specific InvalidRequestError exception print(f"Invalid request error: {e.param}") except stripe.error.StripeError as e: # Handle other Stripe-related errors print(f"Stripe error: {e}") except stripe.error.ValueError as e: print(f"Stripe error: {e}") except Exception as e: # Handle other general exceptions return JsonResponse({'error': str(e)}) The method that renders the success page def order_complete(request): session_id = request.GET.get('session_id') session = stripe.checkout.Session.retrieve(session_id) order_number = session["metadata"]["orderID"] transID = session["id"] try: order = Order.objects.get(order_number=order_number, is_ordered=True) ordered_products = OrderProduct.objects.filter(order_id=order.id) payment = Payment.objects.get(payment_id=transID) context = { 'order': order, 'ordered_products': ordered_products, 'order_number': order.order_number, 'transID': payment.payment_id, … -
How to reply comment using django and javascript
Please, I need help with my code, I have been unable to figure out my mistake for two days. I have a comment system that work properly but I want user to be able to reply comments. My issue now is that the reply comment is not submitting as I keep having the error: This page isn’t working right now. If the problem continues, contact the site owner. HTTP ERROR 405 Below is my view.py associated with it class BlogDetailsView(DetailView): model = models.BlogPost template_name = 'home/blog_details.html' def get_context_data(self, *args, **kwargs): get_likes = get_object_or_404(models.BlogPost, id=self.kwargs['pk']) context = super().get_context_data(*args, **kwargs) post = self.get_object() context['comments'] = post.comments.filter(status=True) context['comment_form'] = NewCommentForm() total_likes = get_likes.total_likes() liked = False if get_likes.likes.filter(id=self.request.user.id).exists(): liked = True context['total_likes'] = total_likes context['liked'] = liked return context def add_comment(request, pk): post = get_object_or_404(models.BlogPost, pk=pk) comments = post.comments.filter(status=True) if request.method == "POST": comment_form = NewCommentForm(request.POST) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.post = post user_comment.save() return redirect('index:blog_details', pk=pk) else: comment_form = NewCommentForm() return redirect('index:blog_details', pk=pk) Below is urls.py app_name = 'index' urlpatterns = [ path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('images/favicon.ico'))), path('', views.home, name = 'home'), path('blog/', BlogHomeView.as_view(), name="blog_list"), path('blog/<int:pk>/', BlogDetailsView.as_view(), name='blog_details'), path('add_post/', AddPostView.as_view(), name='add_post'), path('blog/edit/<int:pk>', EditPostView.as_view(), name='edit_post' ), path('blog/<int:pk>/delete', DeletePostView.as_view(), name='delete_post' ), path('like/<int:pk>', views.LikeView, name='like_post'), path('job/', JobHomeView.as_view(), …