简体   繁体   中英

Django not REST - API user registration

I have my first project as junior in my work. It is old (Django 1.8) and it is normal django framework... not REST.

It supports web, and mobile.

I have to create endpoint for mobile to create user.

I think it is not a problem (to create) but I want to make sure it will be save.

First of all I thought that I will create normal ModelForm (RegisterAPIForm based on model=User with full validation (I mean init all fields that are in "backend" not visible for user | cleaned_data for all fields | special overwriten method save() that in addition hashes password, and send email) and in Views I'll add something like this:

class RegistrationAPITestView(View):
   def post(self, request):
       form = RegistrationAPIForm(
           request.POST
       )
       if form.is_valid():
           form.save()
           return JsonResponse({})
       else:
           #check errors and send error code back

Or I should do it other way, by using User object?

class RegistrationAPITestView(View):
       def post(self, request):
           #check if user does not exist
           #password1 and password2 validation
           user = User.objects.create()
           user.name = request.POST['username']
           user.set_password(request.POST['password'])
           #init all fields that user can't choose like groups etc
           user.save()

What do you think? Do I need ModelForm that I won't even render? It seems to be safer, but maybe I should check it other way? with User object?

Btw. Registration form already exists for web but there is a lot of "web" stuff that I don't need and I don't have to check and there is another method of saving password, so I believe I should create new one.

My code will be revieved in 2 weeks (senior vacations) but now I'm alone and want to do my best.

There is nothing wrong with the second option, but here is the problem that you as a junior should avoid. This line will make the server return a 500 error request.POST['username'] because python will throw a key error if the user doesn't provide the username, to fix just change to request.POST.get('username', 'value if doesn\\'t exit') also make sure that everything is ready before create the user or you will have records in the database that wont be useful. Call validators to the password too and try to cover all possible scenario. Remember never trust the user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM