Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
It is impossible to add a non-nullable field Error when extending Abstract User
I want to extend the Base Abstract User Model and this is the extended model: class Student(AbstractUser): birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=25) street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)]) city = models.CharField(max_length=20) province = models.CharField(max_length=20) code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))]) address = str(street) + str(street_number) + str(city) + str(code) + str(province) But I get this message popup: It is impossible to add a non-nullable field 'password' to student without specifying a default. This is because the database needs something to populate existing rows. However I haven't added a new password field and all the existing password fields (for the superuser) already have a value. What should I do? When I add a default value and try to migrate it, it complains that there is no such table as 'mainApp_student'. -
Is there any way to overwrite the default operation id , tag, name ,description of generated drf api schema?
Is there any way to overwrite the default operationid,name,tag,type,summary, description of generated drf api schema? -
Learning Better Way of Doing It (Django Models)
I am doing Django and I have 4 models. District, Province, Schools and User. The District belongs to a Province, in the School model/table there are the foreign keys to which the school belong. In the User table, I have district, province and school foreign keys. these tuples were named province or district in the tables they are FKs. The error I was getting was a conflict and needed to add a related_name. I need someone to explain to me the value for related_name. From my reading, it is showing the table name, If the FK is in the Comments model then the related_name='comments'. In my case I have three FK in the User model so how do I manage this? I hope this tries to explain my query. -
Django python manage.py runserver TypeError: 'dict' object is not callable
''' Environment: Request Method: GET Request URL: http://127.0.0.1:8000/league/ Django Version: 4.1.2 Python Version: 3.10.0 Installed Applications: Traceback (most recent call last): File "/Users/km/Projects/tournament/Worldchamps/champ_env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) Exception Type: TypeError at /league/ Exception Value: 'dict' object is not callable ''' -
Specifying the display of a django DateField from the model, and not form/input/settings?
I have a Django model with a DateField, like so: production_date = models.DateField(null=True, blank=True) I am trying to have that field display as the default Python date format in templates, which looks like "2000-01-01". But in a Django template it displays as "Jan. 1, 2000." In a Python shell, the date displays properly: In [4]: resource.production_date Out[4]: datetime.date(2014, 4, 20) In [5]: str(resource.production_date) Out[5]: '2014-04-20' But in the template, when I call production_date, I get the other format. I have many templates that use this value, and many ways the data gets added to the database. So I do not want to go to each template and change the display. I do not want to change the input form because that is not the only way data gets added. I do not want to change my site settings. I just want the field to display the default Python value. How do I accomplish this? Thank you! -
Error: no such table when extending Abstract User Model
I wanted to extend the Base Abstract User Model within Django to have some other Fields: class Student(AbstractUser): birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=20) street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)]) city = models.CharField(max_length=20) province = models.CharField(max_length=20) code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))]) address = str(street) + str(street_number) + str(city) + str(code) + str(province) def __str__(self): return f'Adresse: {self.address}' I added this into my settings.py file: AUTH_USER_MODEL = 'mainApp.Student' But I get an Error saying there is no such table "Student" when trying to load /admin/. I have made all the migrations using: python manage.py makemigrations mainApp python manage.py migrate mainApp Error: OperationalError at /admin/ no such table: mainApp_student If y'all need any more infos, please comment! -
How to use HTMX to send url to HTML audio element
This is what I've come up with so far. Where am I going wrong? <button hx-put="/link/to/file.mp3" hx-target="audio"> LOAD TRACK 1 </button> <audio controls> <source src="audio" type="audio/mpeg"> Your browser does not support the audio element. </audio> -
python Django get exact table filed value from JWT token
I'm coding a Django project with JWT token. 'email' is a field from user table. I want to get the exact user email by using: usereamil = request.user.email When I print it ,I got none. But if I use: username = request.user.username I can get a wired user name ,not exact one in the data base ,which I think it is a security way to protect the data. But I do want to get the exact email address of user ,so that can send email to the user. Any friend can help ? -
How can I pass in href a field of my model to put it after in the modal id
Im trying to do a dinamic list to create all the references that I already have saved. <div class="row"> <div class="col-2"> <div class="list-group" id="list-tab" role="tablist"> {% for reference in reference_list %} <a class="list-group-item list-group-item-action" id="list-home-list" data-bs-toggle="list" href={{reference.brand_manufacturer}} role="tab" aria-controls="list-home">{{reference.brand_manufacturer}}</a> {% endfor %} </div> </div> <div class="col-8"> {% for reference in reference_list %} <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show" id="{{reference.brand_manufacturer}}" role="tabpanel" aria-labelledby="list-home-list">{{reference.website_url}}</div> {% endfor %} </div> </div> </div> -
How to create a dropdown of foreign keys in a template?
Without crispy forms I can create a form as follows <form method="POST"> {% csrf_token %} <input type="text" id="name" name="name" value="{{ project.name }}"/> </div> However I do not know how to create a dropdown of foreign keys. I cannot use cripsy forms because I want to seperate the fields by headings. What is the correct methodology? -
python3.9 doesn't recognize Walrus operator :=
I created a virtual environment in python3.9. Then I installed django 4.0 framework by pip command. It's ok but surprise it seems python 3.9 doesn't recognize operator :=. This operator is been introduced in python 3.8. Why I get this error from django framework? I can't modify all files for using a normal syntax! These files are many. nicola@giustizia:/etc/apache2/sites-available$ sudo tail -f /var/log/apache2/myproj-error.log [Fri Oct 21 16:18:48.196449 2022] [wsgi:error] [pid 17067] File "/home/nicola/webgiustizia/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 12, in <module> [Fri Oct 21 16:18:48.196452 2022] [wsgi:error] [pid 17067] from django import forms [Fri Oct 21 16:18:48.196457 2022] [wsgi:error] [pid 17067] File "/home/nicola/webgiustizia/lib/python3.9/site-packages/django/forms/__init__.py", line 7, in <module> [Fri Oct 21 16:18:48.196461 2022] [wsgi:error] [pid 17067] from django.forms.fields import * # NOQA [Fri Oct 21 16:18:48.196475 2022] [wsgi:error] [pid 17067] File "/home/nicola/webgiustizia/lib/python3.9/site-packages/django/forms/fields.py", line 43, in <module> [Fri Oct 21 16:18:48.196479 2022] [wsgi:error] [pid 17067] from django.utils.dateparse import parse_datetime, parse_duration [Fri Oct 21 16:18:48.196494 2022] [wsgi:error] [pid 17067] File "/home/nicola/webgiustizia/lib/python3.9/site-packages/django/utils/dateparse.py", line 118 [Fri Oct 21 16:18:48.196501 2022] [wsgi:error] [pid 17067] if match := datetime_re.match(value): [Fri Oct 21 16:18:48.196519 2022] [wsgi:error] [pid 17067] ^ [Fri Oct 21 16:18:48.196544 2022] [wsgi:error] [pid 17067] SyntaxError: invalid syntax -
django.utils.datastructures.MultiValueDictKeyError: 'q'
When I try to filter content with tags I get the following error 2022-10-21 16:05:47,853: Internal Server Error: /tag/tag1/ Traceback (most recent call last): File "/home/app/.virtualenvs/venv/lib/python3.10/site-packages/django/utils/datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'q' **NO MATCH** During handling of the above exception, another exception occurred: **NO MATCH** Traceback (most recent call last): File "/home/app/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/app/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/app/app/blog/views.py", line 28, in home q= request.GET['q'] File "/home/app/.virtualenvs/venv/lib/python3.10/site-packages/django/utils/datastructures.py", line 86, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'q' My views.py is def home(request, tag_slug=None): posts = Post.objects.all() # tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) #search q= request.GET['q'] if q is not None: multiple_q=Q(Q(title__icontains=q) | Q(content__icontains=q)) posts=Post.objects.filter(multiple_q) return render(request, 'blog/home.html', {'posts':posts}) my urls.py has this URLpatterns ... path('tag/<slug:tag_slug>/',views.home, name='post_tag'), The search system works as I intend to but for some reason this is affecting my tag filter. Do you have any idea how to solve this error? -
Redirecting my Login page to a new page and if user is remembered and already logged in show this new page
Setting.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' LOGIN_REDIRECT_URL = '/home1' LOGIN_URL = 'login' views.py def home(request): return render(request, 'users/home.html') class RegisterView(View): form_class = RegisterForm initial = {'key': 'value'} template_name = 'users/register.html' def dispatch(self, request, *args, **kwargs): # Redireccion a Home si ya esta logged if request.user.is_authenticated: return redirect(to='/users/home1') return super(RegisterView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}') return redirect(to='login') return render(request, self.template_name, {'form': form}) class CustomLoginView(LoginView): form_class = LoginForm def form_valid(self, form): remember_me = form.cleaned_data.get('remember_me') if not remember_me: # Expira 0seg self.request.session.set_expiry(0) # Cookies self.request.session.modified = True # Hasta que los cookies expriran return super(CustomLoginView, self).form_valid(form) urls.py urlpatterns = [ re_path('admin/', admin.site.urls), re_path('', include('users.urls')), re_path('login/', CustomLoginView.as_view(redirect_authenticated_user=True, template_name='users/login.html', authentication_form=LoginForm), name='login'), re_path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), re_path('password-reset/', ResetPasswordView.as_view(), name='password_reset'), re_path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), re_path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'), path('password-change/', ChangePasswordView.as_view(), name='password_change'), re_path(r'^oauth/', include('social_django.urls', namespace='social')), re_path('home1/', auth_views.LoginView.as_view(redirect_authenticated_user=True, template_name='users/home1.html'), name='home1'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My templates Got 12 templates, home, home1, base, login, logout, register, profile, password reset, etc I continue to get a too many redirects error, or when I try and change the redirection with … -
Django Migration timed out
I have a logging table,which is being continuously written to,in which i want to add a column,it's migration works fine on local but it's getting timed out on deployment This is the migration file a have: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("request_log", "0004_requestlog2"), ] operations = [ migrations.AddField( model_name="requestlog2", name="request_type", field=models.PositiveSmallIntegerField( blank=True, choices=[(0, "Incoming"), (1, "Outgoing"), (2, "Internal")], help_text="State the type on request", null=True, ), ), ] This is the migration logs: Rendering model states... DONE Applying request_log.0005_requestlog2_request_type...django 21/Oct/2022:15:12:54,194347 +0000 [INFO] squadrun.sentry_helpers: thread=140715699507328 extra: exchash: b8ca65d21d0d448f8fe90658c0708923 detected Traceback (most recent call last): File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/elasticapm/instrumentation/packages/dbapi2.py", line 210, in execute return self._trace_sql(self.__wrapped__.execute, sql, params) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/elasticapm/instrumentation/packages/dbapi2.py", line 244, in _trace_sql result = method(sql, params) psycopg2.extensions.QueryCanceledError: canceling statement due to statement timeout The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 40, in <module> execute_from_command_line(sys.argv) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/db/migrations/executor.py", … -
Why isn't "SELECT" query run in Django?
I have person table as shown below: # "store/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=30) And, I have test view with print(Person.objects.all()) as shown below: # "store/views.py" from django.http import HttpResponse from .models import Person def test(request): print(Person.objects.all()) # Here return HttpResponse("Test") Then, when I run test view, SELECT query is run as shown below: Now, I replace print(Person.objects.all()) with Person.objects.all() as shown below: # "store/views.py" from django.http import HttpResponse from .models import Person def test(request): Person.objects.all() # Here return HttpResponse("Test") Or, I replace print(Person.objects.all()) with persons = Person.objects.all() as shown below: # "store/views.py" from django.http import HttpResponse from .models import Person def test(request): persons = Person.objects.all() # Here return HttpResponse("Test") Then, when I run test view, SELECT query isn't run as shown below: So, why isn't SELECT query run in Django? -
Django queryset filter based on slug
I want to put a filter on a page which shows videos selecting an album shows up on album page not all the videos but my current filter is showing all the published videos. I couldn't find a way to put a filter based on slug that if an album's slug is matching with the current url then shows the video selecting that album. I am all confused help me. models.py from django.db import models from django.urls import reverse STATUS = ( (1, "Publish"), (0, "Draft") ) class WatchCategory(models.Model): title = models.CharField(max_length=20) slug = models.SlugField(max_length=2000, unique=True) def __str__(self): return self.title class Genre(models.Model): title = models.CharField(max_length=20) slug = models.SlugField(max_length=2000, unique=True) def __str__(self): return self.title class Album(models.Model): title = models.CharField(max_length=2000) slug = models.SlugField(max_length=2000, unique=True) image = models.CharField(max_length=2000, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('Watch:album', kwargs={ 'slug': self.slug }) class Video(models.Model): title = models.CharField(max_length=2000) slug = models.SlugField(max_length=2000, unique=True) thumbnail = models.CharField(max_length=2000, unique=True) updated_on = models.DateTimeField(auto_now=True) file = models.CharField(max_length=2000) time = models.CharField(max_length=2000, blank=True) about = models.TextField(blank=True) category = models.ManyToManyField(WatchCategory) album = models.ManyToManyField(Album) genre = models.ManyToManyField(Genre) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=1) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('Watch:video', kwargs={ 'slug': self.slug }) views.py class Album(ListView): … -
using pipreqs getting unknown error while to create requirements.txt
pipreqs .\ the following error is comming. i searched on the google i didn't find any solution. ERROR: Failed on file: .\static\bower_components\jvectormap\converter\converter.py Traceback (most recent call last): File "C:\Users\bsant\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\bsant\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in run_code exec(code, run_globals) File "C:\Users\bsant\Pictures\lms_m16\venv\Scripts\pipreqs.exe_main.py", line 7, in File "C:\Users\bsant\Pictures\lms_m16\venv\lib\site-packages\pipreqs\pipreqs.py", line 488, in main init(args) File "C:\Users\bsant\Pictures\lms_m16\venv\lib\site-packages\pipreqs\pipreqs.py", line 415, in init candidates = get_all_imports(input_path, File "C:\Users\bsant\Pictures\lms_m16\venv\lib\site-packages\pipreqs\pipreqs.py", line 131, in get_all_imports raise exc File "C:\Users\bsant\Pictures\lms_m16\venv\lib\site-packages\pipreqs\pipreqs.py", line 117, in get_all_imports tree = ast.parse(contents) File "C:\Users\bsant\AppData\Local\Programs\Python\Python310\lib\ast.py", line 50, in parse return compile(source, filename, mode, flags, File "", line 139 raise Exception, "Wrong geometry type: "+geometryType ^ SyntaxError: invalid syntax -
How to authenticate with the right scope via OAuth in Django?
I am trying to login to my Django API from my other web app. I setup a application with the Django OAuth Toolkit (Resource owner password-based). The login works fine and I get back an accessToken but the scope I requested is not right. I get back r:profile but wanted instead rw:serverAdmin. The user is a superuser in my Django application and I also added the rw:serverAdmin scope to the oauth toolkit list. So the problem is: How do I login and have the rw:serverAdmin scope assigned? Can anybody help me with this? -
Cannot import name ... from partially initialized module
For a few days, app1 has been importing model2 I have just added model1 to app2 and I am getting this error I cannot undo this error, if I remove the line 'from app1.models import (U_model1)', the error remains - meaning the way it was set up for the last few days no longer works app1 - models.py from app2.models import (U_model2) class model1(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) name = models.CharField(max_length=100, verbose_name="Name") def __str__(self): return self.name class Meta: ordering = ('id', ) app2 - models.py from app1.models import (U_model1) class model2(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) name = models.CharField(max_length=100, verbose_name="Name") def __str__(self): return self.name class Meta: ordering = ('id', ) Why after reverting it to how it's been for the last few days by removing the line causing the error, does it no longer work? -
Django : Downloading PDF generated by the library FPDF
I have a view that contains a wizard form. When the form is submitted, a httpresponse is sent with a PDF file. I generate the PDF file with the FPDF2 Library from the data got in the form submitted by the user. To be sure that the PDF class using this library works, I tested it in a simple python script. My problem comes from the pdf that I download, I can not open it. I have an error "We can't open this file. Something went wrong". So I think that the issue is on the way I send the data of the pdf in the Httpreponse. Here is my code : class FormWizardQR(SessionWizardView): template_name = "invoices/qr.html" form_list = [FormStepOneBeneficiary, FormStepTwoPaymentInfos, FormStepThreeDebtor] def done(self, form_list, **kwargs): # GET DATA FROM FORMS form_data = dict(ChainMap(*[form.cleaned_data for form in form_list])) # PREPARE DATA FOR QR-PDF GENERATOR list_str_pay_to = [form_data.get('iban_beneficiary'), form_data.get('name_beneficiary'), f"{form_data.get('street_beneficiary')} {form_data.get('street_number_beneficiary')}", f"{form_data.get('npa_beneficiary')} {form_data.get('locality_beneficiary')}", form_data.get('country_beneficiary')] list_str_pay_by = [form_data.get('name_debtor'), f"{form_data.get('street_debtor')} {form_data.get('street_number_debtor')}", f"{form_data.get('npa_debtor')} {form_data.get('locality_debtor')}", form_data.get('country_debtor')] reference = form_data.get('ref_number') # GENERATE QR-IMAGE qr = SWISS_QR(data="https://www.20min.ch/fr") image_qr = qr.generate_qr() pdf = PDF('portrait', 'mm', 'A4') pdf.set_margins(left=0, top=0, right=0) pdf.add_page() pdf.border_bill() pdf.r_title("Récépissé") pdf.r_zone_indications(reference=reference, list_str_pay_to=list_str_pay_to, list_str_pay_by=list_str_pay_by) pdf.output(name="myfilename.pdf", dest="S") print(type(pdf)) print(pdf) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=myfilename.pdf" return … -
Django admin get updated model (and updated relative models that are inlines) when "Save" is clicked
I have a model named User and it has some fields, and also some relative models. It's registered in the admin page and some of its relative models are registered as inlines of it. Now, I have a function let's call it update_api(user) which takes the user as an argument (which is an instance of class User) and sends it to an API. Note that this function also uses the relative models of User. I want to call update_api when a user is saved in the admin page but I want all his fields and relative inline models to be updated. Moreover I want this function to be called only once per save. I have tried overriding User.save() or UserAdmin.save_model() but that lead me nowhere because the related fields were not updated by then. When user is saved via a view, I call this function manually at the end after doing a request.user.refresh_from_db(). -
Doubled value when using annotate Sum,Count
I am using this code and I get a result which is not what I expect queryset= User.objects.annotate(earned_leave=Sum('logs__work_hours')) Here is my data "logs": { "id": 96, "time_in": "11:43:34", "time_out": "21:25:49", "user": "admin", "date_created": "2022-10-21", "work_hours": 10, "last_action": "logout", "earned_credit": "0.38400" } and here is the result "earned_leave": 20 Tried this solution but I'm not comfortable with it queryset= User.objects.annotate(earned_leave=Sum('logs__work_hours')/2) I cannot use distinct=True since it won't count same values -
DRF multiple update with reduced database hits
I'm using DRF's example of multiple updates which works fine except every self.child.update is a separate update query to the database. Is there a way I can rewrite this to call the updates as one query as a bulk update? class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): book_mapping = {book.id: book for book in instance} data_mapping = {item['id']: item for item in validated_data} ret = [] for book_id, data in data_mapping.items(): book = book_mapping.get(book_id, None) ret.append(self.child.update(book, data)) return ret class BookSerializer(serializers.Serializer): id = serializers.IntegerField() class Meta: list_serializer_class = BookListSerializer -
Django ORM question about methods for the QuerySet Object
Can someone explain to me why you can use a method like count() for a QuerySet Object but something like pop() does not work. -
Djstripe: ensuring new subscription payment succeeds before confirming successful subscription to customer
We use Djstripe to create Stripe subscriptions on our Django site like so: # Create the Stripe subscription stripe_subscription = stripe.Subscription.create( customer=customer_id, items=[{'price': plan_id}], expand=['latest_invoice.payment_intent'], metadata=metadata, ) # Sync subscription from Stripe subscription = Subscription.sync_from_stripe_data(stripe_subscription) The process on Stripe's end seems to be something like: Create the subscription (return status 200) Create the payment intent object that will charge the customer for the subscription Attempt to charge the customer If the charge fails, put the subscription to status "incomplete" Naively, when we get 200 back from step (1), we proceed as if the payment went through ok, but sometimes it doesn't (step (4) happens). What is a good way to confirm a successful subscription creation to the customer oly if the subsequent charge succeeds?