使用 Python Django 框架和 Htmx 构建单一产品商店
这是使用 Django、htmx 和 Stripe 创建单一产品电子商务网站的两部分系列中的第一部分。在这一部分中,我们将启动 Django 项目并将其与 htmx 集成。
在第二部分中,我们将使用 Stripe 处理订单。
我们出发吧!
为什么选择 Django、htmx 和 Stripe?
我们将使用 Django、htmx 和 Stripe 来创建我们的网站,因为:
- Django 是一个 Python Web 框架,具有出色的 ORM、模板和路由系统。它有一些开箱即用的功能(如身份验证)和多个在线可用的开源包。我们将使用 Django 来构建网站。
- htmx 是一个 JavaScript 库,只需使用 html 属性即可为您的网站带来现代感 - 您实际上不必编写任何 JavaScript(当然您可以)。我们将使用 htmx 为我们的页面提供一些交互性。
- Stripe 是一个具有出色 API 的支付平台 — 它可以处理付款和信用卡信息。它还与 Google 和 Apple Pay 完美集成。我们将使用 Stripe 来促进产品付款。
最终产品的工作原理如下:
- 用户访问我们的网站,可以看到有关我们产品的一些信息,包括其价格和描述。
- 一旦用户点击“购买”按钮,他们就会被重定向到 Stripe 的结帐会话。
- 如果付款成功,他们会再次重定向到我们的网站。我们保存他们的订单信息,并向客户和所有员工用户发送确认电子邮件,通知他们最近的购买。
现在让我们配置 Django 项目,创建初始视图,并使用 htmx 构建购买表单。
配置您的 Django Python 项目
要设置我们的项目,我们需要创建一个虚拟环境,激活它并安装所需的软件包。然后我们可以创建 Django 项目和 Django 应用程序。
创建虚拟环境
让我们从创建一个虚拟环境开始,这样我们就可以隔离我们的依赖项:
python -m venv .venv
以下是我们在 Linux/Mac 上激活它的方法:
source .venv/bin/activate
在 Windows 上:
.venv\Scripts\activate
安装所需的软件包
在我们激活的虚拟环境中,我们需要一些软件包来完成这项工作:
pip install django stripe django-htmx python-dotenv
在这里,我们安装了:
- 姜戈
- Stripe 可与 stripe API 配合使用。
- django-htmx,它提供了一些与 htmx 一起使用的辅助功能。
- python-dotenv 从 .env 文件加载环境变量。
创建 Django 项目
在与我们的虚拟环境相同的目录中,我们创建一个名为 ecommerce_site 的 Django 项目:
django-admin startproject ecommerce_site .
在 Django 中,由一个或多个“应用程序”组织代码是一种很好的做法。每个应用程序都是一个执行特定操作的包。一个项目可以有多个应用程序,但对于这个简单的商店,我们可以只拥有一个包含大部分代码的应用程序 - 我们的电子商务平台的视图、表单和模型。让我们创建它并将其称为电子商务:
python manage.py startapp ecommerce
并将此应用程序添加到 ecommerce_site/settings.py 中的 INSTALLED_APPS 中:
# ecommerce_site/settings.py INSTALLED_APPS = [ # ... the default django apps "ecommerce", # ⬅️ new ]
如果您在设置时遇到问题,请查看最终产品。在此阶段,您的文件结构应如下所示:
ecommerce_site/ ├── .venv/ # ⬅️ the virtual environment ├── ecommerce_site/ # ⬅️ the django project configuration │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── ecommerce/ # ⬅️ our app setup │ ├── templates/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── tests.py │ └── views.py └── manage.py
创建模板
现在我们已经配置了项目,我们需要创建一些基本布局。在 templates 目录中,添加一个 base.html 文件 - 所有其他模板都将从该模板继承。添加用于用户交互的 htmx、用于基本样式的 mvp.css 以及 Django 生成的消息到模板:
<!-- ecommerce/templates/base.html --> <!DOCTYPE html> <html lang="en"> <head> <title>One-Product E-commerce Site</title> <!-- include htmx ⬇️ --> <script src="https://unpkg.com/htmx.org@1.9.11" integrity="sha384-0gxUXCCR8yv9FM2b+U3FDbsKthCI66oH5IA9fHppQq9DDMHuMauqq1ZHBpJxQ0J0" crossorigin="anonymous" ></script> <!-- include mvp.css ⬇️ --> <link rel="stylesheet" href="https://unpkg.com/mvp.css" /> </head> <body hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}' hx-boost="true"> <header> <h1>One-Product E-commerce Site</h1> </header> <main> <section> {% if messages %} {% for message in messages %} <p><mark>{{ message }}</mark></p> {% endfor %} {% endif %} </section> {% block content %} {% endblock %} </main> </body> </html>
在同一个 templates 目录中为我们的主页视图创建一个 home.html 模板。它应该扩展 base.html 并仅填充其内容部分。
<!-- ecommerce/templates/home.html --> {% extends "base.html" %} {% block content %} <section>{% include "product.html" %}</section> {% endblock %}
在此模板中,我们包含了product.html 模板。 Product.html 将呈现有关我们产品的一些详细信息和占位符图像。让我们在同一个 templates 目录中创建它:
<!-- ecommerce/templates/product.html --> <form> <img src="https://picsum.photos/id/30/400/250" alt="mug" /> <h3>mug<sup>on sale!</sup></h3> <p>mugs are great - you can drink coffee on them!</p> <p><strong>5€</strong></p> <button type="submit" id="submit-btn">Buy</button> </form>
创建主视图
在 ecommerce/views.py 中,我们将创建将渲染主页模板的视图:
# ecommerce/views.py from django.shortcuts import render def home(request): return render(request, 'home.html')
并将其添加到 ecommerce_site/urls.py 中的 urlpatterns 中:
# ecommerce_site/urls.py from django.contrib import admin from django.urls import path from ecommerce import views # ⬅️ new urlpatterns = [ path("admin/", admin.site.urls), path("", views.home, name="home"), # ⬅️ new ]
现在我们可以使用以下命令运行服务器:
python manage.py runserver
如果您在浏览器中跳转到 http://127.0.0.1:8000,您应该会看到如下内容:
It might feel like overkill to add a dedicated product.html template instead of just the product details in the home.html template, but product.html will be useful for the htmx integration.
Add the Form and Use Htmx
Great! We now have a view that looks good. However, it doesn’t do much yet. We'll add a form and set up the logic to process our product purchase. Here’s what we want to do:
- Allow the user to select how many products (mugs) they want to buy.
- When the user clicks “Buy”, make a POST request to a different view called purchase in the backend using hx-post.
- In that view, validate the form and wait for 2 seconds to simulate the Stripe integration (we'll cover this in the second part of this guide).
- Replace the form content with the purchase view response.
- While the order is processing, show a loading message and disable the “Buy” button, so that the user doesn’t accidentally make multiple orders.
Let's go step by step.
1: Add a Quantity Order Form
Let’s first create and add a simple order form to our view allowing a user to select the number of mugs they want. In ecommerce/forms.py, add the following code:
# ecommerce/forms.py from django import forms class OrderForm(forms.Form): quantity = forms.IntegerField(min_value=1, max_value=10, initial=1)
In ecommerce/views.py, we can initialize the form in the home view:
# ecommerce/views.py from ecommerce.forms import OrderForm # ⬅️ new def home(request): form = OrderForm() # ⬅️ new - initialize the form return render(request, "home.html", {"form": form}) # ⬅️ new - pass the form to the template
And render it in the template:
<!-- ecommerce/templates/product.html --> <form method="post"> <!-- Same product details as before, hidden for simplicity --> <!-- render the form fields ⬇️ --> {{ form }} <!-- the same submit button as before ⬇️ --> <button type="submit" id="submit-btn">Buy</button> </form>
2: Make a POST Request To a Different View
When the user clicks "Buy", we want to process the corresponding POST request in a dedicated view to separate the different logic of our application. We will use htmx to make this request. In the same ecommerce/templates/product.html template, let's extend the form attributes:
<!-- ecommerce/templates/product.html --> <!-- add the hx-post html attribute ⬇️ --> <form method="post" hx-post="{% url 'purchase' %}"> <!-- Same product details as before, hidden for simplicity --> {{ form }} <button type="submit" id="submit-btn">Buy</button> </form>
With this attribute, htmx will make a POST request to the purchase endpoint and stop the page from reloading completely. Now we just need to add the endpoint.
3: Create the Purchase View
The purchase view can be relatively simple for now:
# ecommerce/views.py import time # ⬅️ new # new purchase POST request view ⬇️ @require_POST def purchase(request): form = OrderForm(request.POST) if form.is_valid(): quantity = form.cleaned_data["quantity"] # TODO - add stripe integration to process the order # for now, just wait for 2 seconds to simulate the processing time.sleep(2) return render(request, "product.html", {"form": form})
In this view, we validate the form, extract the quantity from the cleaned data, and simulate Stripe order processing. In the end, we return the same template (product.html). We also need to add the view to the urlpatterns:
# ecommerce_site/urls.py # ... same imports as before urlpatterns = [ path("admin/", admin.site.urls), path("", views.home, name="home"), path("purchase", views.purchase, name="purchase"), # ⬅️ new ]
We now need to tell htmx what to do with this response.
4: Replace the Form Content With the Purchase View Response
Htmx has a hx-swap attribute which replaces targeted content on the current page with a request's response.
In our case, since the purchase view returns the same template, we want to swap its main element — the

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

每天学习Python两个小时是否足够?这取决于你的目标和学习方法。1)制定清晰的学习计划,2)选择合适的学习资源和方法,3)动手实践和复习巩固,可以在这段时间内逐步掌握Python的基本知识和高级功能。

Python在开发效率上优于C ,但C 在执行性能上更高。1.Python的简洁语法和丰富库提高开发效率。2.C 的编译型特性和硬件控制提升执行性能。选择时需根据项目需求权衡开发速度与执行效率。

Python和C 各有优势,选择应基于项目需求。1)Python适合快速开发和数据处理,因其简洁语法和动态类型。2)C 适用于高性能和系统编程,因其静态类型和手动内存管理。

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。

Python在科学计算中的应用包括数据分析、机器学习、数值模拟和可视化。1.Numpy提供高效的多维数组和数学函数。2.SciPy扩展Numpy功能,提供优化和线性代数工具。3.Pandas用于数据处理和分析。4.Matplotlib用于生成各种图表和可视化结果。

Python在Web开发中的关键应用包括使用Django和Flask框架、API开发、数据分析与可视化、机器学习与AI、以及性能优化。1.Django和Flask框架:Django适合快速开发复杂应用,Flask适用于小型或高度自定义项目。2.API开发:使用Flask或DjangoRESTFramework构建RESTfulAPI。3.数据分析与可视化:利用Python处理数据并通过Web界面展示。4.机器学习与AI:Python用于构建智能Web应用。5.性能优化:通过异步编程、缓存和代码优
