Great Deal! Get Instant $25 FREE in Account on First Order + 10% Cashback on Every Order Order Now

Django Part 4 • Django Part 4: Forms § Adding forms processing for Sudoku example § Create file forms.py within application folder • forms.py from django import forms from django.core import...

1 answer below »


Django Part 4
• Django Part 4: Forms
§ Adding forms processing for Sudoku example
§ Create file forms.py within application folder
• forms.py
from django import forms
from django.core import validators

class SudokuForm(forms.Form):
location=forms.CharField(min_length=4, max_length=4, strip=True)
value = forms.CharField(min_length=1, max_length=1, strip=True)
§ Update view to pass new form into template for rendering
• views.py: home()
• Import new form at top
• from app1.forms import SudokuForm
• Pass empty form to template renderer
• page_data = { "rows": [], "sudoku_form": SudokuForm }
§ Generate form on template
template.py
div >
{% csrf_token %}
{{sudoku_form.as_table}}

utton type="submit" >Move
utton>

form>


utton type="submit" >New Game
utton>

form>

div>
Note: .as_p renders the form controls within a paragraph tags (renders controls vertically with alignment).
There are others too like .as_table.
Note: CRSF stands for Cross-Site Request Forgery, which secures the HTTP POST action when this
form is submitted back to us (prevents spoofing).
CRSF is required by Django for POST requests.
§ Handle form submissions
• Handle New Game form submission
§ views.py
§
if (Board.objects.all().count() == 0) or (request.method == 'POST' and
'new_game' in request.POST):
XXXXXXXXXXnewGame(request)
elif (request.method == 'POST'):
XXXXXXXXXXsudoku_form = SudokuForm(request.POST)
XXXXXXXXXXif (sudoku_form.is_valid()):
XXXXXXXXXXlocation = sudoku_form.cleaned_data["location"]
XXXXXXXXXXvalue = sudoku_form.cleaned_data["value"]
XXXXXXXXXXBoard(name=location, value=value).save()
XXXXXXXXXXelse:
XXXXXXXXXXpage_data["sudoku_form"] = sudoku_form

...continued on next page...
§ Remove "in-line" board input controls (for now)
• home.html, replace section:
{% for name,value in row.items %}

{% if value == 0 %}

{% else %}

{% endif %}

td>
{% endfor %}
{% endfor %}

§ Add front-end and back-end validation to move form:
§
§ forms.py:

def validate_location(value):
if (value[0] != "r") or (not value[1].isdigit()) or \
(value[2] != "c") or (not value[3].isdigit()):
XXXXXXXXXXraise forms.ValidationE
or("Use row and column format, e.g. r1c1.")

def validate_value(value):
try:
XXXXXXXXXXint(value)
except ValueE
or:
XXXXXXXXXXraise forms.ValidationE
or("Enter an integer from 1 to 9.")
if (int(value) < 1 or int(value) > 9):
XXXXXXXXXXraise forms.ValidationE
or("Enter an integer from 1 to 9.")

class SudokuForm(forms.Form):
location=forms.CharField(min_length=4, max_length=4, strip=True,
XXXXXXXXXXwidget=forms.TextInput(attrs={'placeholder':'r1c1','style':'font-size:small'}),
XXXXXXXXXXvalidators=[validators.MinLengthValidator(4),
XXXXXXXXXXvalidators.MaxLengthValidator(4),
XXXXXXXXXXvalidate_location])
value = forms.CharField(min_length=1, max_length=1, strip=True,
XXXXXXXXXXwidget= forms.TextInput(attrs={'placeholder':'1','style':'font-size:small'}),
XXXXXXXXXXvalidators=[validators.MinLengthValidator(1),
XXXXXXXXXXvalidators.MaxLengthValidator(1),
XXXXXXXXXXvalidate_value])
§ Side-Note: Page refresh vs page reload

Django Models
Django Models & Databases
Django ORM (Object Relational Model)


Source: https:
djangobook.com/mdj2-models/
Models connect our Django apps to a DB
The default DB is sqlite (embedded DB)
Other DBs are also supported (modify the ENGINE parameter use for DATABASES in settings.py.)
Included
sqlite (default): django.db.backends.sqlite3
MySQL: django.db.backends.mysql
Oracle: django.db.backends.oracle
PostgresSQL: django.db.backends.postgresql_psycopg2
Add-Ons
IBM DB2
Firebird
Others…
Models are created using a class structure inside of an application's models.py file
Inherit from django.db.models.Model
Each class attribute represents a DB field (table column)
Field type reference: https:
docs.djangoproject.com/en/3.0
ef/models/fields/#model-field-types
Special commands to sync-up apps and project with latest model definitions
Each app
python manage.py makemigrations [] , []...
Project
python manage.py migrate
Coding Examples for Model (sudoku)
Define Model class for Sudoku Board
models.py
from django.db import models

class Board(models.Model):
name = models.CharField(max_length=4, primary_key=True)
value = models.SmallIntegerField()
Run Migrations
python manage.py makemigrations
python manage.py migrate


Enable Django's Built-In Admin Interface and register our new model
Edit admin.py:
from app1.models import Board
#Register your models here
admin.site.register(Board)
Create Django superuser
python manage.py createsuperuser
enter username, password, email>
Add navigation to /admin path
templates/app1/navigation.html

  • Admin
    a>

    li>
    Start project and visit /admin end-point.
    python manage.py runserver
    localhost:8000/admin
    Login with superuser credentials to view admin interface (allows you to view / modify exposed models)
    ...continued on next page...
    Modify view to render Sudoku board from Model data
    views.py
    from app1.models import Board

    # Create your views here.
    def home(request):
    # If there is no model data, reset model for a new game.
    if (Board.objects.all().count() == 0):
    newGame(request)

    page_data = {"rows": []}
    # Populate page_data from board model
    for row in range (1,10):
    ow_data = {}
    for col in range (1,10):
    id= "r{}c{}".format(row,col)
    try:
    ecord = Board.objects.get(name=id)
    ow_data[id] = record.value
    except Board.DoesNotExist:
    ow_data[id] = 0
    page_data.get("rows").append(row_data)

    eturn render(request, 'app1/home.html', page_data)

    def newGame(request):
    page_data = {
    "rows": [
    {"r1c1": 6, "r1c2": 7, "r1c3": 0, "r1c4": 0, "r1c5": 4, "r1c6": 8, "r1c7": 0, "r1c8": 1, "r1c9": 0},
    {"r2c1": 3, "r2c2": 5, "r2c3": 0, "r2c4": 0, "r2c5": 0, "r2c6": 1, "r2c7": 0, "r2c8": 4, "r2c9": 7},
    {"r3c1": 0, "r3c2": 1, "r3c3": 0, "r3c4": 7, "r3c5": 2, "r3c6": 0, "r3c7": 6, "r3c8": 8, "r3c9": 0},
    {"r4c1": 8, "r4c2": 0, "r4c3": 3, "r4c4": 0, "r4c5": 0, "r4c6": 0, "r4c7": 1, "r4c8": 6, "r4c9": 9},
    {"r5c1": 0, "r5c2": 0, "r5c3": 7, "r5c4": 9, "r5c5": 1, "r5c6": 0, "r5c7": 8, "r5c8": 3, "r5c9": 0},
    {"r6c1": 0, "r6c2": 9, "r6c3": 6, "r6c4": 4, "r6c5": 8, "r6c6": 3, "r6c7": 0, "r6c8": 0, "r6c9": 0},
    {"r7c1": 0, "r7c2": 0, "r7c3": 9, "r7c4": 1, "r7c5": 0, "r7c6": 4, "r7c7": 3, "r7c8": 0, "r7c9": 8},
    {"r8c1": 4, "r8c2": 8, "r8c3": 1, "r8c4": 0, "r8c5": 0, "r8c6": 0, "r8c7": 7, "r8c8": 0, "r8c9": 6},
    {"r9c1": 7, "r9c2": 0, "r9c3": 0, "r9c4": 8, "r9c5": 6, "r9c6": 2, "r9c7": 0, "r9c8": 0, "r9c9": 1}
    ]
    }
    # Delete all board model objects (records)
    Board.objects.all().delete()

    # Populate board model objects from page_data
    for row in page_data.get("rows"):
    for name, value in row.items():
    Board(name=name, value=value).save()

    Now existing template code will render from model data.

    Next time...we'll handle the Sudoku moves on the backend by updating the model using Django forms.
  • Answered 5 days AfterMar 03, 2022

    Solution

    Manikandan answered on Mar 09 2022
    72 Votes
    SOLUTION.PDF

    Answer To This Question Is Available To Download

    Related Questions & Answers

    More Questions »

    Submit New Assignment

    Copy and Paste Your Assignment Here