Skip to content

Commit

Permalink
45 - Raw Update Class Based View
Browse files Browse the repository at this point in the history
  • Loading branch information
codingforentrepreneurs committed Aug 8, 2018
1 parent e3b487e commit 2137f65
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
14 changes: 14 additions & 0 deletions src/courses/templates/courses/course_update.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{% extends 'base.html' %}

{% block content %}
<h1>Update: {{object.id }} - {{ object.title }}</h1>

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




{% endblock %}
5 changes: 3 additions & 2 deletions src/courses/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
from .views import (
CourseView,
CourseListView,
CourseCreateView
CourseCreateView,
CourseUpdateView
# my_fbv
)

Expand All @@ -14,6 +15,6 @@

path('create/', CourseCreateView.as_view(), name='courses-create'),
path('<int:id>/', CourseView.as_view(), name='courses-detail'),
# path('<int:id>/update/', <update_view>, name='courses-update'),
path('<int:id>/update/', CourseUpdateView.as_view(), name='courses-update'),
# path('<int:id>/delete/', <delete_view>, name='courses-delete'),
]
33 changes: 33 additions & 0 deletions src/courses/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,39 @@
from .models import Course
# BASE VIEW CLass = VIEW


class CourseUpdateView(View):
template_name = "courses/course_update.html" # DetailView
def get_object(self):
id = self.kwargs.get('id')
obj = None
if id is not None:
obj = get_object_or_404(Course, id=id)
return obj

def get(self, request, id=None, *args, **kwargs):
# GET method
context = {}
obj = self.get_object()
if obj is not None:
form = CourseModelForm(instance=obj)
context['object'] = obj
context['form'] = form
return render(request, self.template_name, context)

def post(self, request, id=None, *args, **kwargs):
# POST method
context = {}
obj = self.get_object()
if obj is not None:
form = CourseModelForm(request.POST, instance=obj)
if form.is_valid():
form.save()
context['object'] = obj
context['form'] = form
return render(request, self.template_name, context)


class CourseCreateView(View):
template_name = "courses/course_create.html" # DetailView
def get(self, request, *args, **kwargs):
Expand Down

0 comments on commit 2137f65

Please sign in to comment.