Rendering Django Forms Automatically for Beginners

  • models.py contains classes needed for rendering things such as forms automatically when a user loads the webpage. The form is pieced together using django with each page reload instead of already existing as an .html webpage.
  • Import then use Django’s ModelForm class in your forms.py file to create a form automatically from a model object in models.py.
  • Add the following form class to forms.py:
class NameForm(forms.ModelForm)
  • Also add the following model class to models.py:
class Name(models.Model)
  • Define properties for the model class in models.py (in this case the properties are fields in your form):
first_name = models.CharField(max_length=100)
  • Also, Django’s ModelForm class requires a ‘fields’ or ‘exclude’ attribute so add the following underneath the form class in forms.py:
class Meta:
model = Name # model class
exclude = ('field_excluded',)
  • Import the model and form to views.py and add a class to create a view of each form submission:
from .forms import NameForm
from .models import Name

class NameCreate(CreateView):
model = Name # model class
form_class = NameForm #form class
  • Once a submission is made, the user can be redirected to their submission with this code added as a property beneath the model class. The submission is rendered in an .html page:
def get_absolute_url(self):
return reverse('html-page-name', args=[str(self.id)])

Leave a Reply

Your email address will not be published. Required fields are marked *