Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting a relay not permitted error with Exim4
I am currently getting the following error: 2019-06-28 14:45:41 no host name found for IP address 192.168.X.X 2019-06-28 14:45:41 H=(cabc5b9f0d80) [192.168.X.X] F=<noreply@X.X.X.X> rejected RCPT <example@exmple.com>: relay not permitted My update-exim4.conf.conf looks as follows: dc_eximconfig_configtype='smarthost' dc_other_hostnames='example.com; localhost.localdomain; localhost' dc_local_interfaces='127.0.0.1 ; ::1' dc_readhost='example.com' dc_relay_domains='*' dc_minimaldns='false' dc_relay_nets='smtpserver.url' dc_smarthost='example.com' CFILEMODE='644' dc_use_split_config='false' dc_hide_mailname='' dc_mailname_in_oh='true' dc_localdelivery='mail_spool' When I run echo "Subject: sendmail test" | sendmail -v example@exmple.com, I receive the email which leads me to believe the config is fine, HOWEVER, when I attempt to send the email via my django app that is hosted on the same server I get the above error. My app conf looks as follows: EMAIL_HOST = "example.com" EMAIL_PORT = 25 EMAIL_NAME = "exmaple" EMAIL_ALIAS = "noreply@X.X.X.X" EMAIL_HOST_USER = "" EMAIL_HOST_PASSWORD = "" EMAIL_USE_TLS = False EMAIL_BATCH_SIZE = 50 EMAIL_BATCH_PAUSE = 300 The error in the app's logs is as follows: Task scheduler.tasks.workflow_send_email[740b2e55-896e-4a75-9e19-4fa5562783e2] raised unexpected: SMTPRecipientsRefused({'example@example.com': (550, b'relay not permitted')},) ... smtplib.SMTPRecipientsRefused: {'example@example.com': (550, b'relay not permitted')} -
Django reverse 'str' object has no attribute 'get'
I am trying to use reverse method in django view but I got an exception 'str' object has no attribute 'get'. here is my view class AbandonTicketView(View): context = dict() template_name = "places/order_detail.html" def get(self, request, uidb64, token, ordercode): order = abandon_oder(uidb64, token, ordercode) if order is not None and order.paid is False: return reverse("order_detail", kwargs={"ordercode": order.code}) return redirect("tickets") view that I want to go: class OrderDetailView(LoginRequiredMixin, View): template_name = "places/order_detail.html" context = dict() def get(self, request, ordercode): order = Order.objects.get(code=ordercode) self.context["order"] = order self.context["key"] = settings.tycoon.STRIPE_PUBLISHABLE_KEY if order.send_count >= 3 and order.paid is False: self.context["abandon_ticket"] = "Order was canceled" return render(request, template_name=self.template_name, context=self.context) def post(self, request, ordercode): order = pay_for_ticket(ordercode, request.POST["stripeToken"], request.user) self.context["order"] = order return render(request, template_name=self.template_name, context=self.context) here is url: path("orders/<code:ordercode>/detail/", views.OrderDetailView.as_view(), name="order_detail"), path("tickets/", views.OrderedTicketsView.as_view(), name="tickets"), I don't really know why it happends, because I do the similar reverse earlier and everything works fine, but not now. Could you help me please to solve this problem? -
SPAM appears at the beginning of the message title
I have a problem with sending email messages. When I send a message from the contact form in django 1.5 and receive a message - the word SPAM appears at the beginning of the message title. Email address is not on blacklist. When I am sending message on my local machine, everything is OK. email = EmailMessage( 'Contact', message, 'mail@from.com', [form.cleaned_data['email'] ], ['bcc@addressbcc.com'], headers={'X-PremiumMailfilter-Spam-Flag': 'NO'}, ) email.send() -
How to include API views in app's urls when the API is just a bunch of views in a module?
I want to create some API views for my Django app. Given that I will not be using Django REST Framework nor creating a separate app for this API, how can I incorporate such views in my app? My idea is to create api.py module in the app's folder at the same level as views.py sit and write those views there. But how do I include such API's urls in the urls.py of the app, which currently looks like this?: from django.urls import path from . import views, # import api as well? app_name='analyzer' urlpatterns = [ path('', views.index, name='index'), #how to inlclude views from api.py here? ] -
?: (urls.W005) URL namespace 'main' isn't unique. You may not be able to reverse all URLs in this namespace
getting this error when i am using the python manage.py runserver this is my project url (mysite/url): from django.contrib import admin from django.urls import path, include from users import views as user_views urlpatterns = [ path('register/', user_views.register, name='register'), path('', include('main.urls')), path('admin/', admin.site.urls), path('about/', include('main.urls')), ] and this is my first app url (main/url) from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('', views.blog, name='blog'), path("about/", views.about, name="about"), ] and this is my second app url(users/urls): actually there is no urls in my second app but the register template we will find it in second app. I will be thankful. if You find a solution :) -
SSL certificate thowing error on Mobile Network
My domain is: www.habibindustry.com I have set a Django host on Ubuntu 18.04 with Nginx, Gunicorn. Then I set up my certbot to install Let’s encrypt SSL. It is working fine with both Desktop and Mobile over wifi network. But when I switch to Mobile Network it says : The page you are trying to view can not be shown because the authenticity of the received data could not be verified. Here is SSL Lab report : https://www.ssllabs.com/ssltest/analyze.html?d=www.habibindustry.com These are the instructions from DigitalOcean I followed : https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 -
Detect in django view whether web sockets are connected or not
I am working on a project where websockets are being used extensively.Sometimes it happens that though message has been sent from django view but the client doesn't receive that message.On analyzing the logs i saw that sometimes messages are being sent even if websockets in the Group are connected or not. Like i have a django view in which if certain conditions are met then a message is sent to the Group.Its like this:- def send_message(request): #some existing lines of code if(some_condition): Group("receivers").send({"text":json.dumps({"key1":"value1","key2":"value2"})}) I want to know before sending the message to "receivers" Group whether websockets of this group are connected or not. If they are not connected then code should wait till the websockets get connected and then message is sent. So overall it should be like this: def send_message(request): #some existing lines of code if(some_condition): if(websockets_are_not_connected): wait_for_websockets_to_get_connected elif(websockets_are_connected): Group("receivers").send({"text":json.dumps({"key1":"value1","key2":"value2"})}) PS: I am using django=1.11,channels==1.1.8 and redis as a message broker. -
django.db.utils 2006, 'Can\'t connect to local MySQL \'/var/run/mysqld/mysqld.sock\'
Trying to docker-compose up and permanently bumping into the issue with SQL socket. here is my docker-compose.yml version: '3' services: web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" container_name: jl_backend volumes: - .:/jl_backend ports: - "8000:8000" depends_on: - db db: image: mysql:latest command: mysqld --default-authentication-plugin=mysql_native_password volumes: - "./mysql:/var/lib/mysql" ports: - "3307:3307" # changed the port from 3306 so that it doesnt bump into SQL restart: always environment: here is the error: jl_backend | return Connection(*args, **kwargs) jl_backend | File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 208, in init jl_backend | super(Connection, self).init(*args, **kwargs2) jl_backend | django.db.utils.OperationalError: (2006, 'Can\'t connect to local MySQL server through socket \'/var/run/mysqld/mysqld.sock\' (2 "No such file or directory")') jl_backend exited with code 1 -
How to synchronize my local PostgreSQL with my heroku database for my website built using Django?
I have created a website using Django as backend and recently hosted it with heroku. Also, I have uploaded my local database on heroku, now I have added some more rows in my local database and want to synchronize my local database with my heroku database so that whenever I add some items in my local database, it is also added to the heroku database. How should I proceed? -
Managing client connections with Django channels
Disclaimer: This is a bit of a systems design question. I googled where to post system design questions and found a meta stack exchange thread that suggested stack overflow was the place. Feel free to redirect me if that’s not true. I’m trying to accomplish real time speech to text with django + websockets. I’m using nexmo to make a call + stream the audio back to my server. I'm then streaming the audio to watson speech to text to get the transcripts. I'm then streaming the transcripts back to a react frontend via websockets. I've managed to do this with tornado, but would like to use django channels. I’m stumbling on how to create / persist a client websocket connection to watson within a consumer. Here’s a simplified version of my problem: In the receive method of a django consumer: I’m catching a specific message to open a client websocket connection to watson I’m streaming audio from nexmo -> my server -> watson def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] if message == “open”: self.watson = openWatsonWebsocket() if message == “audio”: sendAudioToWatson(self.watson) I’ve been having a hard time opening / persisting the watson websocket call. There is … -
How to perform incremental operator in django template
I'm trying to fetch the number unread messages in a chat, It works fine in the django shell but i ran into a problem in the template because i cant use incremental operator In the django shell, i used the following codes # After importing the required models unread = 0 for message in chat.messages.all(): if message.read != True: unread += 1 This works fine In the template, I used the code below {%for message in chat.messages.all %} {% with unread=0 %} {% if message.read != True %} {{unread+=1}} {% endif %} {% endwith %} <span class="badge badge-light badge" style="margin-top: 27px; font-size: 2.5em; float:right; border-radius: 1.0rem;">{{unread}}</span> {%endfor%} I want to be able to output the number of unread messages like i could in the django shell -
How to pass queryset data with multiple relationships to a template in Django
I am working on a project with models that have a multiple OneToOne and OneToMany relationship. The main model, Listing, has 4 other models referring to it with a OneToOne model depending on the type. The other model ListingImages model has a OneToMany relationship with the Listing model. So, I want to pass data from the Listing model and any other related data from the ListingImages and the other 4 models as may be necessary to the template. To make this clearly understood here is the code from attached: models.py from django.db import models from django.contrib.auth.models import User from location_field.models.plain import PlainLocationField from PIL import Image from slugify import slugify from django.utils.translation import gettext as _ from django.core.validators import MaxValueValidator, MinValueValidator from listing_admin_data.models import (Service, SubscriptionType, PropertySubCategory, PropertyFeatures, VehicleModel, VehicleBodyType, VehicleFuelType, VehicleColour, VehicleFeatures, BusinessAmenities, Currency ) def current_year(): return datetime.date.today().year def max_value_current_year(value): return MaxValueValidator(current_year())(value) class Listing(models.Model): listing_type_choices = [('P', 'Property'), ('V', 'Vehicle'), ('B', 'Business/Service'), ('E', 'Events')] listing_title = models.CharField(max_length=255) listing_type = models.CharField(choices=listing_type_choices, max_length=1, default='P') status = models.BooleanField(default=False) featured = models.BooleanField(default=False) city = models.CharField(max_length=255, blank=True) location = PlainLocationField(based_fields=['city'], zoom=7, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) expires_on = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True ) listing_owner = models.ForeignKey(User, on_delete=models.CASCADE, … -
How to get into details view from another details view and get all the queryset in template properly?
I need to get into details view from another details view..but i can't pass the queryset clearly... In models: class Match(models.Model): mega_league = models.ManyToManyField('MegaLeague', blank=True) class MegaPricePoolBreak(models.Model): pass class MegaLeague(models.Model): price_pool_break = models.ManyToManyField(MegaPricePoolBreak, blank=True) In views: def league(request): match = Match.objects.all() context = { 'match': match, } return render(request, 'main/league.html', context=context) def league_detail(request, pk): match = get_object_or_404(Match, pk=pk) context = { 'match': match, } return render(request, 'main/league_detail.html', context=context) def league_detail_more(request, pk): match = get_object_or_404(Match, pk=pk) context = { 'match': match, 'title': 'select matches', } return render(request, 'main/league_detail_more.html', context=context) In league template, i pass {% url 'league_detail' match.pk %} to get queryset from Match into league_detail template and in league_detail template i pass {% url 'league_detail_more' match.pk %}---here is the main problem..it pass all the pk of Match but i need to pass match.pk and match.mega_league.pk to get queryset from Match into league_detail_more template.. In all template i use for loop..it's working...but to get specific pk query is not working.. It is working for league_detail template but not for league_detail_more template..in league_detail_more template pk pass from league_detail is not working. How can i get the all the queryset clearly for both template using match = get_object_or_404(Match, pk=pk)?? -
Why do I get a userId duplicate key error even though my model does not have user as the primary key?
I have an Interactions model which inherits from the predefine django user model, but I have the messageId to be the primary key. models.py: class Interaction(models.Model): messageId = models.TextField(max_length=5000,primary_key=True, unique = True) user = models.OneToOneField(User, primary_key = False, on_delete=models.CASCADE) reciever = models.TextField(max_length=5000,blank=True,default='') sender = models.TextField(max_length=5000,blank=True,default='') date = models.TextField(max_length=5000,blank=True,default='') subject = models.TextField(max_length=5000,blank=True,default='') label = models.TextField(max_length=5000,blank=True,default='') I have a dictionary called data which stores the information required. In views.py entry, created = Interaction.objects.get_or_create(messageId=data['id']) entry.user = request.user entry.sender = data['from'] entry.reciever = data['to'] entry.date = data['date'] entry.subject = data['subject'] entry.label = data['label'] entry.save() So while running the code there are messages with the same user but obviously different message ids user is not my primary key yet I keep getting the error djongo.sql2mongo.SQLDecodeError: FAILED SQL: UPDATE "mainapp_interaction" SET "user_id" = %(0)s, "reciever" = %(1)s, "sender" = %(2)s, "date" = %(3)s, "subject" = %(4)s, "label" = %(5)s WHERE "mainapp_interaction"."messageId" = %(6)s Pymongo error: {'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: 5d02255b9ccf640b8c608ee1_mysitev6.mainapp_interaction index: user_id_1 dup key: { : 16 }'} -
How to save and display previously entered values in the form fields?
I have 2 forms per page. Here is one of them. $('form').submit(function(e) { e.preventDefault(); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form action="" method="post"> <div> <label for="sum">Sum</label> <input id="sum" type="number"> <label for="currency">Currency</label> <select id="currency"> <option value="KZT">KZT</option> <option value="USD">USD</option> </select> </div> <div> <label for="term">Term</label> <select id="term"> <option value="1">1 month</option> <option value="3">3 months</option> </select> </div> <input type="submit" value="Submit"> </form> forms.py class CreditFilterForm(forms.Form): sum = forms.CharField() currency = forms.ChoiceField(choices = CURRENCY_CHOICES, ...) term = forms.ChoiceField(choices = PERIOD_CHOICES, ...) views.py CreitsListView(ListView): ... def get(self): little_form = CreditFilterForm(self.request.GET or None, prefix="little") class LittleFormView(FormView): form_class = CreditFilterForm prefix = 'little' def form_valid(self, form): ... Now, when the user entered the data and reloaded the page (without a submit), or when he simply closed the page and opened it again after some time - the entered data disappears. How can I save and display them? It is necessary to use caching. Or store the entered values in the database, and then substitute them? -
AWS Lambda Couldn't load 'Argon2PasswordHasher' algorithm library
I am using Zappa to deploy my backend application. I can login to the /admin normally while I am running local on OSX 10.14.2. Then I try deploy on AWS Lambda. Endpoint works fine. But /admin/ returns to me Couldn't load 'Argon2PasswordHasher' algorithm library I had followed this, but does not work. I have both of the dependencies according to official docs django[argon2]==2.2.2 argon2-cffi==19.1.0 zappa==0.48.2 I also check with Django issue. It has been solved 4 years ago I have never not got this issue while I was working with EC2 or any VM except AWS Lambda serverless Where am I wrong? -
Django Rest shows TemplateDoesNotExist
I am trying to learn django rest on a existing blog project. My project has a model named "BlogPost". There I have created an endpoint to GET the blogpost object. I can create a blog successfully from django admin, but whenever I give the url "http://127.0.0.1:8000/api/postings/1/", it shows the error "TemplateDoesNotExist at /api/postings/1/", while there isn't any error in my terminal. it shows "GET /api/postings/1/ HTTP/1.1" 500 85630. Can anyone help me where am I doing wrong? from django.conf import settings from django.db import models from django.urls import reverse class BlogPost(models.Model): # pk aka id --> numbers user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=120, null=True, blank=True) content = models.TextField(max_length=120, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user.username) views.py: from rest_framework import generics from postapp.models import BlogPost from .serializers import BlogPostSerializer class BlogPostRudView(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'pk' serializer_class = BlogPostSerializer def get_queryset(self): return BlogPost.objects.all() Here is the serializer: from rest_framework import serializers from postapp.models import BlogPost class BlogPostSerializer(serializers.ModelSerializer): class Meta: model = BlogPost fields = [ 'pk', 'user', 'title', 'content', 'timestamp', ] My urls.py inside the api from .views import BlogPostRudView from django.urls import path urlpatterns = [ path('<int:pk>/', BlogPostRudView.as_view(), name='post-rud') ] and my urls.py inside the project: from django.contrib import … -
ValueError The QuerySet value for an exact lookup must be limited to one result using slicing on django views
am Getting this error i cant figure a way to solve it here are the views.py class SellerTransactionListView(ListView): model = Transaction template_name = "sellers/transaction_list_view.html" def get_queryset(self): account = SellerAccount.objects.filter(user=self.request.user) if account.exists(): products = Product.objects.filter(seller=account) return Transaction.objects.filter(product__in=products) return [] template transaction_list_view.html {% extends "base.html" %} {% block content %} <h1>Transactions</h1> <ul> {% include "sellers/transaction_list.html" with transaction_list=object_list %} </ul> {% endblock %} and the transaction_list.html <table> <thead> <th>Product</th> <th>User</th> <th>order_id</th> <th>Sale Total</th> <th></th> </thead> <tbody> {% for trans in transaction_list %} <tr> <td>{{ trans.product }}</td> <td>{{ trans.profile }}</td> <td>{{ trans.order_id }}</td> <td>{{ trans.amount }}</td> <td>{{ trans.timestamp|timesince }} ago</td> </tr> {% endfor %} </tbody> </table> if i change the transaction_list_view.html the include part to {% include "sellers/transaction_list.html" with transaction_list=transactions %} the error disappears but the transactions are not showing. -
How can i update a django template in real time?
In this template i'm retrieving the price of Bitcoin from an API. At the actual moment, the price will be updated only when the page is refreshed, while i would like it to be updated without refreshing the whole page, dynamically. This is my view: def home(request): symbol = "BTCUSDT" tst = client.get_ticker(symbol=symbol) test = tst['lastPrice'] context={"test":test} return render(request, "main/home.html", context ) And the template's line looks something like this: <h3> var: {{test}} </h3> There are two problems here: 1) From the little i know, Django itself is not asynchronous, so i need to find a way to update that part of the template in real time, without having to refresh the whole page. 2) At the actual moment, the API is requested when the page is opened/refreshed, but to stream the price, it should be always running. I tried this (awful) solution: add a while true in the view, but of course it broke my code, executing only the part the while statement. Any advice is appreciated :) -
saving dynamic form elements in database
I have a dynamic form inputs in UI which users can add rows or remove but I do not have an idea how to store this elements in DB. I have looked at some answer which was done with function based views but I am using CBV. my code looks like this models.py class Item(models.Model): item_name = models.CharField(max_length=200) sku = models.CharField(max_length=200) barcode = models.CharField(max_length=200) category = models.CharField(max_length=200) views.py class ItemCreateView(CreateView): model = Item template_name = 'items/item_form.html' fields = ['item_name', 'sku', 'barcode', 'category'] def form_valid(self): #some code here here is the my code this input field can be dynamic according to number of item. Then how can I store them with CBV? and Which way is better to save in this condition? Thanks a lot in advance! -
Not able to access data using 'categories.products .all ' in template view. Django Models with foreign key
I have models that have relation using a foreign key. class Cat1(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length = 100) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50) productId = models.AutoField(max_length=50,primary_key=True) productType = models.CharField(max_length=50) matType = models.CharField(max_length=100,default='Use comma , to seperate multiple materials') seller = models.ForeignKey(User, related_name='sellers',on_delete=models.CASCADE,default='NA') cat_1 = models.ForeignKey(Cat1,related_name='catlevel1',on_delete=models.CASCADE,default='NA') Then i have my views of the page. where i need to display all the product from the category i have clicked on. My View is : def cat_products(request,pk): categories = get_object_or_404(Cat1, pk=pk) #here the categories get the category i clicked on homepage. products = Product.objects.all() return render(request, 'products.html', {'categories':categories,'products':products}) Then products.html is: <!--Full Code not shown for easy understanding--> {% for prod in categories.products.all %} {{categories.name}} <tr> <td>{{ prod.name }}</td> <td>{{ prod.matType }}</td> <td>0</td> <td>0</td> <td>0</td> </tr> {% endfor %} So basically categories is the the name that can be used to access current category.Products is the list of all products. I have tried this code above which yield no result. <!--Full Code not shown for easy understanding--> {% for prod in products %} {{categories.name}} <tr> <td>{{ prod.name }}</td> <td>{{ prod.matType }}</td> <td>0</td> <td>0</td> <td>0</td> </tr> {% endfor %} i have tried only printing all the products {% … -
How to pass multiple product ids while object creation?
I have a service master class in which the user can add multiple products. I'm unable to figure out how to do it? One possible idea for me was to use the Many2Many field but I wanted to know is there any other way? I also thought about creating separate relation table in which I will store the service id and the product id but my question is how do I pass that in the response after creating the service? -
How to set a callable function to AutoField default attribute?
I'm trying to overwrite the pk of my models to use a random generator. Here's the model field: pk = models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', default=genkey) and the keygenerator: def genkey(): return random.randrange(1,142857) So, I would like to make the autofield to execute the genkey function as much as possible until it gets a non-used key. Is there an attribute that I didn't find or do I need to code it in the generator (by getting all the used keys) ? My main goal is to make a generator as generic as possible, not define a custom generator for each model. -
How to change default web location from root user directory to another user directory in Nginx?
I'm new to Nginx I've created Django app and deployed in root user home directory due to some reasons I need to move it to some other user home directory; I've changed everything but when i access to the website it is still pointing to app from same root user directory. Previously /etc/uwsgi/sites/djangoproject.ini [uwsgi] project = djangoproject username = root base = /%(username) chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 5 uid = %(username) socket = /run/uwsgi/%(project).sock chown-socket = %(username):nginx chmod-socket = 660 vacuum = true Currently: /etc/uwsgi/sites/djangoproject.ini [uwsgi] project = djangoproject username = jenkins base = /scratch/%(username) chdir = /home/%(username)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 5 uid = %(username) socket = /run/uwsgi/%(project).sock chown-socket = %(username):nginx chmod-socket = 660 vacuum = true Currently: /etc/nginx/nginx.conf #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; server { listen 8001; listen svcpjanjana.nms.fnc.fujitsu.com:8001; server_name svcpjanjana.nms.fnc.fujitsu.com; location = favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/jenkins/djangoproject; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/djangoproject.sock; } } Previously: /etc/nginx/nginx.conf #user nobody; … -
how can i check whether a Stripe customer already has a specific card before adding a new one in django python
I want to store multiple card on stripe for customer.In this, customer try to add new card on stripe at that time check if this card store or not in django python I use below code to add customer card on stripe card = stripe.Customer.create_source( 'customer_stripe_id' source =request.POST['stripeToken'] )