0

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.

Community
  • 1
  • 1
SilentDev
  • 20,997
  • 28
  • 111
  • 214

1 Answers1

1

So what you have built and what you have linked appear to be solving different problems. What you are doing is serializing the user data for the API. So I can see the users username if I use your api. But what your linking to is allowing people to create new users with their API's. So which do you want to do?

The best way of putting it is your doing a "GET" request, and they are using a "POST" request.

Zoe Steinkamp
  • 149
  • 3
  • 13
  • I want to be able to create a new user (using POST) But when I serialize a user object, I want to only return the username and not the password. – SilentDev May 06 '15 at 02:30
  • 1
    Okay, then what you have currently will work for when you want to return the data, but you will need to follow the other users answers in order to the first part of your problem. So leave the code you have right now, thats fine, just add the new code from those links so when people do a POST request they can create a new user. If you have any questions/problems message me :) – Zoe Steinkamp May 06 '15 at 06:15
  • the issue is, the other user's UserSerialzer ( http://stackoverflow.com/questions/27078272/django-rest-framework-user-registrations-with-extra-fields ) has "fields = ('password', 'username', 'first_name', 'last_name', 'email', 'token', 'phone_number')". So when creating a new user, he can do "serialized = UserSerializer(data=request.DATA)" because inside data is the username, password etc. and his UserSerializer has those fields. My UserSerializer only has the "username" field because I don't want to return a password (or anything else other than the username) when serializing. – SilentDev May 06 '15 at 17:07