Creating forms in Django
In Django, we can use forms to handle user input and validate data. We can define forms in our app's forms.py file. Here's an example form for creating a new blog post:
python
Copy code
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content']
In this example, we define a PostForm class that inherits from Django's ModelForm. We set the Meta class to use the Post model and define the fields attribute to include the title and content fields.
We can use our form in a view by importing it and rendering it in a template:
python
from django.shortcuts import render
from .forms import PostForm
def create_post(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form.save()
return redirect('post_list')
else:
form = PostForm()
return render(request, 'create_post.html', {'form': form})
In this example, we define a create_post view that handles POST requests by creating a new Post object with the submitted form data. We render the create_post.html template with the PostForm object passed as context.
No comments:
Post a Comment