I've only started using the Django REST framework recently. I want to create a user. Before (without Django REST framework) I used to create users with the following logic (using the User model in django.contrib.auth.models):
Step 1) create a User registration form (which -1- validates that when a user initially types in his password when registering, password1 and 'confirm password' / password2 matches and -2- validates that the username only consists of letters, numbers underscores and -3- validates that the username is not already registered / taken):
class RegistrationForm(forms.Form):
username = forms.CharField(label='Username', max_length=30)
email = forms.EmailField(label='Email')
password1 = forms.CharField(label='Password', widget=forms.PasswordInput())
password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput())
def clean_password2(self):
if 'password1' in self.cleaned_data:
password1 = self.cleaned_data['password1']
password2 = self.cleaned_data['password2']
if password1 == password2:
return password2
raise forms.ValidationError('Passwords do not match.')
def clean_username(self):
username = self.cleaned_data['username']
if not re.search(r'^\w+$', username): #checks if all the characters in username are in the regex. If they aren't, it returns None
raise forms.ValidationError('Username can only contain alphanumeric characters and the underscore.')
try:
User.objects.get(username=username) #this raises an ObjectDoesNotExist exception if it doesn't find a user with that username
except ObjectDoesNotExist:
return username #if username doesn't exist, this is good. We can create the username
raise forms.ValidationError('Username is already taken.')
Step 2) create a View which handles this form when it is submitted:
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
From my understanding, the Django REST framework comes into play only when I'm returning a user object. So suppose I want to return a User as a JSON object, I'd use the Django REST framework like so: my serializers.py file:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', )
and my view which deals with returning user objects:
if request.method == 'GET':
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
Is this the correct way of doing it? Because this SO post: Django Rest Framework User Registrations with extra fields seems to be creating users a different way:
serialized = UserSerializer(data=request.DATA)
if serialized.is_valid():
user = User.objects.create_user(
email = serialized.init_data['email'],
and this post: django rest framework user registration also creates users a different way than what I have above.