Django Tutorial - Custom Forms
# Creating Custom Dynamic Forms in Django: A Step-by-Step Tutorial
In this tutorial, we will guide you through the process of creating custom dynamic forms in Django. This builds on our previous video where we worked with basic Django forms using form classes. Today, we aim to make your forms more interactive and user-friendly by allowing users to add items to their todo list and track whether they are complete or incomplete.
---
## Introduction
The goal of this tutorial is to enable users to perform two key tasks:
1. **Add new items** to their todo list.
2. **Mark items as complete/incomplete** using checkboxes.
Currently, our application only allows users to create new todo lists but lacks functionality for adding individual items or tracking completion status. We will address these gaps by creating a custom form that handles both tasks dynamically.
---
## Setting Up the Form in HTML
To achieve this, we need to set up a form within our HTML file. The form must handle POST requests to send data back to our view. Here's how we structure the form:
```html
```
### Explanation:
1. **Form Structure**: The form uses the `post` method to send data securely.
2. **Buttons**: We include two buttons:
- **Save**: Updates the completion status of items.
- **Add Item**: Adds new items to the todo list.
3. **Input Field**: A text field (`name="new"`) allows users to input new todo items.
4. **Checkboxes**: Each todo item has a checkbox. The `name` attribute is set to `c{{item.id}}`, where `{{item.id}}` is replaced with the actual item ID during rendering. This helps us identify which checkboxes are checked when the form is submitted.
---
## Handling Form Data in Django Views
Once the form is set up, we need to handle the data it sends to our view. Here's how we process the form submission:
```python
def index(request):
if request.method == 'POST':
# Process checkbox updates
if request.POST.get('save'):
for item in TodoItem.objects.all():
checkbox_name = f'c{item.id}'
if request.POST.get(checkbox_name) == 'clicked':
item.complete = True
else:
item.complete = False
item.save()
# Process new item addition
elif request.POST.get('add_item'):
text = request.POST.get('new')
if len(text) > 2:
TodoItem.objects.create(text=text, complete=False)
return render(request, 'index.html', {'todo_list': TodoItem.objects.all()})
```
### Explanation:
1. **Save Button Handling**:
- When the Save button is clicked, we loop through all todo items.
- For each item, we check if its corresponding checkbox was marked using `request.POST.get()`.
- If checked, we set `item.complete = True`; otherwise, `item.complete = False`.
2. **Add Item Handling**:
- When the Add Item button is clicked, we retrieve the input value from the `new` field.
- We validate the input to ensure it has at least 3 characters.
- If valid, we create a new `TodoItem` with the provided text and set `complete=False`.
---
## Testing the Form
After implementing these changes, you can test the functionality:
1. **Adding Items**: Type a new item in the input field and click "Add Item."
2. **Checking/Unchecking Items**: Click the checkbox next to an item to mark it as complete or incomplete.
3. **Saving Changes**: Click the "Save" button to persist any changes you've made to the checkboxes.
---
## Conclusion
By following this tutorial, you have successfully created a custom dynamic form in Django that allows users to add new items and track their completion status. This approach provides a solid foundation for building more complex forms and interactive features in your Django applications.
In our next video, we will explore how to enhance the user interface by adding Bootstrap styling and additional features like a sidebar. Stay tuned!