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.


# some branches removed for clarity
├── mysite
│   ├──
│   ├──
└── surferprofile
    ├── #<=== inside app
    ├── templates
    │   └── surferprofile
    │       ├── diary.html

Add to
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', 

This url calls the updateprofile method (created next).

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

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

The updateprofile method uses surfer_id grabbed in 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():
        return redirect('/{}/'.format(surfer_id))
    return render(request, 'surferprofile/updateprofile.html', {'form': form})

create updateprofile.html

<!DOCTYPE html>
        <form role="form" action="" method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Submit</button>

results matching ""

    No results matching ""