Django – Use ModelForm to List and Create User Data

Django User List

Django User List

Here is a very basic example to show you how to use ModelForm in Django to list and create user data. Let’s start from creating Django app and MySQL Database.

Create your Django App

$ python manage.py startapp users

Open your project settings.py and add your app into INSTALLED_APPS like this:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'user',
)

Add new url pattern into urls.py.

from django.conf.urls import include, url
from django.contrib import admin
import user.views as UserViews

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^user/', UserViews.Users.as_view()),
]

Here is the DB you need

After you created the Django App user, you will need to create a table which has users_ as it’s prefix. In Django, the default table name will be [app]_[table]

mysql> SHOW TABLES;
+-------------------+
| Tables_in_yosites |
+-------------------+
| django_migrations |
| user_users        |
+-------------------+
2 rows in set (0.00 sec)

mysql> SHOW COLUMNS FROM user_users;
+-----------+--------------+------+-----+-------------------+-------+
| Field     | Type         | Null | Key | Default           | Extra |
+-----------+--------------+------+-----+-------------------+-------+
| id        | varchar(50)  | NO   | PRI |                   |       |
| name      | varchar(100) | NO   |     |                   |       |
| create_at | datetime     | NO   |     | CURRENT_TIMESTAMP |       |
| status    | varchar(20)  | NO   |     | active            |       |
+-----------+--------------+------+-----+-------------------+-------+
4 rows in set (0.01 sec)

Create Model – users/models.py

Inside of models.py, you need to defind the fields. It should look like this:

from django.db import models

class Users(models.Model):
    id = models.CharField(max_length=50, primary_key=True)
    name = models.CharField(max_length=100)
    create_at = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=20, default='active')

Create Form – users/forms.py

We are using ModelForm in here to extend the user/models.py we just created. In the class Meta, all you need to do is to tell this form which model you are going to use, and what kinda fields you would like to display for users.

I only picked up two fields: ['id', 'name'] because I don’t need user to worry about other two columns.

from django import forms
from .models import Users

class UserForm(forms.ModelForm):
    class Meta:
        model = Users
        fields = ['id', 'name']

Create View – users/views.py

Now we already have our model and form ready. Let’s put those data into view so we can display the user list and the creating form in HTML template.

Here is the basic requirement for this page.

When user go to http://localhost/user/, they should be able to see the user list and a form which allows them to add new user.

Base on this requirement, we need to prepare something for GET method.

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import View
from .models import Users as UsersModel
from .forms import UserForm


class Users(View):
    template_name = 'users.html'

    def get(self, request):
        user_list = []
        form_user = UserForm()
        users = UsersModel.objects.all()[:50]

        for user in users:
            user_list.append({'id': user.id, 'name': user.name, 'status': user.status, 'create_at': user.create_at})

        return render(request, self.template_name, {
            'title': 'User List',
            'user_list': user_list,
            'form_user': form_user
        })

In the code, we already assign our template_name as users.html; let’s create this template for our view so we will be able to see the page correctly.

Create Template – user/templates/users.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <table>
        <caption>{{title}}</caption>
        <thead><th>ID</th><th>Name</th><th>Status</th><th>Create At</th></thead>
        <tbody>
        {% for user in user_list%}
        <tr><td>{{user.id}}</td><td>{{user.name}}</td><td>{{user.status}}</td><td>{{user.create_at}}</td></tr>
        {% endfor %}
        </tbody>
    </table>
    <form method="POST" action="/user/">
        <fieldset>
            <legend>Create User</legend>
            {% csrf_token %}
            {{form_user}}
            <button type="submit">Create</button>
        </fieldset>
    </form>
  </body>
</html>

Now, if you go to http://localhost/user/, you should be able to see the page looks like our screenshot.

But we are not done yet, because the user creating form is not ready yet. So, let’s keep working on our views.py.

Add POST method into views.py

Open your user/views.py, let’s add few more lines to make sure that we can create new users. I put post() method at the bottom of this class.

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import View
from .models import Users as UsersModel
from .forms import UserForm


class Users(View):
    template_name = 'users.html'

    def get(self, request):
        user_list = []
        form_user = UserForm()
        users = UsersModel.objects.all()[:50]

        for user in users:
            user_list.append({'id': user.id, 'name': user.name, 'status': user.status, 'create_at': user.create_at})

        return render(request, self.template_name, {
            'title': 'User List',
            'user_list': user_list,
            'form_user': form_user
        })

    def post(self, request):
        form_user = UserForm(request.POST)
        if form_user.is_valid():
            form_user.save()
            return HttpResponseRedirect('/user/')

This post() method will take the data you sent from POST then check it. If the data is valid, it will trigger form_user.save() to create new record, then it will redirect to http://localhost/user/ again to show you the updated result.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s