Reputation: 930
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})
Upvotes: 0
Views: 390
Reputation: 3104
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})
Upvotes: 2