Django项目中调用Stripe Customer.create方法报错:'function has no attribute'
stripe.Customer.create() in Django Hey there! Let's break down why you're hitting that annoying attribute error when trying to create a Stripe Customer in your Django view. Here are the most common fixes to get you back on track:
1. Check for Variable Name Conflicts
The #1 culprit here is often a variable or function in your code that's named stripe, which overrides the imported Stripe module. For example, if somewhere in your file you have something like:
stripe = "some_payment_string" # OR def stripe(): # ... some unrelated code
This turns stripe from the Stripe SDK module into a string or function, so stripe.Customer won't exist anymore.
Fix: Search your entire file (and any imported modules) for any instances where you've named something stripe and rename it to something else (like stripe_service or stripe_api_handler).
2. Verify Stripe SDK Installation & Version
Sometimes an incomplete or outdated installation can cause unexpected attribute issues.
- First, confirm the Stripe SDK is properly installed by running:
This should display the version number and installation details. If it doesn't, reinstall and upgrade it with:pip show stripepip install --upgrade stripe - For newer versions of the Stripe SDK (v2020+),
stripe.Customer.create()is still the correct syntax, but ensure you're following the docs matching your installed version.
3. Ensure You've Set Your Stripe API Key
While this won't directly cause an attribute error, it's a critical missed step that can lead to other failures later. Before making any API calls, you need to set your Stripe secret key. The best practice is to pull this from your Django settings instead of hardcoding it:
import stripe from django.conf import settings from django.shortcuts import redirect, reverse # Set the API key once at the top of your file stripe.api_key = settings.STRIPE_SECRET_KEY def charge(request): amount = 5 if request.method == 'POST': print('Data:', request.POST) try: # Create the customer with error handling customer = stripe.Customer.create( description="My First Test Customer (created for API docs)", ) print(f"Successfully created customer: {customer.id}") except AttributeError as e: # Debug check to see what `stripe` actually is print(f"Error details: {e}") print(f"Type of 'stripe' object: {type(stripe)}") # Should be <class 'module'> if imported correctly return redirect(reverse('success', args=[amount]))
Quick Debug Tip
If you're still stuck, add a print statement right before the stripe.Customer.create() call to check what stripe actually is:
print(type(stripe))
If this outputs anything other than <class 'module'>, you know something is overriding your imported Stripe module.
内容的提问来源于stack exchange,提问作者Mihir Kohli

