I'm new to Django. I 'm trying to practice create Raw Update Class Based View but it get in to error Method Not Allowed (POST). Can any one help me please.
I already follow the instruction step by step but the result is the same. I also try a lot of method to fix but still can't. I really want to know what is the problem. I very appreciate for someone help me fix this.
view.py
from django.shortcuts import render, get_object_or_404
from django.views import View
from .models import Client
from .forms import ClientFrom
class ClientUpdateView(View):
template_name = "clients/client-update.html"
def get_object(self):
id = self.kwargs.get('id')
obj = None
if id is not None:
obj = get_object_or_404(Client, 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 = ClientFrom(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 = ClientFrom(request.POST, instance=obj)
if form.is_valid():
form.save()
context['object'] = obj
context['form'] = form
return render(request, self.template_name, context)
forms.py
from django import forms
from .models import Client
class ClientFrom(forms.ModelForm):
class Meta:
model = Client
fields = [
'Name',
'Address',
'Contact',
]
form in client-update.html
{% extends 'clienthead.html' %}
{% block content %}
<h1>Update: {{object.id}} - {{ object.Name }}</h1>
<form action='.' method='POST'> {% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Save' />
</form>
{% endblock %}
urls.py
from django.urls import path
from .views import (
ClientUpdateView,
)
app_name = 'client'
urlpatterns = [
path('<int:id>/adjust', ClientUpdateView.as_view(), name='client-adjust'),
]