Skip to content

Instantly share code, notes, and snippets.

@nu12
Last active May 14, 2020 17:58
Show Gist options
  • Select an option

  • Save nu12/e827637e53c6b56fe0303c28341de221 to your computer and use it in GitHub Desktop.

Select an option

Save nu12/e827637e53c6b56fe0303c28341de221 to your computer and use it in GitHub Desktop.
CRUD with Django

CRUD Django

Source: EN | PT

Packages and env

Install packages

$ sudo apt-get update -y 
$ sudo apt-get upgrade -y 
$ sudo apt-get install -y python3-pip python3-virtualenv

Create new env and activate

$ python3 -m virtualenv myenv -p python3 --always-copy
$ source myenv/bin/activate

Install django

(myenv) $ python -m pip install django

Create project and app

Create a project

(myenv) $ django-admin startproject project .

Create an app

(myenv) $ django-admin startapp products

Register the app in project/settings.py

Register products.urls in project/urls.py and add import to include

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('products.urls')),
    path('admin/', admin.site.urls),
]

Create the file products/urls.py (copy from project/urls.py)

from django.urls import path

urlpatterns = [
]

Create the model class in products/models.py

class Product(models.Model):
	description = models.CharField(max_length = 100)
	price = models.DecimalField(max_digits = 9, decimal_places = 2)
	quantity =  models.IntegerField()

	def __str__(self):
		return self.description

See availables data types

Run the migration

(myenv) $ python manage.py makemigrations
(myenv) $ python manage.py migrate

Import the new model in products/views.py and add import to redirect

from django.shortcuts import render, redirect
from .models import Product

Create the folder products/templates

Run the application with

(myenv) $ python manage.py runserver

(Optional) Create admin

Create a superuser for the application

(myenv) $ python manage.py createsuperuser 

Register the model in products/admin.py

from django.contrib import admin
from .models import Product

admin.site.register(Product)

CRUD

Items needed for CRUD

  • Form
  • View
  • Template
  • URL

Read/Retrieve

Create the view for list_products in products/views.py

def list_products(request):
	products = Product.objects.all()
	return render(request, 'products.html', {'products': products})

Create the template products/templates/products.html

<ul>
	{% for product in products %}
		<li>{{ product.description }}</li>
	{% endfor %}
</ul>

Import the list_products function and add the path for the view in products/urls.py

from django.urls import path
from .views import list_products

urlpatterns = [
	path('', list_products, name='list_products'),
]

Create

Create the file products/forms.py and create a form to be used

from django import forms
from .models import Product

class ProductForm(forms.ModelForm):
	class Meta:
		model = Product
		fields = ['description', 'price', 'quantity']

Import the form with from .forms import ProductForm and create the view for create_product in products/views.py and

def create_product(request):
	form = ProductForm(request.POST or None)

	if form.is_valid():
		form.save()
		return redirect('list_products')

	return render(request, 'product_form.html', {'form': form})

Add a link to the form in products/templates/products.html

<a href="{% url 'create_product' %}">New product</a>

Create the template in products/templates/product_form.html

<form method="POST">
	{% csrf_token %}
	{{ form }}
	<input type="submit" value="Save" />
</form>

Import the create_product function and add the path for the view in products/urls.py

from django.urls import path
from .views import list_products, create_product

urlpatterns = [
	path('', list_products, name='list_products'),
	path('new', create_product, name='create_product'),
]

Update

Create the view for update_product in products/views.py with id as a parameter

def update_product(request, id):
	product = Product.objects.get(id=id)
	form = ProductForm(request.POST or None, instance=product)

	if form.is_valid():
		form.save()
		return redirect('list_products')

	return render(request, 'product_form.html', {'form': form, 'product':product})

Add a link to the form in each product in products/templates/products.html

<li>{{ product.description }} <a href="{% url 'update_product' product.id %}">Update</a></li> 

Import the update_product function and add the path for the view in products/urls.py

from django.urls import path
from .views import list_products, create_product, update_product

urlpatterns = [
	path('', list_products, name='list_products'),
	path('new', create_product, name='create_product'),
	path('update/<int:id>', update_product, name='update_product'),
]

Delete

Create the view for delete_product in products/views.py with id as a parameter

def delete_product(request, id):
	product = Product.objects.get(id=id)
	if request.method == 'POST':
		product.delete()
		return redirect('list_products')
	return render(request, 'product_confirm_delete.html', {'product': product})

Add a delete link in products/templates/product_form.html

{% if product %}
	<a href="{% url 'delete_product' product.id %}">Delete</a>
{% endif %}

Create the template in products/templates/product_confirm_delete.html

<form method="POST">
	{% csrf_token %}
	Delete {{ product.description }}. Are you sure?
	<input type="submit" value="Confirm" />
</form>

Import the delete_product function and add the path for the view in products/urls.py

from django.urls import path
from .views import list_products, create_product, update_product, delete_product

urlpatterns = [
	path('', list_products, name='list_products'),
	path('new', create_product, name='create_product'),
	path('update/<int:id>', update_product, name='update_product'),
	path('delete/<int:id>', delete_product, name='delete_product'),
]

Aditional info

Django data types

Data type Django model type Description
Date/time models.DateField() Creates a date field to store dates
models.TimeField() Creates a date field to store times
models.DateTimeField() Creates a datetime field to store dates with times
Number models.DecimalField(decimal_places=X,max_digits=Y) Enforces a number have a maximum X digits and Y decimal points Creates a decimal field to store decimal numbers. Note both X and Y arguments are required, where the X argument represents the maximum number of digits to store and the Y argument represents the number of decimal places to store.
models.FloatField() Creates a column to store floating-point numbers.
models.IntegerField() Creates a column to store integer numbers.
Text models.CharField(max_length=N) Creates a text column, where the max_length argument is required to specify the maximum length in characters.
models.TextField() Creates a text field to store text.
models.EmailField() Enforces the text is a valid email with the internal Django EmailValidator to determine what is and isn't a valid. Works just like CharField defaulting to a max_length of 254 characters and also enforces the string is a valid email.

Source and more data types

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment