Creating a simple modelform - Django

/ #Django


In this guide, I will show you how to create a simple modelform using Django.

Creating the project

Let's begin by creating a brand new Django project. This isn't necessary of course, I just do it to make things as clean as possible for this post.

$ django-admin.py startproject modelformtest
$ cd modelformtest

The project is created and we're inside the root folder of the project. We can then continue by starting a demo app.

$ python manage.py startapp product

We need to tell Django that this application exist, so add "product" to the list of installed apps inside "modelformtest/settings.py".

INSTALLED_APPS = [
  .
  . 
  .
  'product'
]

Creating the database model

class Product(models.Model):
  title = models.CharField(max_length=200)
  description = models.TextField()

The database model is really simple, but this is just a quick example of what it can look like. Let's go back to the command line and update the database.

$ python manage.py makemigrations
$ python manage.py migrate

Creating the form

Inside the product folder, create a new file called "forms.py". Add the following content to it:

from django import forms
from .models import Product

class ProductForm(forms.ModelForm):
  class Meta:
    model = Product
    fields = 'all'

This demo form is also quite simple. We create a new instance of the ModelForm class. To configure this we add some options to the Meta class. We pass in the Product model and we also say that we want all the fields to be rendered.

Creating the views

We need to add a view where we can render the form. Open up views.py and add this code:

from django.shortcuts import render, redirect

def addproduct(request):
  if request.method == 'POST':
    form = ProductForm(request.POST)
    if form.is_valid():
      form.save()

      return redirect('/')
  else:
    form = ProductForm()

  context = {
    'form': form
  }

  return render(request, 'addproduct.html', context)

This is a really simple view. If the request is POST, we pass in the POST data to the form, and if not, we just create a new instance of it.

Creating the template

Create a new folder in the "product" folder called templates and add a file inside there called "addproduct.html". The contents of this file should look something like this:

<html>
  <body>
    <form method="post" action=".">
      {% csrf_token %}

      {{ form.as_p }}
      <input type="submit" value="Add product">
    </form>
  </body>
</html>

And that is it! This will render the whole form, including errors if there are some.

Testing the form

Before you can test the form, you need to make sure that Django can find the template and also add the view to the url patterns.

Open up urls.py and make the following changes:

from product.views import addproduct # Import the view

urlpatterns = [
  .
  .
  .
  path('addproduct/', addproduct, name='addproduct') # Add the view to the patterns
]

Open up settings.py and add the templates dir to the template configuration:

'DIRS': [os.path.join(BASE_DIR, 'product/templates'],

And now you should be able to test the form :-)

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.