Building on what gruszczy said if you have a model named Author
you can declare a ModelForm
for this model thus:
class AuthorForm(forms.ModelForm): # Note the different superclass.
class Meta:
model = Author
If you want a form that includes all attributes of Author
then that is all you need to do. If however you need only a subset of attributes of Author
(say name
and title
) then you can modify the model form thus:
class AuthorForm(forms.ModelForm): # Note the different superclass.
class Meta:
model = Author
fields = ('name', 'title',)
Note that you didn't have to use CharField
here.
If on the other hand you want everything but name
and title
, then you can define your form like this:
class AuthorForm(forms.ModelForm): # Note the different superclass.
class Meta:
model = Author
exclude = ('name', 'title',)
Update
(After reading comment) You can treat AuthorForm
like any other regular form. In your view you can instantiate this form with or without data based on the request.method
. Something like this:
def add_author(request, *args, **kwargs):
if request.method == 'GET':
form = AuthorForm()
elif request.method == 'POST':
form = AuthorForm(request.POST.copy())
if form.is_valid():
author = form.save()
# Redirect to listing etc.
context = dict(form = form)
return render_to_response(template_name, context) # etc.
And in your template:
{{ form.as_p }}
There are different ways to render a form; as_p
is but one of them.