Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fetch time from database as local time
I created a model in django for postgresql this is my models.py class Other(models.Model): poster = models.ImageField(upload_to="articlepic", blank=True) text = models.CharField(max_length=300, blank=False) created_at = models.DateTimeField("created at", auto_now_add=True) I fetched the date(created at) by using axios in react.when I used below code <p className="mb-0"><small>{item.created_at.toLocaleString()}</small></p></div> then I am getting this 2020-10-21T19:14:34.864421Z But I need in format (Ex:- 2 June 2020).Then how should I write it? -
How i can change the name of the variable in Django?
i added 'Avaliação' to my test site, and, when i migrate the new function i noticed that the name of the variable that receives the TextField, appears in the site, so 'cause of aesthetics reasons, i try change the name of the variable. before: from django.db import models class Avaliação(models.Model): ava = models.TextField(max_length=250) data_ava = models.DateTimeField(auto_now_add=True) after: from django.db import models class Avaliação(models.Model): Deixe_sua_sugestão = models.TextField(max_length=250) #leave_your_suggest in pt-br# data_ava = models.DateTimeField(auto_now_add=True) And gave an OperationalError 'cause "no such columns" or something like that. Someone know how i can change the name of the variable WITHOUT open the file django.db and delecting the tables? -
ican't correct the error no such column in django
my directory What do i have to do? from django.db import models class Product(models.Model): a = models.CharField(max_length=200) b = models.CharField(max_length=200) c = models.CharField(max_length=200) d = models.CharField(max_length=200) my error is no such column and i"ve tried several times. -
Using django-stripe's built-in webhook support
I'm using Django 3.0, Django-Stripe 2.0, and the Stripe CLI. django-stripe provides native support for Stripe webhooks, and their documentation says to include the following in my django project's main urls.py file to expose the webhook endpoint: url(r"^stripe/", include("djstripe.urls", namespace="djstripe")), I have done this, but how do I now leverage the endpoint? As a separate experiment, I created a payments app, setup the URL conf, and successfully called the view when triggering the non django-stripe webhook endpoint via the Stripe CLI. But it doesn't use any djstripe functionality: # project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('stripe/', include("djstripe.urls", namespace="djstripe")), path('payments/', include("payments.urls", namespace="payments")), ] # payments/urls.py from django.urls import path from . import views app_name="payments" urlpatterns = [ path("", views.my_handler, name="my-handler"), ] # payments/views.py from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def my_handler(request, **kwargs): print(request.body) return HttpResponse(status=200) Running stripe listen --forward-to localhost:8000/payments/ and, in a separate window, stripe trigger product.created returns a 200 response. But stripe listen --forward-to localhost:8000/stripe/webhook/ and stripe trigger product.created returns a 500. Thank you in advance for your help. -
Dynamically setting path to static file in Django
In Django, I'm trying to dynamically set the path to a static JavaScript file in a subfolder parsed from the URL. Not sure if this a good way to do it in Django (i.e. best practice), or if I am completely off. It seems like way too many steps and not very DRY, especially the views.py code. Will Django allow me to parse the request in the view (base.html) template and bypass the views.py step? I could use JavaScript, but is it possible in Django? Static file configuration has been defined in myproject/myproject/settings.py as: STATIC_URL = '/static/' My static files are set up as follows Note: each main.js file contains scripts specific to that page. /static/ └── js/ ├── global.js ├── home/ │ └── main.js ├── projects/ │ └── main.js └── users/ └── main.js If this is my URL: http://example.com/projects Views.py: I set a file path relative to my STATIC_URL path def projects(request): context={'js_file':'js/projects/main.js'} return render(request, 'pages/projects.html',{'context':context}) Which I use in my base.html layout template to set the JavaScript path {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- template head content --> </head> <body> <!-- template content --> <script src="{% static context.js_file %}"></script> </body> </html> This renders the … -
Django - Create model object with Foreign Key object
I don't feel like I get an idea on how it should work... I do have 2 models: Group is my custom model I wanna save. class Group(models.Model): name = models.CharField(max_length=40) subject = models.CharField(max_length=40) user = models.ForeignKey('User', on_delete=models.CASCADE) User is a standard user model for the application. I'm skipping UserManager for now. Simply said User can have multiple groups. class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=40, null=True, blank=True) surname = models.CharField(max_length=40, null=True, blank=True) objects = UserManager() A serializer for the custom model: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name', 'subject', 'user') And a viewset with overwritten create method: class GroupViewSet(viewsets.ModelViewSet): serializer_class = GroupSerializer def create(self, request, *args, **kwargs): group = group.objects.create(user=self.request.user) serializer = GroupSerializer(group) return Response(serializer.data) When calling a POST a new Group is created. The Group has relation to the User, but other fields (name, subject) are empty. -
'Entry' object has no attribute 'topic' problem in Django, Can anyone help please?
I'm working with Django and I'm stuck in editing entries in views app because of this error: ('Entry' object has no attribute 'topic') from django.shortcuts import render, redirect from .models import Topic, Entry from .forms import TopicForm, EntryForm def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if request != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topic', topic_id=topic.id) context = { 'entry':entry, 'topic':topic, 'form':form } return render(request, 'learning_logs/edit_entry.html', context) It says the problem is from line: topic = entry.topic but I can't figure it out!! -
How to add custom filename to django static file
This is a django jinja2 template code to download static file with a name of Final_Outliers.csv but I want the same functionality but add an extra name i.e. filepath which will be returned by views.py in django. {% load static %} <a href={% static '/Final_Outliers.csv' %} id="button4" class="btn btn-primary">Export to CSV</a> I am returning this filepath fom views.py: return render(request, 'home.html', {'DataFrame': var4, 'path': path, 'message1': True, 'filepath':z[0]}) -
Django: Initialize date input dynamically
I'm building a simple web app where users can log new entries that have a name (CharField) and a date. By default, the date is set to the current date: class EntryForm(forms.Form): entry_name = forms.CharField(label='New Entry', max_length=100) entry_date = forms.DateField(initial=datetime.date.today, widget=forms.widgets.DateInput(attrs={'type': 'date'})) If users select a different date and add an entry with that date, I want the selected date to persist as new initial value when the page reloads. I know there are a lot of related questions on setting initial values dynamically, but unfortunately, I still could achieve setting an initial value dynamically. My view with the form looks like this: @login_required def index(request): if request.method == 'POST': form = EntryForm(request.POST) if form.is_valid(): # get the label name and strip and convert to lower before saving it entry_name = form.cleaned_data['entry_name'].strip().lower() entry_date = form.cleaned_data['entry_date'] entry = Entry.objects.create(name=entry_name, date=entry_date, owner=request.user) return HttpResponseRedirect(reverse('app:index')) else: form = EntryForm() # other, unrelated stuff stuff ... context = { 'form': form, } return render(request, 'app/index.html', context) Even setting the initial value of a form field to a fixed value inside the view's else branch didn't work. I tried EntryForm(initial={'entry_name': 'test'}) (also for entry_date) without success. Also form.fields['entry_name'].initial = 'test', which didn't work either. In … -
403 forbidden access is denied nginx django in plesk
I am using plesk while deploying django https://www.plesk.com/blog/guides/django-hosting-latest-plesk-onyx/ . I am failed to deploy and i am trying to resolve but unable to do it. I am using vps with centos 8 and plesk But i am getting 403 forbidden While checking the logs i am getting [Wed Oct 21 19:51:06.344607 2020] [ssl:warn] [pid 34641:tid 140441160681792] AH01909: mrcric.com:443:0 server certificate does NOT include an ID which matches the server name [Wed Oct 21 20:20:17.381151 2020] [autoindex:error] [pid 55629:tid 140128584320768] [client 162.158.166.34:0] AH01276: Cannot serve directory /var/www/vhosts/mrcric.com/httpdocs/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm,index.shtml) found, and server-generated directory index forbidden by Options directive I have applied chmod 777 to the www directory but nothing has been resolved -
datatables server-sided smart search
I'm using a server-sided Datatable on Django,once i got the table to be server-sided i lost the smart search. I already did a search on datatable's forums but with no luck at all. Using django, django-rest-framework and Datatables. JS code: <script> $(document).ready(function() { var table = $('#bibs').DataTable({ "serverSide": true, "ajax": "/api/livros/?format=datatables", "columnDefs": [ { "targets": [0,1,2,3,4,5], // "visible": false, "searchable": true, "orderable": true, } ], "columns": [ { "className": 'details-control', "orderable": false, "data": null, "defaultContent": '', "render": function () { return '<i class="fa fa-plus-square" aria-hidden="true"></i>'; }, width:"25px" }, {"data": "autor"}, {"data": "ano"}, {"data": "titulo"}, {"data": "referencia"}, {"data": "tema"}, {"data": "tipo"}, ], "dom":'<"toolbar">Brtip', }); </script> -
How can I add both milliseconds and timezone to Django's logs?
Currently my settings.py file has the following: 'formatters': { 'debug': { 'format': f'%(asctime)s.%(msecs)03d - %(filename)s [%(lineno)4d] - %(levelname)s - %(message)s', 'datefmt': '%m/%d/%Y %I:%M:%S' } } which prints out the following format: 10/21/2020 08:13:34.257. This allows me to see milliseconds, but unfortunately it doesn't let me see the timezone. If I change the datefmt to include the timezone 'datefmt': '%m/%d/%Y %I:%M:%S %Z' then the timezone will show up before the milliseconds like so: 10/21/2020 08:13:34 UTC.410. I wasn't able to find a flag that allows me to add milliseconds to the datefmt portion. How can I add both milliseconds and timezone to Django's logs and have them in a proper order? I want the output to look like this: 10/21/2020 08:13:34.410 UTC. -
Redirect to login page with middleware is causing 'too many redirects" issue
What I want is redirect users to login page if they aren't authenticated. I made a middleware but the redirect is not working. Could someone give me a help? My urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('contas/', include('django.contrib.auth.urls'), name='login'), # I want call this path('', include('apps.props.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my middleware.py from django.http import HttpResponseRedirect from django.urls import reverse class AuthRequiredMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if not request.user.is_authenticated: return HttpResponseRedirect(reverse('login')) # Here I call login response = self.get_response(request) return response and finally, my settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'middleware.AuthRequiredMiddleware', # Registering middleware ] What I am getting is this page with "too many redirects" My log: -
The command 'makemigrations' don't make migrations, but i write some lines in models.py
i write this code in models.py: from django.db import models class Avaliação(models.Model): ava = models.CharField(max_length=250) data_ava = models.DateTimeField(auto_now_add=True) And i register this in admin.py with: from django.contrib import admin from .models import Avaliação admin.site.register(Avaliação) But when i try run the code python manage.py migrate and later python manage.py makemigrations, returns to me the answer : 'no changes detected', nothing change in my local site, nothing created in migrations.py. So i write the 0001_init.py my self, he must be auto_generated by Django but it happens when the commands work. The 0001_init.py generated by me, below: from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name = 'Avaliação', fields = [ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ava', models.CharField(max_length=250)), ('data_ava', models.DateTimeField(auto_now_add=True)),] ) ] Running the code python manage.py showmigrations returns to me the 0001_init.py, but nothing changed in my site... -
Processing async in django
i have a code structure like below. I'm sending a json data to my django server. I'm getting json data with webhook. but I want to do this in sync with asyncio. Receiving json data No errors. but the server gives an error "http 500". When I uninstall the async process, the application runs. but when I run it in async structure as below, it gives "http 500" error. how can i fix this situation? json data I sent { "side": "BUY", "type": "MARKET", "symbol": "BCHUSDT", "cryptoType": "binancefutures", "timeLine": "5m" } # web hook receive json data @csrf_exempt def webhook(request): webhook_received_json = json.loads(request.body) queryset = CryptoInfo.objects.filter(status=True, symbol=webhook_received_json['symbol'], side=webhook_received_json['side'], memberStatus=True) table_data = serializers.serialize('json', queryset) for pair_list in json.loads(table_data): if pair_list['fields']['symbol'] == webhook_received_json['symbol'] and pair_list['fields']['status'] and \ pair_list['fields']['cryptoType']: # get active positions asyncio.run(get_active_position(futures_api_key=pair_list['fields']['futures_api_key'], futures_secret_key=pair_list['fields']['futures_secret_key'], side=pair_list['fields']['side'], symbol=pair_list['fields']['symbol'])) async def get_active_position(futures_api_key, futures_secret_key, side, symbol): client = Client(futures_api_key, futures_secret_key) data = await client.futures_position_information() asyncio.run( create_new_order(futures_api_key, futures_secret_key, side, symbol)) return get_active_position async def create_new_order(futures_api_key, futures_secret_key, side, symbol): client = Client(futures_api_key, futures_secret_key) try: create_order = await client.futures_create_order(symbol=symbol, type=Client.ORDER_TYPE_MARKET, side=side, quantity=15) except Exception as e: return "New order error :" + str(e) return create_new_order `` -
Delete column from PostgreSQL (Heroku)
I have a Django project on Heroku, database there - postgresql. So, during manipulation of migrations conflicts with the database arose. When I post a request to the project API, the error occurs IntegrityError at /api/clients/ null value in column "loan_approved" violates not-null constrain But I no longer have this column in my database. As far as I understand, this column was left over from old migrations and I tried to delete it directly: cursor.execute("alter table my_table drop column loan_approved;") then I check all columns in the table as follows cursor.execute("Select * FROM clients_client LIMIT 0") colnames = [desc[0] for desc in cursor.description] But this column is still in the database. Can I delete it in theory? Thanks, any help would be helpful -
Trying to make a visit counter + IP unique in CBV for django blog
I'm doing an integer field in models fou counting the visits, but I would like to be filtered also by IP. counter = models.IntegerField(default=0) class ArticleDetailView(DetailView): model=Post template_name = 'article_details.html' def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(ArticleDetailView, self).get_context_data(*args, **kwargs) context["cat_menu"]= cat_menu return context def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip I'm not sure how to do the logic in CBV for the count. Any suggestions? -
How to preserve parent ID and filter any further views based on that ID throughout the entire site in Django?
The context: I am working on a site (written in Django) where after selecting a main entity (e.g. a "School" from the list of "Schools") I got a context-independent navbar with fixed link structure (Location, Staff, Students, Financial statements etc.) The idea is that all the views that can be reached trough these links and sub-links are filtered based on the previously selected main entity (school) ID. How I try to solve the task: I save the School ID as a session variable upon selection, and access this variable in every single view that follows through request.session. The pain The pain is that I can't really use generic views (Generic detail view must be called with either an object pk or a slug - the error message says) and I have to write views manually, overriding the get() function of the class Based views or using function views like that: def LocationDetails(request): context = {} my_school_pk = request.session['active_school'] my_location = Location.objects.get(school=my_school_pk) context['location'] = my_location return render(request, 'location/location_details.html', context=context) The question: Do you know please a better, more concise, more elegant way for solving this issue? Thank you in advance! -
How to make google, facebook authentication in django with flutter
I am using Flutter for a mobile app and django for backend API. I want user to be able to login with accounts from Facebook, Google etc. How Can I implement this? Also I saw that dj-rest-auth provides requests for Social Media Authentication. Should I use something like this? -
Getting permission denied when I `python manage.py runserver` locally
I am running a Django app locally and I cant seem to understand why I am getting this error when I runserver. I am in a virtualenv and so I don't see why it is grabbing from outside. [ERROR 2020-10-21 19:00:36,868] base.py [:256] handle_uncaught_exception: Internal Server Error: /favicon.ico Traceback (most recent call last): File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/handlers/base.py", line 108, in get_response response = middleware_method(request) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/middleware/common.py", line 74, in process_request if (not urlresolvers.is_valid_path(request.path_info, urlconf) and File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/urlresolvers.py", line 647, in is_valid_path resolve(path, urlconf) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/urlresolvers.py", line 522, in resolve return get_resolver(urlconf).resolve(path) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/urlresolvers.py", line 366, in resolve for pattern in self.url_patterns: File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/urlresolvers.py", line 402, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/urlresolvers.py", line 396, in urlconf_module self._urlconf_module = import_module(self.urlconf_name) File "/opt/anaconda3/envs/py2/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/andynguyen/Documents/AggrigatorCode/aggrigator/site_aggrigator/urls.py", line 5, in <module> url(r'', include('accounts.urls')), File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 33, in include urlconf_module = import_module(urlconf_module) File "/opt/anaconda3/envs/py2/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/andynguyen/Documents/AggrigatorCode/aggrigator/accounts/urls.py", line 1, in <module> from accounts import views File "/Users/andynguyen/Documents/AggrigatorCode/aggrigator/accounts/views.py", line 27, in <module> import geonameszip File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/geonameszip/__init__.py", line 21, in <module> os.makedirs(BASE_DIR) File "/opt/anaconda3/envs/py2/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/var/lib/geonameszip/' -
Python Django , Couldn't import Django?
I have been learning django 3.x and I set up all necessary staff. I activated my virtual enviroment and it works, but when I try to run this command it gives me this error: Traceback (most recent call last): File "C:\Users\dzhiv\Dev\django-bootcamp\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\dzhiv\Dev\django-bootcamp\manage.py", line 22, in <module> main() File "C:\Users\dzhiv\Dev\django-bootcamp\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I have python on path enviroment.(If I had not, cmd would not show me when I type python) I created virtual envrioment(python -m venv . ) I started django project(django-admin startproject ...) I activate virtual enviroment with (.\Scripts\activate) and it works. When I run this (python manage.py createsuperuser) command I get errors. So I am on a windows 10 pc and I used powershell or VsCode's terminal(same, I know). What should I do ? -
How to curl a date for Django Rest Framework?
My model has: class Player(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE) date_of_birth = models.DateField() I am trying to send a curl like this: curl -X POST -H "Content-type: application/json" -d '{ ..., "date_of_birth":"1991-01-02"}' http://localhost:8000/api/player/ however, I get: django.db.utils.IntegrityError: null value in column "date_of_birth" violates not-null constraint DETAIL: Failing row contains (4, null, 24). I tried -
Scrapyrt not using callback functions
these are my files: views.py from uuid import uuid4 from urllib.parse import urlparse from django.core.validators import URLValidator from rest_framework.decorators import api_view, renderer_classes from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from time import sleep import os import json import requests def is_valid_url(url): validate = URLValidator() try: validate(url) # check if url format is valid except ValidationError: return False return True @csrf_exempt @api_view(['POST',]) def getProduct(request): url = request.POST['url'] if not url: return JsonResponse({'error': 'Missing args'}) if not is_valid_url(url): return JsonResponse({'error': 'URL is invalid'}) data = { "request": { "url": str(url), "callback": "start_requests", "dont_filter": "false" }, "spider_name": "GetinfoSpider" } scrapyrt = 'http://127.0.0.1:9081/crawl.json' try: #print(str(requests.post(scrapyrt, data = data))) r = requests.post(scrapyrt, json = data) print(r) return JsonResponse({'data': r}) except Exception as e: print(e) return JsonResponse({'error': str(e)}) this is my spider file getInfo.py import scrapy from scrapy_splash import SplashRequest from ..items import WallmartItem import logging class GetinfoSpider(scrapy.Spider): name:str = 'GetinfoSpider' allowed_domains = ['www.walmart.com'] script1:str = ''' function main(splash, args) splash.private_mode_enabled = false url = args.url assert(splash:go(url)) assert(splash:wait(1)) splash:set_viewport_full() return splash:html() end ''' def start_requests(self, url): yield scrapy.Request(str(url), callback=self.parse_item, meta={ 'splash': { 'args': { # set rendering arguments here 'lua_source': self.script1 }, # optional parameters 'endpoint': 'render.html', # optional; default is render.json } }) def … -
django widget_tweaks supports select tag?
Can I make something like this? {% for field in selected_products_form %} <div class="mt-2"> {% render_field field type="select" class="selectpicker" name="food" data-style="btn-primary" data-width="auto" multiple="true" data-selected-text-format="count > 2" data-live-search="true" data-actions-box="true"%} </div> <!-- HERE I WANT TO MAKE OPTIONS IN 'FOR' LOOP (THERE WILL BE A LOT OF THEM) --> {% endfor %} The problem is: tag closed after render and my 'for' loop is outside tag. Maybe I can pass my loop inside render ... But that render adding attrs inside tags, not tags that have to be inside... btw, form fields is MultipleChoiceFields. -
Django Stripe PaymentIntent
I am trying to setup the paymentIntent API from Stripe but I can't seem to figure out the error I am getting. I followed along from this video: https://www.youtube.com/watch?v=w1oLdAPyuok&t=1414s I have a react frontend which makes a request to my Django view: try { const { data: clientSecret } = await axios.post("http://127.0.0.1:8000/paymentIntent/", { amount: price * 100 }); My view: from django.shortcuts import render from django.http import HttpResponse from django.views.generic import View from django.views.decorators.csrf import csrf_exempt import logging from rest_framework.views import APIView from rest_framework import status, generics from rest_framework.response import Response from rest_framework.decorators import api_view from django.conf import settings import stripe stripe.api_key = "pk_test_51HWMwZB5hTmoPZOBJd00GjCvDYUg" @api_view(['POST']) def payment(request): try: amount = request.body paymentIntent = stripe.PaymentIntent.create( amount = amount, currency = "usd", # payment_method_types=['card'], # capture_method='manual', metadata={'integration_check': 'accept_a_payment'}, ) data = paymentIntent.client_secret return Response(data,status=status.HTTP_200_OK) except : return Response(status=status.HTTP_400_BAD_REQUEST)