Part 3: Django CRUD, Display Models

Continued from Part 2: Setting up Django, URL’s & Views

Full code on

Add to the crudapp/ file

from django.db import models

In the same file create a model called ‘Members’ with columns for ‘first_name’, ‘last_name’ and ‘description’. This is equivalent to a table called ‘Members’ with fields for ‘first_name’, ‘last_name’ and ‘description’.

class Members(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    description = models.CharField(max_length=600)
    # pub_date = models.DateTimeField('date published')
    def __str__(self):
        return ' '. join([ self.first_name, self.last_name, ])

Give the model an admin interface, in crudapp/

from .models import Members

Go to http://localhost:8000/admin and you will see a model called ‘Memberss’ with effectively rows of the database or as we say in Django instances of the class Member. Note Django places an extra ‘s’ on the class name in admin. Using the Django admin you can now view, edit and delete this model.

Next we will change the cruduapp/ file so that it takes data from the model or class Members

from django.shortcuts import render
from .models import Members
# Create your views here.

def init(request):
    details = Members.objects.all()
    context = {'details': details}
    return render(request, 'index.html', context)

This passes all the data in the class Members to index.html where we can display it,

{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
  {% if details %}
    {% for item in details %}
    <li>{{ item.description}}</li>
    {% endfor %}
  {% else %}
  <p>No polls are available.</p>
  {% endif %}

Part 4: Django CRUD. Create