1660393740
Trong hướng dẫn này, tôi sẽ trình bày cách định cấu hình trang web Django mới từ đầu để chấp nhận thanh toán một lần bằng Stripe .
Hiện có ba cách để chấp nhận thanh toán một lần với Stripe:
Bạn nên sử dụng cái nào?
Mặc dù bạn vẫn có thể sử dụng API tính phí, nhưng nếu bạn mới sử dụng Stripe, đừng sử dụng nó vì nó không hỗ trợ các quy định ngân hàng mới nhất (như SCA ). Bạn sẽ thấy tỷ lệ từ chối cao. Để biết thêm thông tin, hãy xem lại trang API ý định thanh toán so với khoản phí từ tài liệu chính thức của Stripe.
Bạn vẫn sử dụng API tính phí? Nếu hầu hết khách hàng của bạn sống ở Hoa Kỳ hoặc Canada, bạn chưa cần phải di cư. Xem lại hướng dẫn hướng dẫn di chuyển Checkout để biết thêm thông tin.
Tạo một thư mục dự án mới cùng với một dự án Django mới có tên djangostripe
:
$ mkdir django-stripe-checkout && cd django-stripe-checkout
$ python3.10 -m venv env
$ source env/bin/activate
(env)$ pip install django==3.2.9
(env)$ django-admin startproject djangostripe .
Hãy trao đổi virtualenv và Pip cho thơ hoặc Pipenv . Để biết thêm, hãy xem lại Môi trường Python hiện đại .
Tiếp theo, tạo một ứng dụng mới có tên payments
:
(env)$ python manage.py startapp payments
Bây giờ, hãy thêm ứng dụng mới vào INSTALLED_APPS
cấu hình trong settings.py :
# djangostripe/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Local
'payments.apps.PaymentsConfig', # new
]
Cập nhật tệp urls.py cấp dự án với payments
ứng dụng:
# djangostripe/urls.py
from django.contrib import admin
from django.urls import path, include # new
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('payments.urls')), # new
]
Cũng tạo tệp urls.py trong ứng dụng mới:
(env)$ touch payments/urls.py
Sau đó điền nó như sau:
# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
]
Bây giờ hãy thêm tệp views.py :
# payments/views.py
from django.views.generic.base import TemplateView
class HomePageView(TemplateView):
template_name = 'home.html'
Và tạo một thư mục và tệp "mẫu" dành riêng cho trang chủ của chúng tôi.
(env)$ mkdir templates
(env)$ touch templates/home.html
Sau đó, thêm HTML sau:
<!-- templates/home.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django + Stripe Checkout</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
</head>
<body>
<section class="section">
<div class="container">
<button class="button is-primary" id="submitBtn">Purchase!</button>
</div>
</section>
</body>
</html>
Đảm bảo cập nhật tệp settings.py để Django biết tìm thư mục "mẫu":
# djangostripe/settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'], # new
...
Cuối cùng chạy migrate
để đồng bộ cơ sở dữ liệu và runserver
khởi động máy chủ web cục bộ của Django.
(env)$ python manage.py migrate
(env)$ python manage.py runserver
That's it! Check out http://localhost:8000/ and you'll see the homepage:
Time for Stripe. Start by installing it:
(env)$ pip install stripe==2.63.0
Next, register for a Stripe account (if you haven't already done so) and navigate to the dashboard. Click on "Developers":
Then in the left sidebar click on "API keys":
Each Stripe account has four API keys: two for testing and two for production. Each pair has a "secret key" and a "publishable key". Do not reveal the secret key to anyone; the publishable key will be embedded in the JavaScript on the page that anyone can see.
Hiện tại, nút chuyển đổi cho "Xem dữ liệu kiểm tra" ở phía trên bên phải cho biết rằng chúng tôi đang sử dụng các khóa kiểm tra ngay bây giờ. Đó là những gì chúng tôi muốn.
Ở cuối tệp settings.py của bạn , thêm hai dòng sau bao gồm bí mật kiểm tra của riêng bạn và kiểm tra khóa có thể xuất bản. Đảm bảo bao gồm các ''
ký tự xung quanh các phím thực tế.
# djangostripe/settings.py
STRIPE_PUBLISHABLE_KEY = '<your test publishable key here>'
STRIPE_SECRET_KEY = '<your test secret key here>'
Cuối cùng, bạn sẽ cần chỉ định "Tên tài khoản" trong "Cài đặt tài khoản" của mình tại https://dashboard.stripe.com/settings/account :
Tiếp theo, chúng ta cần tạo ra một sản phẩm để bán.
Nhấp vào "Sản phẩm" và sau đó "Thêm sản phẩm":
Thêm tên sản phẩm, nhập giá và chọn "Một lần":
Nhấp vào "Lưu sản phẩm".
Sau khi người dùng nhấp vào nút mua hàng, chúng ta cần thực hiện các thao tác sau:
Get Publishable Key
Create Checkout Session
Redirect the User Appropriately
Confirm Payment with Stripe Webhooks
Let's start by creating a new static file to hold all of our JavaScript:
(env)$ mkdir static
(env)$ touch static/main.js
Add a quick sanity check to the new main.js file:
// static/main.js
console.log("Sanity check!");
Sau đó, cập nhật tệp settings.py để Django biết nơi tìm tệp tĩnh:
# djangostripe/settings.py
STATIC_URL = '/static/'
# for django >= 3.1
STATICFILES_DIRS = [BASE_DIR / 'static'] # new
# for django < 3.1
# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] # new
Thêm thẻ mẫu tĩnh cùng với thẻ tập lệnh mới bên trong mẫu HTML:
<!-- templates/home.html -->
{% load static %} <!-- new -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django + Stripe Checkout</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
<script src="{% static 'main.js' %}"></script> <!-- new -->
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
</head>
<body>
<section class="section">
<div class="container">
<button class="button is-primary" id="submitBtn">Purchase!</button>
</div>
</section>
</body>
</html>
Chạy lại máy chủ phát triển. Điều hướng đến http: // localhost: 8000 / và mở bảng điều khiển JavaScript. Bạn sẽ thấy kiểm tra sự tỉnh táo:
Tiếp theo, thêm một chế độ xem mới vào Payment / views.py để xử lý yêu cầu XHR:
# payments/views.py
from django.conf import settings # new
from django.http.response import JsonResponse # new
from django.views.decorators.csrf import csrf_exempt # new
from django.views.generic.base import TemplateView
class HomePageView(TemplateView):
template_name = 'home.html'
# new
@csrf_exempt
def stripe_config(request):
if request.method == 'GET':
stripe_config = {'publicKey': settings.STRIPE_PUBLISHABLE_KEY}
return JsonResponse(stripe_config, safe=False)
Thêm cả một URL:
# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('config/', views.stripe_config), # new
]
Tiếp theo, sử dụng API Tìm nạp để thực hiện một yêu cầu XHR (XMLHttpRequest) tới /config/
điểm cuối mới trong static / main.js :
// static/main.js
console.log("Sanity check!");
// new
// Get Stripe publishable key
fetch("/config/")
.then((result) => { return result.json(); })
.then((data) => {
// Initialize Stripe.js
const stripe = Stripe(data.publicKey);
});
Phản hồi từ một fetch
yêu cầu là một luồng có thể đọc được . result.json()
trả về một lời hứa, mà chúng tôi đã giải quyết cho một đối tượng JavaScript - ví dụ data
:. Sau đó, chúng tôi sử dụng ký hiệu dấu chấm để truy cập publicKey
nhằm lấy khóa có thể xuất bản.
Bao gồm Stripe.js trong các mẫu / home.html như sau:
<!-- templates/home.html -->
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django + Stripe Checkout</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
<script src="https://js.stripe.com/v3/"></script> <!-- new -->
<script src="{% static 'main.js' %}"></script>
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
</head>
<body>
<section class="section">
<div class="container">
<button class="button is-primary" id="submitBtn">Purchase!</button>
</div>
</section>
</body>
</html>
Bây giờ, sau khi tải trang, một lệnh gọi sẽ được thực hiện tới /config/
, lệnh này sẽ phản hồi bằng khóa có thể xuất bản Stripe. Sau đó, chúng tôi sẽ sử dụng khóa này để tạo một phiên bản mới của Stripe.js.
Lưu lượng:
Nhận khóa dành cho nhà xuất bản
Tạo phiên thanh toán
Chuyển hướng người dùng một cách thích hợp
Xác nhận thanh toán bằng Stripe Webhooks
Tiếp tục, chúng ta cần đính kèm một trình xử lý sự kiện vào sự kiện nhấp chuột của nút, điều này sẽ gửi một yêu cầu XHR khác đến máy chủ để tạo ID phiên Checkout mới.
Đầu tiên, hãy thêm chế độ xem mới:
# payments/views.py
@csrf_exempt
def create_checkout_session(request):
if request.method == 'GET':
domain_url = 'http://localhost:8000/'
stripe.api_key = settings.STRIPE_SECRET_KEY
try:
# Create new Checkout Session for the order
# Other optional params include:
# [billing_address_collection] - to display billing address details on the page
# [customer] - if you have an existing Stripe Customer ID
# [payment_intent_data] - capture the payment later
# [customer_email] - prefill the email input in the form
# For full details see https://stripe.com/docs/api/checkout/sessions/create
# ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
checkout_session = stripe.checkout.Session.create(
success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
cancel_url=domain_url + 'cancelled/',
payment_method_types=['card'],
mode='payment',
line_items=[
{
'name': 'T-shirt',
'quantity': 1,
'currency': 'usd',
'amount': '2000',
}
]
)
return JsonResponse({'sessionId': checkout_session['id']})
except Exception as e:
return JsonResponse({'error': str(e)})
Ở đây, nếu phương thức yêu cầu là GET
, chúng tôi đã xác định a domain_url
, gán khóa bí mật Stripe cho stripe.api_key
(vì vậy nó sẽ được gửi tự động khi chúng tôi thực hiện yêu cầu tạo Phiên kiểm tra mới), tạo Phiên kiểm tra và gửi lại ID trong phản ứng. Hãy lưu ý success_url
và cancel_url
. Người dùng sẽ được chuyển hướng trở lại các URL đó trong trường hợp thanh toán thành công hoặc hủy tương ứng. Chúng tôi sẽ sớm thiết lập các chế độ xem đó.
Đừng quên nhập:
import stripe
Thêm URL:
# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('config/', views.stripe_config),
path('create-checkout-session/', views.create_checkout_session), # new
]
Thêm trình xử lý sự kiện và yêu cầu XHR tiếp theo vào static / main.js :
// static/main.js
console.log("Sanity check!");
// Get Stripe publishable key
fetch("/config/")
.then((result) => { return result.json(); })
.then((data) => {
// Initialize Stripe.js
const stripe = Stripe(data.publicKey);
// new
// Event handler
document.querySelector("#submitBtn").addEventListener("click", () => {
// Get Checkout Session ID
fetch("/create-checkout-session/")
.then((result) => { return result.json(); })
.then((data) => {
console.log(data);
// Redirect to Stripe Checkout
return stripe.redirectToCheckout({sessionId: data.sessionId})
})
.then((res) => {
console.log(res);
});
});
});
Ở đây, sau khi giải quyết result.json()
lời hứa, chúng tôi đã gọi redirectToCheckout với ID phiên Checkout từ lời hứa đã giải quyết.
Navigate to http://localhost:8000/. On button click you should be redirected to an instance of Stripe Checkout (a Stripe-hosted page to securely collect payment information) with the T-shirt product information:
We can test the form by using one of the several test card numbers that Stripe provides. Let's use 4242 4242 4242 4242
. Make sure the expiration date is in the future. Add any 3 numbers for the CVC and any 5 numbers for the postal code. Enter any email address and name. If all goes well, the payment should be processed, but the redirect will fail since we have not set up the /success/
URL yet.
Flow:
Get Publishable Key
Tạo phiên thanh toán
Chuyển hướng người dùng một cách thích hợp
Xác nhận thanh toán bằng Stripe Webhooks
Cuối cùng, hãy sắp xếp các mẫu, chế độ xem và URL để xử lý chuyển hướng thành công và hủy.
Mẫu thành công:
<!-- templates/success.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django + Stripe Checkout</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
</head>
<body>
<section class="section">
<div class="container">
<p>Your payment succeeded.</p>
</div>
</section>
</body>
</html>
Mẫu đã hủy:
<!-- templates/cancelled.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django + Stripe Checkout</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
</head>
<body>
<section class="section">
<div class="container">
<p>Your payment was cancelled.</p>
</div>
</section>
</body>
</html>
Lượt xem:
# payments/views.py
class SuccessView(TemplateView):
template_name = 'success.html'
class CancelledView(TemplateView):
template_name = 'cancelled.html'
URL:
# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('config/', views.stripe_config),
path('create-checkout-session/', views.create_checkout_session),
path('success/', views.SuccessView.as_view()), # new
path('cancelled/', views.CancelledView.as_view()), # new
]
Ok, làm mới trang web tại http: // localhost: 8000 / . Nhấp vào nút thanh toán và sử dụng 4242 4242 4242 4242
lại số thẻ tín dụng cùng với phần còn lại của thông tin giả. Gửi khoản thanh toán. Bạn sẽ được chuyển hướng trở lại http: // localhost: 8000 / success / .
Để xác nhận một khoản phí đã thực sự được thực hiện, hãy quay lại trang tổng quan Stripe trong "Thanh toán":
Để xem xét, chúng tôi đã sử dụng khóa bí mật để tạo ID phiên Checkout duy nhất trên máy chủ. Sau đó, ID này được sử dụng để tạo một phiên bản Checkout, mà người dùng cuối được chuyển hướng đến sau khi nhấp vào nút thanh toán. Sau khi khoản phí xảy ra, họ sẽ được chuyển hướng trở lại trang thành công.
Lưu lượng:
Nhận khóa dành cho nhà xuất bản
Tạo phiên thanh toán
Chuyển hướng người dùng một cách thích hợp
Xác nhận thanh toán bằng Stripe Webhooks
Ứng dụng của chúng tôi hoạt động tốt tại thời điểm này, nhưng chúng tôi vẫn không thể xác nhận thanh toán theo chương trình và có thể chạy một số mã nếu thanh toán thành công. Chúng tôi đã chuyển hướng người dùng đến trang thành công sau khi họ kiểm tra, nhưng chúng tôi không thể chỉ dựa vào trang đó vì xác nhận thanh toán xảy ra không đồng bộ.
There are two types of events in Stripe and programming in general: Synchronous events, which have an immediate effect and results (e.g., creating a customer), and asynchronous events, which don't have an immediate result (e.g., confirming payments). Because payment confirmation is done asynchronously, the user might get redirected to the success page before their payment is confirmed and before we receive their funds.
Một trong những cách dễ nhất để nhận thông báo khi thanh toán được thực hiện là sử dụng gọi lại hoặc cái gọi là Stripe webhook . Chúng tôi sẽ cần tạo một điểm cuối đơn giản trong ứng dụng của mình, Stripe sẽ gọi bất cứ khi nào một sự kiện xảy ra (tức là khi người dùng mua một chiếc áo phông). Bằng cách sử dụng webhook, chúng tôi có thể hoàn toàn chắc chắn rằng khoản thanh toán đã được thực hiện thành công.
Để sử dụng webhook, chúng ta cần:
Phần này được viết bởi Nik Tomazic .
Tạo chế độ xem mới được gọi là chế độ xem stripe_webhook
sẽ in thông báo mỗi khi thanh toán được thực hiện thành công:
# payments/views.py
@csrf_exempt
def stripe_webhook(request):
stripe.api_key = settings.STRIPE_SECRET_KEY
endpoint_secret = settings.STRIPE_ENDPOINT_SECRET
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as e:
# Invalid signature
return HttpResponse(status=400)
# Handle the checkout.session.completed event
if event['type'] == 'checkout.session.completed':
print("Payment was successful.")
# TODO: run some custom code here
return HttpResponse(status=200)
stripe_webhook
bây giờ đóng vai trò là điểm cuối webhook của chúng tôi. Ở đây, chúng tôi chỉ tìm kiếm các checkout.session.completed
sự kiện được gọi bất cứ khi nào thanh toán thành công, nhưng bạn có thể sử dụng cùng một mẫu cho các sự kiện Stripe khác .
Đảm bảo thêm HttpResponse
nhập vào đầu:
from django.http.response import JsonResponse, HttpResponse
Điều duy nhất cần làm để làm cho điểm cuối có thể truy cập được là đăng ký nó trong urls.py :
# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('config/', views.stripe_config),
path('create-checkout-session/', views.create_checkout_session),
path('success/', views.SuccessView.as_view()),
path('cancelled/', views.CancelledView.as_view()),
path('webhook/', views.stripe_webhook), # new
]
Chúng tôi sẽ sử dụng Stripe CLI để kiểm tra webhook.
Sau khi tải xuống và cài đặt , hãy chạy lệnh sau trong cửa sổ đầu cuối mới để đăng nhập vào tài khoản Stripe của bạn:
$ stripe login
Lệnh này sẽ tạo mã ghép nối:
Your pairing code is: peach-loves-classy-cozy
This pairing code verifies your authentication with Stripe.
Press Enter to open the browser (^C to quit)
Bằng cách nhấn Enter, CLI sẽ mở trình duyệt web mặc định của bạn và yêu cầu quyền truy cập thông tin tài khoản của bạn. Hãy tiếp tục và cho phép truy cập. Quay lại thiết bị đầu cuối của bạn, bạn sẽ thấy một cái gì đó tương tự như:
> Done! The Stripe CLI is configured for Django Test with account id acct_<ACCOUNT_ID>
Please note: this key will expire after 90 days, at which point you'll need to re-authenticate.
Tiếp theo, chúng ta có thể bắt đầu lắng nghe các sự kiện Stripe và chuyển tiếp chúng đến điểm cuối của chúng ta bằng lệnh sau:
$ stripe listen --forward-to localhost:8000/webhook/
Điều này cũng sẽ tạo ra một bí mật ký webhook:
> Ready! Your webhook signing secret is whsec_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (^C to quit)
Để khởi tạo điểm cuối, hãy thêm bí mật vào tệp settings.py :
# djangostripe/settings.py
STRIPE_ENDPOINT_SECRET = '<your webhook signing secret here>'
Stripe bây giờ sẽ chuyển tiếp các sự kiện đến điểm cuối của chúng tôi. Để kiểm tra, hãy chạy một khoản thanh toán thử nghiệm khác thông qua với 4242 4242 4242 4242
. Trong thiết bị đầu cuối của bạn, bạn sẽ thấy Payment was successful.
thông báo.
Sau khi hoàn tất, hãy dừng stripe listen --forward-to localhost:8000/webhook/
quá trình.
Nếu bạn muốn xác định người dùng thực hiện mua hàng, bạn có thể sử dụng client_reference_id để đính kèm một số loại nhận dạng người dùng vào phiên Stripe.
Ví dụ:
# payments/views.py @csrf_exempt def create_checkout_session(request): if request.method == 'GET': domain_url = 'http://localhost:8000/' stripe.api_key = settings.STRIPE_SECRET_KEY try: checkout_session = stripe.checkout.Session.create( # new client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled/', payment_method_types=['card'], mode='payment', line_items=[ { 'name': 'T-shirt', 'quantity': 1, 'currency': 'usd', 'amount': '2000', } ] ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)})
Cuối cùng, sau khi triển khai ứng dụng của mình, bạn có thể đăng ký điểm cuối trong trang tổng quan Stripe, trong Nhà phát triển> Webhooks . Điều này sẽ tạo ra một bí mật ký webhook để sử dụng trong ứng dụng sản xuất của bạn.
Ví dụ:
Lưu lượng:
Nhận khóa dành cho nhà xuất bản
Tạo phiên thanh toán
Chuyển hướng người dùng một cách thích hợp
Xác nhận thanh toán bằng Stripe Webhooks
Trên một trang web trực tiếp, bắt buộc phải có HTTPS để kết nối của bạn được an toàn. Ngoài ra, mặc dù chúng tôi đã mã hóa cứng các khóa API và bí mật ký webhook để đơn giản hóa, nhưng chúng thực sự nên được lưu trữ trong các biến môi trường. Có thể bạn cũng sẽ muốn lưu trữ domain_url
dưới dạng một biến môi trường.
Lấy mã từ kho thanh toán django-sọc trên GitHub.
Nguồn: https://testdriven.io
1660393740
Trong hướng dẫn này, tôi sẽ trình bày cách định cấu hình trang web Django mới từ đầu để chấp nhận thanh toán một lần bằng Stripe .
Hiện có ba cách để chấp nhận thanh toán một lần với Stripe:
Bạn nên sử dụng cái nào?
Mặc dù bạn vẫn có thể sử dụng API tính phí, nhưng nếu bạn mới sử dụng Stripe, đừng sử dụng nó vì nó không hỗ trợ các quy định ngân hàng mới nhất (như SCA ). Bạn sẽ thấy tỷ lệ từ chối cao. Để biết thêm thông tin, hãy xem lại trang API ý định thanh toán so với khoản phí từ tài liệu chính thức của Stripe.
Bạn vẫn sử dụng API tính phí? Nếu hầu hết khách hàng của bạn sống ở Hoa Kỳ hoặc Canada, bạn chưa cần phải di cư. Xem lại hướng dẫn hướng dẫn di chuyển Checkout để biết thêm thông tin.
Tạo một thư mục dự án mới cùng với một dự án Django mới có tên djangostripe
:
$ mkdir django-stripe-checkout && cd django-stripe-checkout
$ python3.10 -m venv env
$ source env/bin/activate
(env)$ pip install django==3.2.9
(env)$ django-admin startproject djangostripe .
Hãy trao đổi virtualenv và Pip cho thơ hoặc Pipenv . Để biết thêm, hãy xem lại Môi trường Python hiện đại .
Tiếp theo, tạo một ứng dụng mới có tên payments
:
(env)$ python manage.py startapp payments
Bây giờ, hãy thêm ứng dụng mới vào INSTALLED_APPS
cấu hình trong settings.py :
# djangostripe/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Local
'payments.apps.PaymentsConfig', # new
]
Cập nhật tệp urls.py cấp dự án với payments
ứng dụng:
# djangostripe/urls.py
from django.contrib import admin
from django.urls import path, include # new
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('payments.urls')), # new
]
Cũng tạo tệp urls.py trong ứng dụng mới:
(env)$ touch payments/urls.py
Sau đó điền nó như sau:
# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
]
Bây giờ hãy thêm tệp views.py :
# payments/views.py
from django.views.generic.base import TemplateView
class HomePageView(TemplateView):
template_name = 'home.html'
Và tạo một thư mục và tệp "mẫu" dành riêng cho trang chủ của chúng tôi.
(env)$ mkdir templates
(env)$ touch templates/home.html
Sau đó, thêm HTML sau:
<!-- templates/home.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django + Stripe Checkout</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
</head>
<body>
<section class="section">
<div class="container">
<button class="button is-primary" id="submitBtn">Purchase!</button>
</div>
</section>
</body>
</html>
Đảm bảo cập nhật tệp settings.py để Django biết tìm thư mục "mẫu":
# djangostripe/settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'], # new
...
Cuối cùng chạy migrate
để đồng bộ cơ sở dữ liệu và runserver
khởi động máy chủ web cục bộ của Django.
(env)$ python manage.py migrate
(env)$ python manage.py runserver
That's it! Check out http://localhost:8000/ and you'll see the homepage:
Time for Stripe. Start by installing it:
(env)$ pip install stripe==2.63.0
Next, register for a Stripe account (if you haven't already done so) and navigate to the dashboard. Click on "Developers":
Then in the left sidebar click on "API keys":
Each Stripe account has four API keys: two for testing and two for production. Each pair has a "secret key" and a "publishable key". Do not reveal the secret key to anyone; the publishable key will be embedded in the JavaScript on the page that anyone can see.
Hiện tại, nút chuyển đổi cho "Xem dữ liệu kiểm tra" ở phía trên bên phải cho biết rằng chúng tôi đang sử dụng các khóa kiểm tra ngay bây giờ. Đó là những gì chúng tôi muốn.
Ở cuối tệp settings.py của bạn , thêm hai dòng sau bao gồm bí mật kiểm tra của riêng bạn và kiểm tra khóa có thể xuất bản. Đảm bảo bao gồm các ''
ký tự xung quanh các phím thực tế.
# djangostripe/settings.py
STRIPE_PUBLISHABLE_KEY = '<your test publishable key here>'
STRIPE_SECRET_KEY = '<your test secret key here>'
Cuối cùng, bạn sẽ cần chỉ định "Tên tài khoản" trong "Cài đặt tài khoản" của mình tại https://dashboard.stripe.com/settings/account :
Tiếp theo, chúng ta cần tạo ra một sản phẩm để bán.
Nhấp vào "Sản phẩm" và sau đó "Thêm sản phẩm":
Thêm tên sản phẩm, nhập giá và chọn "Một lần":
Nhấp vào "Lưu sản phẩm".
Sau khi người dùng nhấp vào nút mua hàng, chúng ta cần thực hiện các thao tác sau:
Get Publishable Key
Create Checkout Session
Redirect the User Appropriately
Confirm Payment with Stripe Webhooks
Let's start by creating a new static file to hold all of our JavaScript:
(env)$ mkdir static
(env)$ touch static/main.js
Add a quick sanity check to the new main.js file:
// static/main.js
console.log("Sanity check!");
Sau đó, cập nhật tệp settings.py để Django biết nơi tìm tệp tĩnh:
# djangostripe/settings.py
STATIC_URL = '/static/'
# for django >= 3.1
STATICFILES_DIRS = [BASE_DIR / 'static'] # new
# for django < 3.1
# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] # new
Thêm thẻ mẫu tĩnh cùng với thẻ tập lệnh mới bên trong mẫu HTML:
<!-- templates/home.html -->
{% load static %} <!-- new -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django + Stripe Checkout</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
<script src="{% static 'main.js' %}"></script> <!-- new -->
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
</head>
<body>
<section class="section">
<div class="container">
<button class="button is-primary" id="submitBtn">Purchase!</button>
</div>
</section>
</body>
</html>
Chạy lại máy chủ phát triển. Điều hướng đến http: // localhost: 8000 / và mở bảng điều khiển JavaScript. Bạn sẽ thấy kiểm tra sự tỉnh táo:
Tiếp theo, thêm một chế độ xem mới vào Payment / views.py để xử lý yêu cầu XHR:
# payments/views.py
from django.conf import settings # new
from django.http.response import JsonResponse # new
from django.views.decorators.csrf import csrf_exempt # new
from django.views.generic.base import TemplateView
class HomePageView(TemplateView):
template_name = 'home.html'
# new
@csrf_exempt
def stripe_config(request):
if request.method == 'GET':
stripe_config = {'publicKey': settings.STRIPE_PUBLISHABLE_KEY}
return JsonResponse(stripe_config, safe=False)
Thêm cả một URL:
# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('config/', views.stripe_config), # new
]
Tiếp theo, sử dụng API Tìm nạp để thực hiện một yêu cầu XHR (XMLHttpRequest) tới /config/
điểm cuối mới trong static / main.js :
// static/main.js
console.log("Sanity check!");
// new
// Get Stripe publishable key
fetch("/config/")
.then((result) => { return result.json(); })
.then((data) => {
// Initialize Stripe.js
const stripe = Stripe(data.publicKey);
});
Phản hồi từ một fetch
yêu cầu là một luồng có thể đọc được . result.json()
trả về một lời hứa, mà chúng tôi đã giải quyết cho một đối tượng JavaScript - ví dụ data
:. Sau đó, chúng tôi sử dụng ký hiệu dấu chấm để truy cập publicKey
nhằm lấy khóa có thể xuất bản.
Bao gồm Stripe.js trong các mẫu / home.html như sau:
<!-- templates/home.html -->
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django + Stripe Checkout</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
<script src="https://js.stripe.com/v3/"></script> <!-- new -->
<script src="{% static 'main.js' %}"></script>
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
</head>
<body>
<section class="section">
<div class="container">
<button class="button is-primary" id="submitBtn">Purchase!</button>
</div>
</section>
</body>
</html>
Bây giờ, sau khi tải trang, một lệnh gọi sẽ được thực hiện tới /config/
, lệnh này sẽ phản hồi bằng khóa có thể xuất bản Stripe. Sau đó, chúng tôi sẽ sử dụng khóa này để tạo một phiên bản mới của Stripe.js.
Lưu lượng:
Nhận khóa dành cho nhà xuất bản
Tạo phiên thanh toán
Chuyển hướng người dùng một cách thích hợp
Xác nhận thanh toán bằng Stripe Webhooks
Tiếp tục, chúng ta cần đính kèm một trình xử lý sự kiện vào sự kiện nhấp chuột của nút, điều này sẽ gửi một yêu cầu XHR khác đến máy chủ để tạo ID phiên Checkout mới.
Đầu tiên, hãy thêm chế độ xem mới:
# payments/views.py
@csrf_exempt
def create_checkout_session(request):
if request.method == 'GET':
domain_url = 'http://localhost:8000/'
stripe.api_key = settings.STRIPE_SECRET_KEY
try:
# Create new Checkout Session for the order
# Other optional params include:
# [billing_address_collection] - to display billing address details on the page
# [customer] - if you have an existing Stripe Customer ID
# [payment_intent_data] - capture the payment later
# [customer_email] - prefill the email input in the form
# For full details see https://stripe.com/docs/api/checkout/sessions/create
# ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
checkout_session = stripe.checkout.Session.create(
success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
cancel_url=domain_url + 'cancelled/',
payment_method_types=['card'],
mode='payment',
line_items=[
{
'name': 'T-shirt',
'quantity': 1,
'currency': 'usd',
'amount': '2000',
}
]
)
return JsonResponse({'sessionId': checkout_session['id']})
except Exception as e:
return JsonResponse({'error': str(e)})
Ở đây, nếu phương thức yêu cầu là GET
, chúng tôi đã xác định a domain_url
, gán khóa bí mật Stripe cho stripe.api_key
(vì vậy nó sẽ được gửi tự động khi chúng tôi thực hiện yêu cầu tạo Phiên kiểm tra mới), tạo Phiên kiểm tra và gửi lại ID trong phản ứng. Hãy lưu ý success_url
và cancel_url
. Người dùng sẽ được chuyển hướng trở lại các URL đó trong trường hợp thanh toán thành công hoặc hủy tương ứng. Chúng tôi sẽ sớm thiết lập các chế độ xem đó.
Đừng quên nhập:
import stripe
Thêm URL:
# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('config/', views.stripe_config),
path('create-checkout-session/', views.create_checkout_session), # new
]
Thêm trình xử lý sự kiện và yêu cầu XHR tiếp theo vào static / main.js :
// static/main.js
console.log("Sanity check!");
// Get Stripe publishable key
fetch("/config/")
.then((result) => { return result.json(); })
.then((data) => {
// Initialize Stripe.js
const stripe = Stripe(data.publicKey);
// new
// Event handler
document.querySelector("#submitBtn").addEventListener("click", () => {
// Get Checkout Session ID
fetch("/create-checkout-session/")
.then((result) => { return result.json(); })
.then((data) => {
console.log(data);
// Redirect to Stripe Checkout
return stripe.redirectToCheckout({sessionId: data.sessionId})
})
.then((res) => {
console.log(res);
});
});
});
Ở đây, sau khi giải quyết result.json()
lời hứa, chúng tôi đã gọi redirectToCheckout với ID phiên Checkout từ lời hứa đã giải quyết.
Navigate to http://localhost:8000/. On button click you should be redirected to an instance of Stripe Checkout (a Stripe-hosted page to securely collect payment information) with the T-shirt product information:
We can test the form by using one of the several test card numbers that Stripe provides. Let's use 4242 4242 4242 4242
. Make sure the expiration date is in the future. Add any 3 numbers for the CVC and any 5 numbers for the postal code. Enter any email address and name. If all goes well, the payment should be processed, but the redirect will fail since we have not set up the /success/
URL yet.
Flow:
Get Publishable Key
Tạo phiên thanh toán
Chuyển hướng người dùng một cách thích hợp
Xác nhận thanh toán bằng Stripe Webhooks
Cuối cùng, hãy sắp xếp các mẫu, chế độ xem và URL để xử lý chuyển hướng thành công và hủy.
Mẫu thành công:
<!-- templates/success.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django + Stripe Checkout</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
</head>
<body>
<section class="section">
<div class="container">
<p>Your payment succeeded.</p>
</div>
</section>
</body>
</html>
Mẫu đã hủy:
<!-- templates/cancelled.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django + Stripe Checkout</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.15.4/js/all.js"></script>
</head>
<body>
<section class="section">
<div class="container">
<p>Your payment was cancelled.</p>
</div>
</section>
</body>
</html>
Lượt xem:
# payments/views.py
class SuccessView(TemplateView):
template_name = 'success.html'
class CancelledView(TemplateView):
template_name = 'cancelled.html'
URL:
# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('config/', views.stripe_config),
path('create-checkout-session/', views.create_checkout_session),
path('success/', views.SuccessView.as_view()), # new
path('cancelled/', views.CancelledView.as_view()), # new
]
Ok, làm mới trang web tại http: // localhost: 8000 / . Nhấp vào nút thanh toán và sử dụng 4242 4242 4242 4242
lại số thẻ tín dụng cùng với phần còn lại của thông tin giả. Gửi khoản thanh toán. Bạn sẽ được chuyển hướng trở lại http: // localhost: 8000 / success / .
Để xác nhận một khoản phí đã thực sự được thực hiện, hãy quay lại trang tổng quan Stripe trong "Thanh toán":
Để xem xét, chúng tôi đã sử dụng khóa bí mật để tạo ID phiên Checkout duy nhất trên máy chủ. Sau đó, ID này được sử dụng để tạo một phiên bản Checkout, mà người dùng cuối được chuyển hướng đến sau khi nhấp vào nút thanh toán. Sau khi khoản phí xảy ra, họ sẽ được chuyển hướng trở lại trang thành công.
Lưu lượng:
Nhận khóa dành cho nhà xuất bản
Tạo phiên thanh toán
Chuyển hướng người dùng một cách thích hợp
Xác nhận thanh toán bằng Stripe Webhooks
Ứng dụng của chúng tôi hoạt động tốt tại thời điểm này, nhưng chúng tôi vẫn không thể xác nhận thanh toán theo chương trình và có thể chạy một số mã nếu thanh toán thành công. Chúng tôi đã chuyển hướng người dùng đến trang thành công sau khi họ kiểm tra, nhưng chúng tôi không thể chỉ dựa vào trang đó vì xác nhận thanh toán xảy ra không đồng bộ.
There are two types of events in Stripe and programming in general: Synchronous events, which have an immediate effect and results (e.g., creating a customer), and asynchronous events, which don't have an immediate result (e.g., confirming payments). Because payment confirmation is done asynchronously, the user might get redirected to the success page before their payment is confirmed and before we receive their funds.
Một trong những cách dễ nhất để nhận thông báo khi thanh toán được thực hiện là sử dụng gọi lại hoặc cái gọi là Stripe webhook . Chúng tôi sẽ cần tạo một điểm cuối đơn giản trong ứng dụng của mình, Stripe sẽ gọi bất cứ khi nào một sự kiện xảy ra (tức là khi người dùng mua một chiếc áo phông). Bằng cách sử dụng webhook, chúng tôi có thể hoàn toàn chắc chắn rằng khoản thanh toán đã được thực hiện thành công.
Để sử dụng webhook, chúng ta cần:
Phần này được viết bởi Nik Tomazic .
Tạo chế độ xem mới được gọi là chế độ xem stripe_webhook
sẽ in thông báo mỗi khi thanh toán được thực hiện thành công:
# payments/views.py
@csrf_exempt
def stripe_webhook(request):
stripe.api_key = settings.STRIPE_SECRET_KEY
endpoint_secret = settings.STRIPE_ENDPOINT_SECRET
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as e:
# Invalid signature
return HttpResponse(status=400)
# Handle the checkout.session.completed event
if event['type'] == 'checkout.session.completed':
print("Payment was successful.")
# TODO: run some custom code here
return HttpResponse(status=200)
stripe_webhook
bây giờ đóng vai trò là điểm cuối webhook của chúng tôi. Ở đây, chúng tôi chỉ tìm kiếm các checkout.session.completed
sự kiện được gọi bất cứ khi nào thanh toán thành công, nhưng bạn có thể sử dụng cùng một mẫu cho các sự kiện Stripe khác .
Đảm bảo thêm HttpResponse
nhập vào đầu:
from django.http.response import JsonResponse, HttpResponse
Điều duy nhất cần làm để làm cho điểm cuối có thể truy cập được là đăng ký nó trong urls.py :
# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('config/', views.stripe_config),
path('create-checkout-session/', views.create_checkout_session),
path('success/', views.SuccessView.as_view()),
path('cancelled/', views.CancelledView.as_view()),
path('webhook/', views.stripe_webhook), # new
]
Chúng tôi sẽ sử dụng Stripe CLI để kiểm tra webhook.
Sau khi tải xuống và cài đặt , hãy chạy lệnh sau trong cửa sổ đầu cuối mới để đăng nhập vào tài khoản Stripe của bạn:
$ stripe login
Lệnh này sẽ tạo mã ghép nối:
Your pairing code is: peach-loves-classy-cozy
This pairing code verifies your authentication with Stripe.
Press Enter to open the browser (^C to quit)
Bằng cách nhấn Enter, CLI sẽ mở trình duyệt web mặc định của bạn và yêu cầu quyền truy cập thông tin tài khoản của bạn. Hãy tiếp tục và cho phép truy cập. Quay lại thiết bị đầu cuối của bạn, bạn sẽ thấy một cái gì đó tương tự như:
> Done! The Stripe CLI is configured for Django Test with account id acct_<ACCOUNT_ID>
Please note: this key will expire after 90 days, at which point you'll need to re-authenticate.
Tiếp theo, chúng ta có thể bắt đầu lắng nghe các sự kiện Stripe và chuyển tiếp chúng đến điểm cuối của chúng ta bằng lệnh sau:
$ stripe listen --forward-to localhost:8000/webhook/
Điều này cũng sẽ tạo ra một bí mật ký webhook:
> Ready! Your webhook signing secret is whsec_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (^C to quit)
Để khởi tạo điểm cuối, hãy thêm bí mật vào tệp settings.py :
# djangostripe/settings.py
STRIPE_ENDPOINT_SECRET = '<your webhook signing secret here>'
Stripe bây giờ sẽ chuyển tiếp các sự kiện đến điểm cuối của chúng tôi. Để kiểm tra, hãy chạy một khoản thanh toán thử nghiệm khác thông qua với 4242 4242 4242 4242
. Trong thiết bị đầu cuối của bạn, bạn sẽ thấy Payment was successful.
thông báo.
Sau khi hoàn tất, hãy dừng stripe listen --forward-to localhost:8000/webhook/
quá trình.
Nếu bạn muốn xác định người dùng thực hiện mua hàng, bạn có thể sử dụng client_reference_id để đính kèm một số loại nhận dạng người dùng vào phiên Stripe.
Ví dụ:
# payments/views.py @csrf_exempt def create_checkout_session(request): if request.method == 'GET': domain_url = 'http://localhost:8000/' stripe.api_key = settings.STRIPE_SECRET_KEY try: checkout_session = stripe.checkout.Session.create( # new client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled/', payment_method_types=['card'], mode='payment', line_items=[ { 'name': 'T-shirt', 'quantity': 1, 'currency': 'usd', 'amount': '2000', } ] ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)})
Cuối cùng, sau khi triển khai ứng dụng của mình, bạn có thể đăng ký điểm cuối trong trang tổng quan Stripe, trong Nhà phát triển> Webhooks . Điều này sẽ tạo ra một bí mật ký webhook để sử dụng trong ứng dụng sản xuất của bạn.
Ví dụ:
Lưu lượng:
Nhận khóa dành cho nhà xuất bản
Tạo phiên thanh toán
Chuyển hướng người dùng một cách thích hợp
Xác nhận thanh toán bằng Stripe Webhooks
Trên một trang web trực tiếp, bắt buộc phải có HTTPS để kết nối của bạn được an toàn. Ngoài ra, mặc dù chúng tôi đã mã hóa cứng các khóa API và bí mật ký webhook để đơn giản hóa, nhưng chúng thực sự nên được lưu trữ trong các biến môi trường. Có thể bạn cũng sẽ muốn lưu trữ domain_url
dưới dạng một biến môi trường.
Lấy mã từ kho thanh toán django-sọc trên GitHub.
Nguồn: https://testdriven.io
1620177818
Welcome to my blog , hey everyone in this article you learn how to customize the Django app and view in the article you will know how to register and unregister models from the admin view how to add filtering how to add a custom input field, and a button that triggers an action on all objects and even how to change the look of your app and page using the Django suit package let’s get started.
#django #create super user django #customize django admin dashboard #django admin #django admin custom field display #django admin customization #django admin full customization #django admin interface #django admin register all models #django customization
1616572320
Welcome to what I hope will be a very detailed and useful tutorial on building a Django web app from scratch to production. Having developed dozens of Django projects prior, I have acquired certain tips and tricks to increase efficiency in each Django project that I will present in the form of a tutorial. This tutorial is a step-by-step process of how I go about building robust Django applications. Enjoy!
You can check out the deployment here: Live Link
#django #how-to-django #django-tips #app-development #web-app-development #web-app-development-tools #web-apps #programming #web-monetization
1616147643
Django is a highly powerful framework for building small and large scale web applications. Being a Python-based framework, Django for web development is the preferred choice of companies all over the world.
If you are looking for proof of Django’s popularity, here it is - Django framework for web development is used by YouTube, Dropbox, Instagram, Pinterest, Google, Reddit, and many more. Being an open-source and maintainable web application development framework, companies adore it for building dynamic and sophisticated web applications.
Now you must be asking yourself “is Django good for web development?” The framework has a lot of benefits over other frameworks like Ruby on Rails, Flutter, Xamarin, etc. When you want a robust, scalable and stable application with a large codebase, using Django for web development is the right choice.
Read more: Pros and Cons of Django Web Framework for App Development
Django is admired by web developers all over the world. It is an easy-to-use battery including a framework that doesn’t eat up a lot of time in configuration and setting up the development environment.
The following benefits are your answer to “why use Django for web development”:-
Simplicity
Django framework for web development is excellent because of its simplicity and the ease of use. It allows developers to do more than one iteration and make modifications without running the entire code from scratch.
Apart from that, it makes development simpler with its Don’t Repeat Yourself Philosophy, allowing developers to reuse the codebase for creating different components.
Ecosystem
Django has a rich and diverse development ecosystem. It permits a lot of third-party apps and integrations. While setting up the ide for Django web development, you can use the third-party apps and integrations to add components or blocks in the web application.
From authorization to sending emails, there are apps for some of the most common features. It reduces the time taken to write code for these programs and leads to the timely delivery of products.
Documentation
Django for web development comes with excellent documentation to develop real-world applications. While other frameworks have alphabetical lists and modules, Django provides quick references to developers for building applications from different stages in the process.
The documentation is updated regularly as Python programmers add new exceptions, rules, and features to the open-source framework. While it is hard to keep it fine-tuned, it is one of the best documentation of a framework.
Wide community
If you are still asking what are the advantages of using Django for web development, then look at its wide community of developers. Django developers are increasing every day as the framework becomes a popular choice amongst enterprises to fulfill their web application needs.
The community is ready to assist on all Python Django web development projects. There are regular meets, tutorials, and material that can help anyone working with Django. The community regularly answers queries, and you can find the solution to almost any Django problem.
Libraries
Django allows developers to use massive amounts of libraries for building feature-rich and functional applications. Django REST framework is an excellent library for building Application Programming Interfaces (APIs). Django CMS, Django-allauth, and many other libraries are used for adding functionalities to web applications.
Since the framework uses Python, using libraries becomes an easy task. Python has a lot of libraries with Django integration that enables building quality applications.
Also Read: A Guide to Django Web Development for your Business
Whether you are looking for an ERP application or a B2C web app, Django framework for web development is the perfect solution. It allows you to develop scalable applications capable of handling heavy traffic load in the future.
You can hire Python developers and Django experts for Python development services from BoTree Technologies who can fulfill your web development needs.
Source: https://www.apsense.com/article/why-should-you-use-django-for-web-development.html
#python development services #django framework #django rest framework #django for web development #django for web development #django
1620185280
Welcome to my blog, hey everyone in this article we are going to be working with queries in Django so for any web app that you build your going to want to write a query so you can retrieve information from your database so in this article I’ll be showing you all the different ways that you can write queries and it should cover about 90% of the cases that you’ll have when you’re writing your code the other 10% depend on your specific use case you may have to get more complicated but for the most part what I cover in this article should be able to help you so let’s start with the model that I have I’ve already created it.
**Read More : **How to make Chatbot in Python.
Read More : Django Admin Full Customization step by step
let’s just get into this diagram that I made so in here:
Describe each parameter in Django querset
we’re making a simple query for the myModel table so we want to pull out all the information in the database so we have this variable which is gonna hold a return value and we have our myModel models so this is simply the myModel model name so whatever you named your model just make sure you specify that and we’re gonna access the objects attribute once we get that object’s attribute we can simply use the all method and this will return all the information in the database so we’re gonna start with all and then we will go into getting single items filtering that data and go to our command prompt.
Here and we’ll actually start making our queries from here to do this let’s just go ahead and run** Python manage.py shell** and I am in my project file so make sure you’re in there when you start and what this does is it gives us an interactive shell to actually start working with our data so this is a lot like the Python shell but because we did manage.py it allows us to do things a Django way and actually query our database now open up the command prompt and let’s go ahead and start making our first queries.
#django #django model queries #django orm #django queries #django query #model django query #model query #query with django