0

I am trying to write a a Function-based View (FBV) as a Class-based View (CBV), specifically a CreateView. So far I have been able to write the FBV as a generic View but not as a CreateView. How would I go about doing this?

FBV

def register(request):
    registered = False
    if request.method == 'POST':
        user_form = UserCreationForm(data=request.POST)
        if user_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            registered = True
        else:
            print(user_form.errors)
    else:
        user_form = UserCreationForm()
    return render(request,'accounts/registration.html', {'user_form':user_form, 'registered':registered})

Converted View

class RegisterView(View):

    def get(self, request):
        registered = False
        user_form = UserCreationForm()
        return render(request,'accounts/registration.html', {'user_form':user_form, 'registered':registered})

    def post(self, request):
        registered = False
        user_form = UserCreationForm(data=request.POST)
        if user_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            registered = True
        else:
            print(user_form.errors)
        return render(request,'accounts/registration.html', {'user_form':user_form, 'registered':registered})

1 Answer 1

2

You may follow it

class RegisterView(CreateView):
    model = User
    form_class = UserCreationForm
    template_name = 'accounts/registration.html'

    def post(self, request, *args, **kwargs):
        registered = False
        user_form = UserCreationForm(data=request.POST)
        if user_form.is_valid():
            user = user_form.save(commit=False)
            user.set_password(user.password)
            user.save()
            registered = True
        else:
            print(user_form.errors)
        return render(request,'accounts/registration.html', {'user_form':user_form, 'registered':registered})
Sign up to request clarification or add additional context in comments.

Comments

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.