UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 15 - Forms for Data

LEARN

Django for Beginners

Admin Views

Using Forms

Cross-Site Request Forgery

templates/book_new.html

<form action="" method="book">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form>

book/views.py

class BookCreateView(CreateView):
    model = Book
    template_name = 'book_new.html'
    fields = ['title', 'author']

BUILD

Book Builder Demo

Create Week6 code

Settings Design Pattern

config/settings.py

# Variables to adjust

TEMPLATES
STATIC_URL
STATICFILES_DIRS
STATIC_ROOT
ALLOWED_HOSTS
INSTALLED_APPS

Data Model Design Pattern

book/models.py

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    body = models.TextField()

    def __str__(self):
        return f'{self.pk} - {self.title} by {self.author}'

    def get_absolute_url(self):
        return reverse('book_detail', args=[str(self.id)])

CRUD Design Pattern

Data Views Design Pattern

Data Views URLs Design Pattern

config/urls.py

urlpatterns = [
    # Book

]

Data Views Templates Design Pattern

templates/book_list.html

{% for book in object_list %} <h3><a href="{% url 'book_detail' book.pk %}">{{ book.title }}</a></h3> <p>by {{ book.author }}</p> {% endfor %}

templates/book_detail.html

```

{{ book.title }}

{{ book.author }}

<a href="{% url 'book_edit' book.pk %}">Edit Book Book</a>
<a href="{% url 'book_delete' book.pk %}">Delete Book Book</a>

```

templates/book_new.html

```

<form action="" method="book">{% csrf_token %}
   {{ form.as_p }}
   <input type="submit" value="Save">
</form>

```

templates/book_edit.html

<form action="" method="book">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"> </form>

templates/book_delete.html

<h1>Delete Book</h1> <form action="" method="post">{% csrf_token %} <p>Are you sure you want to delete "{{ book.title }}"?</p> <input type="submit" value="Confirm"> </form>

Data Views Design Pattern

book/views.py

class BookView(RedirectView):
    url = '/book/'

class BookListView(ListView):
    template_name = 'book_list.html'
    model = Book

class BookDetailView(DetailView):
    template_name = 'book_detail.html'
    model = Book

class BookCreateView(LoginRequiredMixin, CreateView):
    template_name = "book_edit.html"
    model = Book
    fields = ['title', 'author']

class BookUpdateView(LoginRequiredMixin, UpdateView):
    template_name = "book_edit.html"
    model = Book
    fields = ['title', 'author']

class BookDeleteView(LoginRequiredMixin, DeleteView):
    model = Book
    template_name = 'book_delete.html'
    success_url = reverse_lazy('book_list')