Reputation: 423
I am watching a django tutorial and in it this code is used:
class UserFormView(View):
form_class=UserForm
def post(self:request):
form=self.form_class(request.POST)
if form.is_valid():
user=form.save()
username=form.cleaned_data('username')
password=form.cleaned_data('password')
user.set_password(password)
user.save()
In the tutorial it is said that the form.save() command stores the field data to the shell, which i find incredibly misleading. Shouldn't the save command save the data to a user object in the database? Next they use set_password to save the password value, what does set_password
do? Does it hash the password input?
Finally the user details are persisted to the database by calling save()
on user. But how does django know which model user belongs too? Is that information also acquired when you call form.save() and assign the result to user
?
Thank you
Upvotes: 0
Views: 2117
Reputation: 77912
I don't know where this "tutorial" comes from but it's about as bad and wrong as it could be.
Assuming UserForm
is a (correctly written) ModelForm
(you didn't post the form's definition), form.save()
should already take care of doing the right thing (creating the record in the database, with the password already encrypted, and returning the newly created User
instance).
My advice: forget about this s...y tutorial, do the official one instead, and use the official doc for more details.
Upvotes: 2
Reputation: 743
FIY, you've got indentation problem in your code (or it's just as formatting). form.save()
purpose is to save related model to database, you are right.
You're also right about set_password
, for more info just read the docs.
Django knows about model and all it's data, due to instance it's holding (in your case user
). This data is available from that instance - see the docs.
Hope it helps.
Upvotes: 0