basic form

Date: March 20th 2016
Last updated: March 20th 2016

I found creating forms tricky to get my head around. Hopefully this entry will serve as a reminder for the basic steps to create a generic form with all default settings. The objective is to create an update page for surfers in the existing example I have been working on up until this point.

create forms.py

# some branches removed for clarity
├── mysite
│   ├── settings.py
│   ├── urls.py
...
└── surferprofile
    ├── admin.py
    ├── forms.py #<=== forms.py inside app
    ├── templates
    │   └── surferprofile
    │       ├── diary.html
    ├── urls.py
    └── views.py

Add to forms.py
Note that the Surfer table actually contains Foreign keys and ManyToMany relationships. I have omitted them here by selecting the columns without these relationships.

from django import forms
from surferprofile.models import Surfer

class SurferForm(forms.ModelForm):
    class Meta:
        model = Surfer
        fields = ['firstname','lastname','height', 
                  'weight','DOB','hometown']

update urls.py
This url calls the updateprofile method (created next).

from django.conf.urls import url
from . import views

app_name = 'surferprofile'
urlpatterns = [
    #<snipped>
    url(r'^(?P<surfer_id>[0-9]+)/update/$', views.updateprofile, name='update'),
]

update views.py
The updateprofile method uses surfer_id grabbed in urls.py to get the correct surfer. This provides the instance to populate the fields of the form. If the form is saved the surfer is redirected back to their own profile page which is currently identified by the primary key.

from django.shortcuts import render, get_object_or_404
from .models import Surfer
from .forms import SurferForm

def updateprofile(request, surfer_id):
    surfer = get_object_or_404(Surfer, pk=surfer_id)
    form = SurferForm(request.POST or None, instance=surfer)
    if form.is_valid():
        form.save()
        return redirect('/{}/'.format(surfer_id))
    return render(request, 'surferprofile/updateprofile.html', {'form': form})

create updateprofile.html

<!DOCTYPE html>
<html>
    <head>
        <title>Profile</title>
    </head>
    <body>
        <h1>Details</h1>      
        <form role="form" action="" method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Submit</button>
        </form>
    </body>
</html>

127.0.0.1:8080/1/update/

results matching ""

    No results matching ""