Part 3: Django CRUD, Display Models

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

Full code on https://github.com/shanegibney/djangoCRUD

Add to the crudapp/models.py 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/admin.py

from .models import Members

admin.site.register(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/views.py 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">
<head>
</head>
<body>
  {% if details %}
  <ul>
    {% for item in details %}
    <li>{{ item.description}}</li>
    {% endfor %}
  </ul>
  {% else %}
  <p>No polls are available.</p>
  {% endif %}
</body>

Part 4: Django CRUD. Create