'How to test registration form in django?
I have a test to check if registration form works correctly but user doesn't create. I don't understand why. For example if in test I use assertEqual(Profile.objects.last().user, 'test1'), it is said that it's Nonetype object. If I check response's status code, it is 200. So I can be sure that page works. And finally If I go to this register page and create a user with the same information by myself it will be created successfully.
What is the problem and how can I solve it?
Model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
city = models.CharField(max_length=36, blank=True)
phone = models.IntegerField(blank=True)
verification = models.BooleanField(default=False)
quantity_posts = models.IntegerField(default=0)
def __str__(self):
return str(self.user)
def get_absolute_url(self):
return reverse('information', args=[str(self.pk)])
Form:
class RegisterForm(UserCreationForm):
city = forms.CharField(max_length=36, required=False, help_text='Город')
phone = forms.IntegerField(required=False, help_text='Сотовый номер')
class Meta:
model = User
fields = ('username', 'city', 'phone', 'password1', 'password2')
View:
def register_view(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
user = form.save()
city = form.cleaned_data.get('city')
phone = form.cleaned_data.get('phone')
Profile.objects.create(
user=user,
city=city,
phone=phone,
)
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/')
else:
form = RegisterForm()
return render(request, 'users/register.html', {'form': form})
part of main urls:
path('users/', include('app_users.urls'))
part of app urls:
path('register/', register_view, name='register')
test:
def test_if_can_register_profile(self):
self.client.post('/users/register/', {
'username': 'test1',
'city': 'pavlodar',
'phone': 87055551122,
'password': 'Mypassword777',
'password confirmation': 'Mypassword777'
})
self.assertTrue(Profile.objects.filter(user__username='test1').exists())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
