Skip to content
This repository has been archived by the owner on Sep 17, 2023. It is now read-only.

10 Forms

scotwk edited this page May 10, 2015 · 1 revision

Make a form

Currently note objects can only be created in the admin. Make a new form in note/forms.py

from django import forms

from .models import Note

class NoteForm(forms.ModelForm):

    class Meta:
        model = Note
        exclude = ['owner', 'pub_date']

The owner and pub_date fields are excluded from our form because we will auto-populate them in the view. (We don't want to allow the user to choose who owns the note!)

Make a view that uses the form

Modify note/views.py:

from django.views.generic import ListView, DetailView, CreateView
from django.utils import timezone
from django.core.urlresolvers import reverse_lazy

from .forms import NoteForm
...

class NoteCreate(LoginRequiredMixin, CreateView):
    form_class = NoteForm
    template_name = 'note/form.html'
    success_url = reverse_lazy('note:index')

    def form_valid(self, form):
        form.instance.owner = self.request.user
        form.instance.pub_date = timezone.now()
        return super(NoteCreate, self).form_valid(form)

Update URLs to include your view

Add a new URL. Don't forget to import NoteCreate first.

url(r'^new/$', NoteCreate.as_view(), name='create'),

Try accessing your new view by typing the URL in the address bar. Looks like it still needs a template.

Update templates

Here is a template for the form. Can you figure out where to put it? (Hint: look at your view definition) https://github.com/sixfeetup/ElevenNote/raw/10-create-note/elevennote/note/templates/note/form.html

Also add this line in to your index template to make a link to the new form page:

<a href="{% url 'note:create' %}">Create a new note</a>