0

I'm doing a django app and at first I've done methods to my view, but I'd like now to change to class.

Here's an exemple of how I tried :

def register(response):
if response.method == "POST":
    form = RegisterForm(response.POST)
    if form.is_valid():
        form.save()
        return redirect("/login")
else:
    form = RegisterForm()

return render(response, "register/register.html", {"form":form})

And tried to change like this :

class RegisterView(generic.View):
    def post(self, request):
        form = RegisterForm(response.POST)
        if form.is_valid():
            form.save()
            return redirect("/login")
        else:
            form = RegisterForm()
        return render(response, "register/register.html", {"form":form})

But I keep getting a 405 Error Method not allowed, I guess it's because I'm not doing right the changing from method to class. Any idea ?

3
  • 2
    You need to define a get method. The same way you have a post method Commented Apr 13, 2020 at 13:47
  • and what does that method returns ? Commented Apr 13, 2020 at 13:49
  • @David check my answer Commented Apr 13, 2020 at 13:50

1 Answer 1

2

You need to define the get method as well. Below is the code that must do the job

class RegisterView(generic.View):
    def post(self, request):
        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("/login")
        else:
            form = RegisterForm()
        return render(request, "register/register.html", {"form":form})

    def get(self, request):
        form = RegisterForm()
        return render(request, "register/register.html", {"form":form})
Sign up to request clarification or add additional context in comments.

3 Comments

thank you sir it's working, only had to change response to request !
my bad! i made the change from response to request. You can accept the answer if it worked
no problem, will accept in 5 minutes I have to wait since I created a few minutes ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.