I want to fill up form with data from model instance. But my form has less fields than model. If I have code like this:
class Item(models.Model) name = models.CharField(max_length=100) price = models.PositiveIntegerField() class ItemForm(forms.Form): name = forms.CharField()
What wrong is with this function and how it should look to be good?
def bound_form(request, id): item = Item.objects.get(id=id) form = ItemForm(item.name) return render_to_response('bounded_form.html', {'form': form})
I getting error like this: AttributeError: 'ItemForm' object has no attribute 'get'
First, create a model that contains fields name and other metadata. It can be used to create a table in database and dynamic HTML form. This file contains a class that inherits ModelForm and mention the model name for which HTML form is created. Write a view function to load the ModelForm from forms.py.
Model Forms are forms that are connected directly to models, allowing them to populate the form with data. It allows you to create a form from a pre-existing model. You add an inline class called Meta, which provides information connecting the model to the form. An inline class is a class within another class.
Django ModelForm is a class that is used to directly convert a model into a Django form. If you're building a database-driven app, chances are you'll have forms that map closely to Django models. For example, a User Registration model and form would have the same quality and quantity of model fields and form fields.
Generally when creating a form for a Model, you will want to use ModelForm. It keeps to the DRY principle such that you do not have to redefine field types for the form class. It also automatically handles validation. You retain full flexibility to customize the fields and widgets used. Use fields
to specify the fields you want or exclude
to specify fields to ignore. With your example:
from django import forms from django.shortcuts import get_object_or_404 class ItemForm(forms.ModelForm): class Meta: model = Item fields = ("name", ) def bound_form(request, id): item = get_object_or_404(Item, id=id) form = ItemForm(instance=item) return render_to_response('bounded_form.html', {'form': form})
get_object_or_404()
is useful here as a form of error handling. Using Item.objects.get(id=id)
on a missing ID will throw an uncaught Item.DoesNotExist
exception otherwise. You could use a try/except block also of course.
def bound_form(request, id): item = Item.objects.get(id=id) form = ItemForm(initial={'name': item.name}) return render_to_response('bounded_form.html', {'form': form})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With