please help to write the test.
views.py:
def ajax_username_check(request):
"""
ajax check username for registration form
return true - no matched
return false - matched
"""
result = True
if request.method == 'POST' and request.is_ajax():
username = request.POST.get('username', '')
try:
check_username_match = User.objects.get(username=username)
except:
pass
else:
result = False
data = {
'result': result,
}
return HttpResponse(json.dumps(data), content_type='application/json')
tests.py:
class TestAjaxCheckUsername(TestCase):
def setUp(self):
self.client = Client()
self.record = User.objects.create(
user_id=2,
username='qqqqqq',
password='pbkdf2_sha256$12000$Bm1GmmeGtnyU$v4E1UUcXWjk7pmQEkIWXvY2Hsw2ycG783R/bVpoVEWk=',
is_active=1,
is_staff=0,
is_superuser=0,
email='asasas@mail.ru'
)
def test_diary(self):
json_string = json.dumps({'username':'qqqqqq'})
self.response = self.client.post('/ajax_username_check/', json_string, "text/json", HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertContains(self.response, true)
error message:
ERROR: test_diary (app_accounts.tests.TestAjaxCheckUsername)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/kalinins/.virtualenvs/kinopom_project/kinopom/app_accounts/tests.py", line 17, in setUp
email='asasas@mail.ru'
File "/home/kalinins/.virtualenvs/kinopom_project/kinopom_env/local/lib/python2.7/site-packages/django/db/models/manager.py", line 157, in create
return self.get_queryset().create(**kwargs)
File "/home/kalinins/.virtualenvs/kinopom_project/kinopom_env/local/lib/python2.7/site-packages/django/db/models/query.py", line 320, in create
obj = self.model(**kwargs)
File "/home/kalinins/.virtualenvs/kinopom_project/kinopom_env/local/lib/python2.7/site-packages/django/db/models/base.py", line 417, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'user_id' is an invalid keyword argument for this function
I am trying to verify the existence of a user named qqqqqq using Ajax-request. I need to check the return value for the function ajax_username_check()
I have read this post and tried to use it, but to no avail
User has no field user_id
, it has a field id
. However, I wouldn't set that either, as the ID may already exist and usually Django chooses the model ids. So I would just remove the user_id=2
line.
Two other comments: first, never use a bare except:
like that, use except User.DoesNotExist:
explicitly, otherwise you might accidentally catch who knows what exception.
Second, I wouldn't use get()
here at all: what you're looking for is whether the User exists
or not. So:
result = {'result': User.objects.filter(username=username).exists()}
should do.