'How can I create a user in Django?
I am trying to create a user in my Django and React application (full-stack), but my views.py fails to save the form I give it. Can someone explain me the error or maybe give me other ways to create an user? Below there is the code:
# Form folder
def Registration(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
User.objects.create(
email = email ,
username = username,
password = password,
)
user = form.save()
login(request,user)
return redirect('/profile/')
else:
context = {"Error" : "Error during form loading"}
return render(request,'accounts/registration.html',context=context)
return render(request,'accounts/registration.html',context=context)
And that's my Forms.py
class UserForm(UserCreationForm):
username = forms.TextInput()
email = forms.EmailField()
password = forms.TextInput()
password2 = forms.TextInput()
class Meta:
model = User
fields = ("username", "email", "password", "password2")
def save(self, commit=True):
user = super(UserForm, self).save(commit=False)
if self.password != self.password2:
raise forms.ValidationError('Input unvalid')
elif commit:
user.save()
return user
Solution 1:[1]
In your module where you call User in the django server you want to call something like
user = User.objects.create_user(username, email, password)
if not user:
raise Exception("something went wrong with the DB!")
It may be helpful to read the django docs on User table, I've linked directly to the part describing the create_user() method.
The if block above is helpful to confirm things are working as intended.
If you want to use the UserCreationForm approach, then remove the call to User model. This is handled for you in the UserCreationForm once you save and commit.
So the form of the if branch will look like this:
if form.is_valid():
user = form.save()
login(request, user)
return redirect('/profile/')
Once you've got it working you will also want to write a unit test that confirms the user was created. You can confirm that by doing something like this:
class UserTests(TestCase):
def test_logout_deletes_token(self):
# some stuff here that creates a single user
self.assertEqual(User.objects.count(), 1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
