2022-01-18 | BugBytes | Building Django forms with django-crispy-forms

从丑陋到优雅 Django表单的crispy-forms改造与HTMX应用

媒体详情

上传日期
2025-06-27 09:54
来源
https://www.youtube.com/watch?v=MZwKoi0wu2Q
处理状态
已完成
转录状态
已完成
Latest LLM Model
gemini-2.5-pro

转录

下载为TXT
speaker 1: In this video, we're going to take a look at Jango Crespy forms. We're going to build a form in Jango that we're then going to refactor using Jango Crespy forms. The documentation leads off boldly with the statement forms have never been this kspy. Now the important thing to know is that it provides you with a crispy filter and also a crispy tag that you can use in your Jango templates that can help you render your forms in a nicer and more stylistically pleasing manner. So we're going to build a simple University enrollment form. It's not going to have back end. It's not going to integrate with the database. We're purely going to look at how Django crispy forms can help with the styling and with adding other attributes to your forms. So within vs code, I have a project open. The server is running on port 8000, and we can have a look at that. Now it just says hello and we're going to change that template throughout this tutorial. So let's start by building the form. If we go to the forms pi file, we've got a University form and currently there is nothing in that form, but it inherits from the jangle forms form class. And we're now going to build out a basic form with four fields. So let's remove the PaaS statement here and we're gonna to build out these fields. Now. Firstly, we have the person's name. We'll just say that's a car field. Then we've got the edge, which we will see as an integer field. Now we're going to define a subject field and this is going to be forms dot choice field and we will define the choices to be subject choices. And I'm gonna to paste these in above here in the form class. So we're gonna to have these subject choices, web development, systems programming and data science, and we attach those as choices to our choice field. And finally, I'm gonna to define a date of and that's going to be a forms date field. So throughout this tutorial, we're going to build on this form and add different wedges. We're going to add jangle crispy forms on the templates, and we're going to add some htmx attributes at the end to show how that's done and how it integrates with jangle crispy forms. But for now, this is the basic structure of our form. So what we're now going to do is send that form to our template via the context. So in the views pyfile, we're gonna na add a key for the form within our context and we'll instantiate the University form and PaaS that in as the form key. So now we have access to the form within our template and we'll replace the hello with the rendered form like that. So what we can do now is we can inspect the front end if we go back to the page. And you see now we have these fields. But the form at the moment, it's rather ugly. You wouldn't want to use a website that defined a form like this one. We can add some very basic stylistic changes, such as the form, though, has p thatwill render each field as a paragraph. Again, that's not very nice, arguably isn't much better than it was before. So let's now bring Jango crispy forms into the mix, and we'll see how we can use that to make this form look better. So the first thing to do is to install Jango crispy forms on the documentation. You should see installation section on the left hand side. And we can copy the pep install command and execute that within our terminal, ideally in a virtual environment, and thatinstall that within your system. And once that's installed, you can then add it to your installed apps. So go to settings pi. And within installed apps, you can add crispy forms. And if we go back to the documentation, you should see that jangle chspy forms has some template packs for different libraries, css frameworks, we're going to use the bootstrap four template packs. So copy this particular setting. Again, this goes into settings pi. It's called crispy template pack and we're gonna to set that equal to bootstrap four in this tutorial. So right at the bottom of your settings, pi file, crispy template pack equals bootstrap four, and that's all the settings that we need. We can now use Django crispy forms within our template. And what we need to do is load the crispy forms tag. So add that statement within your template at the top and then online line sewhere, we actually render the form. I'm gonna to change this line here. I'm gonna to use the crispy form tag. So crispy and we PaaS the form to that tag. And that's all we need to do. So let's run the Jango server again and we'll go back to the front end. And now you see we get a form that looks much better. We have these bootstrap rendered form fields and the drop down list looks better. Now what we're gonna to do next is we're gonna to change some of the widgets that are being used in these fields. We've seen now how easy it is to use Jango crispy forms to change the styling a little bit. Let's now change the subject that's currently a drop down. We want to know use a radial input. So we're going to see how to do that. And we also want to change the date of birth. This should be a date wedget. At the moment it's a text field that is not ideal, so we're gonna to change that as well. So let's go back to our forums pi file. And within each field you can PaaS a Wiget to control how it's styled. So we're gonna to do that for the subject field. That's a choice field. And we'll PaaS wedgeequalforms dot radio select for this particular field. So if we refresh the page, we now see that instead of a drop down, we get this these three radio buttons instead, and we can pick one of those. So let's go back to vs code. And we're going na change the Wiget being used on line 17 here for the date field. The Wiget in this case is going to be a forms date input. And to that we PaaS an attributes dictionary and we're going to specify that the type of this field should be a date type. So all inputs in html have a type, currently this one, as you can see here, as of type text, we want to change that and use a date field. So if we do that and refresh, we now see that the format has changed and we have a date field. And if you click on that date field to depending on whether it's chrome or edge or Firefox, this might be slightly different. But you get this date Wiget, and that is what you can use to select a date. And we can improve that further. Since this is a date of birth, we can specify that it has to be before the current date. So what I can do there, you can add another field to this attribute stationary. And the field for this date input is max. So we can specify that the maximum date we can enter is going to be the current date. So that's date time dot now and we'll convert that to a date object. And we import from date time the date time object at the top here. And with that, we can refresh the page. And now when we select that, you see that the dates after the current date are grayed out. So let's move on. What we're gonna na do next is we're gonna na use is the Jango Crespy forms form helper, which is available here on the documentation. And the form hailput is something that you can use within the forms net method and that allows you to customize certain aspects of the form. And we're going to see a couple of examples right now. So let's copy this code here, this net method. And we're going to place that within our University form. And at the top here, I'm actually going to import these things. Here. I'm going to import reverse lazy from Django url's. We import the form helper from crispyforms helper and from crispyforms layout. We're importing submit. We're going to see what that is in just a second. And this form helper that we've defined on line eleven here, we can use that to set additional attributes over form. So for example, what we're going to do is set the form action. And the form action we can reverse lazy here. We can reference the index url. This is just to demonstrate how you would set up the form action using jangle crispy forms. We're not going to handle submitting the form in the view, but if we now refresh the front end here, you see that if we inspect the elements, we have now got a form element. We didn't have that before this form action element here. If we comment out the action call here on line twelve and we refresh the page, you see that the form action disappears. So there's no way to specify where the submission should be sent to on the server. If we bring back that action here, we can use the reverse al lazy function. This is similar to the url template tag. And what it does is it looks up your url's by name. In this case, it uses the name of index, and it can then turn that url name into the proper path for that url on the server. So the form action gives us a way of specifying that. And on the helper, we can also specify the form method. And in this case, I could set that to a get request. As you can see at the moment, this form has a method post. So the submission is via a post request. If I now refresh this, you see the method has changed to get, and that's because we're setting this attribute on the form helper instance within our init method. Now the final thing I want to do is I want to add a submit button to the form using Jango crispy forms. So I'm going to paste this line of code here to the helper. We add another input, and this is of type submit, which we imported from the crispy forms dot layout module. And that submit button appears on the front end underneath the form here. If we inspect this element, you see, then it's got this type submit. And that means that when we hit this button, we're essentially going to submit the form to the server and it will be sent to whatever the form action endpoint is. So this is just demonstrating the jangle Crespy forms. It makes it very easy to add attributes to your form. You can add submit buttons and other inputs to your form within the forms and net method. Now the final thing we're going to do in this tutorial is we're going to see how to add htmx attributes to a form field. Now the htmx attributes are added to the fields in the html code. What we're going to do now is use this class here for the form, and we're going to add them via a Weger attribute dictionary, very similar to what we did here for this date input where we attached a dictionary of attributes. We can also do that with our htmx attributes as well. Now within the based or html file, we are loading up htmx here and the script tag. So we have access to htmx within the index html file because that extends the base html file. So what we're gonna to do is we're gonna to target the name field, which corresponds to this element here at the top, and let's attach some htmx attributes to that. So we're gonna to set a wedget here and it's going to be equal to our forms dot text input. And to that, again, we PaaS an attribute Deiny, and here we can attach the htmx attribute such as hx get, and we'll specify where that get request should be sent to. And again, we can use the reverse lazy function as we did here when we set the form action. And we can specify that that's going to be sent to the index url by giving that parameter index. And we can also specify the hx trigger here, hx trigger. And that's going to be equal to the key op event. So now if we save that and refresh the front end, we should now see if we inspect this particular field. Here we have the hx trigger and the hx get attributes. I'm now attached to this input. So if I go to the network tab and we clear this, we should now see that as we type into this, we are actually sending these htmx hx requests to the back end. So it's all working with the setup. And on the terminal on the back end, we see the get requests are coming in. So this is all working. This is how you attach htmx attributes to your jangle form fields within the form class itself. And that is all for this video. So if you've enjoyed the video or learned anything, like and subscribe, and we'll see you in the next video.

最新摘要 (详细摘要)

生成于 2025-06-27 09:56

概览/核心摘要 (Executive Summary)

本视频教程系统性地演示了如何运用 django-crispy-forms 库,将一个朴素的 Django 表单转变为一个样式精美、功能丰富的现代化组件,并最终集成了 HTMX 以实现动态交互。教程的核心亮点在于展示了如何在 Django 的表单类(forms.py)内部完成所有样式和行为的定制,从而保持模板(template)的简洁性。

核心内容涵盖:

  1. 自动化表单美化:通过安装 django-crispy-forms 并配置 Bootstrap 4 模板包,仅需在模板中使用 {% crispy form %} 标签,即可自动将原生表单渲染为符合 Bootstrap 规范的美观样式。
  2. 表单部件 (Widget) 定制:教程演示了如何通过在表单字段中指定 widget 参数,灵活地改变输入控件的类型。例如,将下拉选择框(ChoiceField)转换为单选按钮组(forms.RadioSelect),并将标准的文本输入框改造为带有日期范围限制的 HTML5 日期选择器(forms.DateInput)。
  3. 使用 FormHelper 集中控制:介绍了 FormHelper 类的强大功能,它允许在表单的 __init__ 方法中集中管理表单级别的属性,如设置提交地址(form_action)、请求方法(form_method),以及便捷地添加提交按钮(Submit)等布局元素。
  4. 在表单类中集成 HTMX:作为教程的最高级应用,视频清晰地展示了如何在表单字段的 widget 属性中直接添加 HTMX 属性(如 hx-gethx-trigger)。这种方法将交互逻辑与表单定义紧密耦合,避免了在模板中手动添加属性的繁琐,实现了更优雅的代码组织。

总而言之,django-crispy-forms 不仅是简化 Django 表单样式的利器,更提供了一套完整的机制,用于在后端代码中精确控制表单的结构、行为乃至与 HTMX 这类现代前端库的集成,显著提升了开发效率与最终用户体验。


1. 构建基础 Django 表单

  • 项目设置:教程在一个基础 Django 项目中进行,服务器运行于本地 8000 端口。完整的起始代码可在其 GitHub 仓库 中找到。
  • 表单定义与初始渲染
    • forms.py 文件中,创建了一个继承自 django.forms.FormUniversityForm 类。
    • 该表单包含四个字段:name (CharField)、age (IntegerField)、subject (ChoiceField) 和 date_of_birth (DateField)。
    • 在视图中实例化表单并传递到模板,使用 {{ form.as_p }} 进行初步渲染。
    • 结果:默认渲染的表单样式简陋,被评价为“相当丑陋”,缺乏用户友好性。

2. 集成 django-crispy-forms 实现样式美化

2.1 安装与配置

  • 步骤 1 (安装):在虚拟环境中使用 pip install django-crispy-forms 安装库。
  • 步骤 2 (注册应用):在 settings.pyINSTALLED_APPS 列表中添加 'crispy_forms'
  • 步骤 3 (指定模板包):在 settings.py 中添加配置 CRISPY_TEMPLATE_PACK = 'bootstrap4'。此设置告知 crispy-forms 使用 Bootstrap 4 的 HTML 结构和 CSS 类来渲染表单,从而实现样式的自动化适配。

2.2 模板应用

  • 步骤 1 (加载标签):在模板文件顶部,使用 {% load crispy_forms_tags %} 加载 crispy-forms 的模板标签库。
  • 步骤 2 (渲染表单):将原有的 {{ form.as_p }} 替换为 {% crispy form %}
  • 效果:刷新页面后,表单立即呈现出专业、美观的 Bootstrap 样式,包括对齐的标签、标准化的输入框和样式化的下拉列表,视觉效果“好得多”。

3. 自定义表单部件 (Widgets)

教程进一步演示了如何通过 widget 参数修改特定字段的默认渲染行为。

  • 示例 1:将下拉列表改为单选按钮
    • 操作:为 subject 字段添加 widget=forms.RadioSelect 参数。
    • 效果:原先的下拉选择框被替换为一组水平排列的单选按钮。
  • 示例 2:创建高级日期选择器
    • 操作:为 date_of_birth 字段设置 widget=forms.DateInput(attrs={'type': 'date'}),将其转换为 HTML5 日期输入框。
    • 进一步优化:通过添加 max 属性,'max': datetime.datetime.now().date(),来限制可选日期不能晚于当前日期。
    • 效果:字段变为一个标准的日期选择器,并且日历控件中未来的日期会被禁用(显示为灰色)。

4. 使用 FormHelper 进行高级定制

FormHelper 提供了一个在表单类内部进行高级配置的接口。

  • 实现方式:在表单的 __init__ 方法中实例化 FormHelper,并将其赋值给 self.helper
  • 功能示例
    • 设置表单属性:通过 self.helper.form_action = reverse_lazy('index')self.helper.form_method = 'get',可以动态设定表单的提交 URL 和 HTTP 方法。
    • 添加布局元素:使用 self.helper.add_input(Submit('submit', 'Submit')),可以轻松地在表单中添加一个经过 Bootstrap 样式化的提交按钮。
  • 效果:这些配置会直接在最终渲染的 HTML <form> 标签上生效,无需在模板中编写任何额外的 HTML 代码。

5. 在表单类中集成 HTMX 属性

教程的最后一部分展示了 crispy-forms 的高级用法:在 forms.py 中直接为字段注入 HTMX 属性。

  • 目标:为 name 字段添加 HTMX 功能,使其在用户输入时(keyup 事件)向服务器发送 GET 请求。
  • 前提:确保项目的基础模板已加载 HTMX 库。
  • 实现方式:为 name 字段配置 TextInput 部件,并在其 attrs 字典中定义 HTMX 属性。
    python widget=forms.TextInput(attrs={ 'hx-get': reverse_lazy('index'), 'hx-trigger': 'keyup' })
  • 验证与效果
    • 在浏览器中检查 name 输入框的元素,可以看到 hx-gethx-trigger 属性已成功附加。
    • 当在输入框中键入内容时,浏览器的“网络”标签页会显示实时发送的 GET 请求,同时,后端的服务器终端也会打印出接收到这些请求的日志,证明 HTMX 集成成功。

结论

本教程清晰地证明了 django-crispy-forms 是一个功能强大的 Django 应用,它不仅能极大地简化表单的样式化工作,还通过 FormHelperwidget 属性提供了一套优雅的机制,用于在后端代码中实现对表单结构、行为和高级前端交互(如 HTMX)的全面控制,是构建现代化、高效率 Django 应用的宝贵工具。