Django test case ValueError: The given username must be set - django

I am testing a Django application, for its user sign-up feature, whether the posted data is correct and post request executes successfully.
In views.py, the Class CustomerSignUpView
class CustomerSignUpView(View):
def post(self, request):
name_r = request.POST.get('customer_username')
password_r = request.POST.get('customer_password')
email_r = request.POST.get('customer_email')
contact_number_r = request.POST.get('customer_contact_number')
profile_picture_r = request.POST.get('customer_profile_picture')
if checkemail(email_r):
# receiving an error here in TEST CASE not in actual program execution
c = User(username=name_r, password=password_r, email=email_r)
c.save()
p = Profile(user=c, phone_number=contact_number_r, profile_picture=profile_picture_r)
p.save()
return render(request, 'catalog/customer_login.html')
else:
return render(request, 'catalog/customer_signup.html')
def get(self, request):
return render(request, 'catalog/customer_signup.html')
This is the test case for user account creation:
class CustomerSignUpViewTest(TestCase):
"""
Test case for User Sign in
"""
def test_registration_view_post_success(self):
"""
A ``POST`` to the ``customer_signup`` view with valid data properly
creates a new user and issues a redirect.
"""
data = {
'username': 'testuser1',
'password': '1X<ISRUkw+tuK',
'email': 'foobar#test.com',
'phone_number': '9876543210',
}
response = self.client.post(reverse('customer_signup'), data, follow=True)
self.assertEqual(response.status_code, 200)
self.assertTrue(response.url.startswith('/catalog/customer_login/'))
The test encounters the following error: ValueError('The given username must be set')
Error
Traceback (most recent call last):
File "/Users/sndtcsi/PycharmProjects/Library/catalog/tests.py", line 54, in test_registration_view_post_success
response = self.client.post(reverse('customer_signup'), data, follow=True)
File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/test/client.py", line 535, in post
response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/test/client.py", line 349, in post
secure=secure, **extra)
File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/test/client.py", line 414, in generic
return self.request(**r)
File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/test/client.py", line 495, in request
raise exc_value
File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/Users/sndtcsi/PycharmProjects/Library/catalog/views.py", line 107, in post
c = User.objects.create_user(username=name_r, password=password_r, email=email_r)
File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 150, in create_user
return self._create_user(username, email, password, **extra_fields)
File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 139, in _create_user
raise ValueError('The given username must be set')
While my sign-up feature works perfectly, the test execution shows that the username is not set. I do not understand why that is happening.

You are using bad key in your TestCase. You are trying to get customer_username in the form in your view, but you are actually posting username key in the data in your TestCase. To make this work you should make this lines to use the same keys:
name_r = request.POST['customer_username']
and
'username': 'testuser1',
The same problems are with all another forms in this your code.

Related

Django AttributeError: 'tuple' object has no attribute 'splitlines'

I'm trying to create an user registration with email confirmation and came up with this code in the models.py
class UserRegister(SuccessMessageMixin, FormView):
template_name = 'login/form_register.html'
form_class = UserRegisterForm
redirect_authenticated_user = True
success_url = reverse_lazy('tasks')
success_message = "User has been created, please login"
def form_valid(self, form):
user = form.save(commit=False)
user.is_active = False # Deactivate account till it is confirmed
user.save()
current_site = get_current_site(self.request)
subject = 'Activate Your Account'
message = render_to_string('login/account_activation_email.html'), {
'user':user,
'domain':current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
'token':account_activation_token.make_token(user),
}
user.email_user(subject, message)
messages.add_message(
self.request,
messages.SUCCESS,
'Check Your Email For Account Activation Link'
)
if user is not None:
login(self.request, user)
return super(UserRegister, self).form_valid(form)
def get(self, *args, **kwargs):
if self.request.user.is_authenticated:
return redirect('tasks')
return super(UserRegister, self).get(*args, **kwargs)
But I keep getting this error AttributeError: 'tuple' object has no attribute 'splitlines'
This is the traceback
Internal Server Error: /register/
Traceback (most recent call last):
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/views/generic/base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/views/generic/base.py", line 142, in dispatch
return handler(request, *args, **kwargs)
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/views/generic/edit.py", line 153, in post
return self.form_valid(form)
File "/home/ihzacordova/projects/todo-list/login/models.py", line 52, in form_valid
user.email_user(subject, message)
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/contrib/auth/models.py", line 402, in email_user
send_mail(subject, message, from_email, [self.email], **kwargs)
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/mail/__init__.py", line 87, in send_mail
return mail.send()
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/mail/message.py", line 298, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 131, in send_messages
sent = self._send(message)
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 147, in _send
message = email_message.message()
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/mail/message.py", line 260, in message
msg = SafeMIMEText(self.body, self.content_subtype, encoding)
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/mail/message.py", line 160, in __init__
MIMEText.__init__(self, _text, _subtype=_subtype, _charset=_charset)
File "/usr/lib/python3.8/email/mime/text.py", line 42, in __init__
self.set_payload(_text, _charset)
File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/mail/message.py", line 170, in set_payload
for line in payload.splitlines()
AttributeError: 'tuple' object has no attribute 'splitlines'
Change
message = render_to_string('login/account_activation_email.html'), {
'user':user,
'domain':current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
'token':account_activation_token.make_token(user),
}
To
message = render_to_string('login/account_activation_email.html', {
'user':user,
'domain':current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
'token':account_activation_token.make_token(user),
})

Django JsonResponse: User matching query does not exist

So I´ve tried to make an ajax for my models but it is giving me a matching query does not exist, here is the full error:
Internal Server Error: /messages/notification/
Traceback (most recent call last):
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\detail.py", line 106, in get
self.object = self.get_object()
File "C:\Users\berna\Desktop\Python & Javascript\Web development\MiFamiliaEsUnDesastre\mifamiliaesundesastre\chat\views.py", line 26, in get_object
obj, created = Thread.objects.get_or_new(self.request.user, other_username)
File "C:\Users\berna\Desktop\Python & Javascript\Web development\MiFamiliaEsUnDesastre\mifamiliaesundesastre\chat\models.py", line 29, in get_or_new
user2 = Klass.objects.get(username=other_username)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 415, in get
raise self.model.DoesNotExist(
django.contrib.auth.models.User.DoesNotExist: User matching query does not exist.
HTTP GET /messages/notification/ 500 [0.16, 127.0.0.1:56012]
Also here is my code:
models.py
class ProfileImage(models.Model):
"""
Profile model
"""
user = models.OneToOneField(
verbose_name=_('User'),
#to=settings.AUTH_USER_MODEL,
to = User,
related_name='profile',
on_delete=models.CASCADE
)
avatar = models.ImageField(upload_to='profile_image')
notifications = models.FloatField(default='0')
views.py
def notifications(request, user_id, *args, **kwargs):
user = User.objects.get(pk=user_id)
user.profile.notifications = user.profile.notifications + 1
user.save()
return JsonResponse(data=user.profile.notifications, safe=False)
urls.py
path('messages/notification/', notifications)
my html for the ajax call
// Add the notification val
$.get('notification/')
someone tell me that is that I dont have users, but when I do have a user, I dont know what is going on
You need to send user_id to the view:
path('messages/notification/(?P<user_id>[a-zA-Z0-9/_\.-]*)', notifications)
and:
$.get('messages/notification/{{ user.pk }}')
Update
You have to know their user id to get their notifications:
$.get('messages/notification/12234')
I assume you have a User model somewhere?
Also, user_id is coming in as a string, so need to int() that:
user = User.objects.get(pk=int(user_id))
Or use:
path('messages/notification/<int:user_id>', notifications)
So for does who saw this later, what I did is to change the
path('messages/notification/', notifications)
To
url(r'^ajax/notification/$', notification),

Model turns into tuple in django's view. Whata hell?

I am trying to save a string (session hash) into django's model, but something is going wrong..
When I try to update the string, the model turns into a tuple causing AttributeError.
At the beginning everything was in a one 'post' function in view and yet not working. I tried to devide that stuff into functions, but it still does not help. Before the assignment type(session) says that 'session' is a model, not tuple.
View function code:
def post(self, request, *args, **kwargs):
data = json.loads(request.body.decode('utf-8'))
form = self.form_class(data)
if form.is_valid():
phone = form.cleaned_data.get('phone')
code = form.cleaned_data.get('code')
password = form.cleaned_data.get('password')
session = Session.objects.get_or_create(phone=phone, user=request.user.telegramuser)
if code and password:
return utils.sign_in(session, phone, code, password)
elif code:
return utils.sign_in(session, phone, code)
elif phone:
return utils.send_code_request(session, phone)
return JsonResponse({'state': 'none'})
utils.send_code_request and sign_in have the same structure
def send_code_request(session, phone):
result = asyncio.run(_send_code_request(phone))
# result - {
# 'state': 'ok',
# 'session': 'Hfkdi...AaF24s'
# }
if result['state'] == 'ok':
session.update_session(result.pop('session'))
return JsonResponse(result)
Manager
class DefaultManager(models.Manager):
def get_or_create(self, *args, **kwargs):
try:
return self.get(*args, **kwargs)
except ObjectDoesNotExist:
return self.create(*args, **kwargs)
Error:
Internal Server Error: /sessions/add/
Traceback (most recent call last):
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\sendall\views.py", line 78, in post
return utils.send_code_request(session, phone)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\sendall\utils.py", line 46, in send_code_request
session.update_session(result.pop('session'))
AttributeError: 'tuple' object has no attribute 'update_session'
[23/Jul/2019 23:51:35] "POST /sessions/add/ HTTP/1.1" 500 86600
get_or_create does indeed return a tuple, of the object and a created flag. Either capture both:
session, created = Session.objects.get_or_create(phone=phone...)
Or, use create instead.
Or even better, use the form save method:
session = form.save()

django-rest-auth: register an active user for my tests

I'm trying to write some tests with django-rest-auth and the following code:
def create_user(username='john', email='johndoe#test.com', password='doe'):
user = get_user_model().objects.create(
username=username,
email=email,
is_active=False)
if password:
user.set_password(password)
else:
user.set_unusable_password()
user.save()
return user
def test_jwt_auth():
username = 'user'
email = 'user#foo.com'
password = 'pass'
create_user(username=username, email=email, password=password)
resp = client.post(REST_LOGIN_URL, {'email': email, 'password': password})
assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
The client.post work fine as long as I don't change/create the user with is_active=True. When I do I get the following error:
Error
Traceback (most recent call last):
File "C:\Users\Ekami\Documents\workspace\NomadSpeed-Web\users\tests.py", line 64, in test_jwt_auth
resp = self.client.post(REST_LOGIN_URL, {'email': email, 'password': password})
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\test.py", line 300, in post
path, data=data, format=format, content_type=content_type, **extra)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\test.py", line 213, in post
return self.generic('POST', path, data, content_type, **extra)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\test.py", line 238, in generic
method, path, data, content_type, secure, **extra)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\test\client.py", line 422, in generic
return self.request(**r)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\test.py", line 289, in request
return super(APIClient, self).request(**kwargs)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\test.py", line 241, in request
request = super(APIRequestFactory, self).request(**kwargs)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\test\client.py", line 503, in request
raise exc_value
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\views\decorators\debug.py", line 76, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_auth\views.py", line 49, in dispatch
return super(LoginView, self).dispatch(*args, **kwargs)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_auth\views.py", line 103, in post
self.serializer.is_valid(raise_exception=True)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\serializers.py", line 236, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\serializers.py", line 437, in run_validation
value = self.validate(value)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_auth\serializers.py", line 108, in validate
email_address = user.emailaddress_set.get(email=user.email)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\db\models\query.py", line 408, in get
self.model._meta.object_name
allauth.account.models.EmailAddress.DoesNotExist: EmailAddress matching query does not exist.
I have no idea how to bypass this error. I need my user to be active with a validated email to continue my test. Any idea? Thank you.
create_user is looking to me as a BaseUserManager so perhaps you should be change it to look like this
def create_user(self, username=None, email=None, password=None):
if not username:
raise ValueError('Users must have an Username')
if not email:
raise ValueError('Users must have an email address')
try:
user = self.get(email=self.normalize_email(email))
except self.model.DoesNotExist:
user = self.model(username=username, email=self.normalize_email(email))
password_validation.validate_password(password)
user.set_password(password)
return user
now you can pass user params and test.

AttributeError: 'dict' object has no attribute 'user' during overriding "social-app-auth-django" create_user

I noticed that the SAAD fails to associate an existing user with the social-auth logged in user. This is creating multiple users with the same email address. I tried to override this by commenting out in settings.py,
# 'social_core.pipeline.user.create_user',
I then made a view to create a user profile. I added this the pipeline,
SOCIAL_AUTH_PIPELINE = (
...
'accounts.views.save_profile',
...
)
In accounts.views,
def save_profile(backend, user, response, *args, **kwargs):
username = ""
if backend.name == "google-oauth2":
email = response["emails"][0]["value"]
existing_user = User.objects.get(email=email)
username = existing_user.username
password = existing_user.password
authenticated_user = authenticate(username=username, password=password)
login(request,authenticated_user) # I need request to login the user
The problem here is that I need request to log in the user. The login requires request and authenticated user as parameters. Suppose I add request as a parameter, I get an AttributeError: 'dict' object has no attribute 'user'.
def save_profile(request, backend, user, response, *args, **kwargs):
username = ""
if backend.name == "google-oauth2":
email = response["emails"][0]["value"]
existing_user = User.objects.get(email=email)
username = existing_user.username
password = existing_user.password
authenticated_user = authenticate(username=username, password=password)
login(request,authenticated_user)
How do I login the user, having known username and password ?
Traceback of the error :
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/social_django/utils.py", line 50, in wrapper
return func(request, backend, *args, **kwargs)
File "/Library/Python/2.7/site-packages/social_django/views.py", line 28, in complete
redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
File "/Library/Python/2.7/site-packages/social_core/actions.py", line 41, in do_complete
user = backend.complete(user=user, *args, **kwargs)
File "/Library/Python/2.7/site-packages/social_core/backends/base.py", line 39, in complete
return self.auth_complete(*args, **kwargs)
File "/Library/Python/2.7/site-packages/social_core/utils.py", line 253, in wrapper
return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/social_core/backends/oauth.py", line 398, in auth_complete
*args, **kwargs)
File "/Library/Python/2.7/site-packages/social_core/utils.py", line 253, in wrapper
return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/social_core/backends/oauth.py", line 409, in do_auth
return self.strategy.authenticate(*args, **kwargs)
File "/Library/Python/2.7/site-packages/social_django/strategy.py", line 115, in authenticate
return authenticate(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/auth/__init__.py", line 74, in authenticate
user = backend.authenticate(**credentials)
File "/Library/Python/2.7/site-packages/social_core/backends/base.py", line 79, in authenticate
return self.pipeline(pipeline, *args, **kwargs)
File "/Library/Python/2.7/site-packages/social_core/backends/base.py", line 82, in pipeline
out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs)
File "/Library/Python/2.7/site-packages/social_core/backends/base.py", line 107, in run_pipeline
result = func(*args, **out) or {}
File "/Users/swaggerjeevan07/Desktop/django/mysite/accounts/views.py", line 76, in save_profile
login(request,authenticated_user)
File "/Library/Python/2.7/site-packages/django/contrib/auth/__init__.py", line 97, in login
user = request.user # This is the issue
AttributeError: 'dict' object has no attribute 'user'
All I did was add social_core.pipeline.social_auth.associate_by_emailto the pipeline above create_user. Now, it checks if there is an account already linked with the obtained social-auth email. If it does't, it creates a new user.
SOCIAL_AUTH_PIPELINE = (
...
'social_core.pipeline.social_auth.associate_by_email',
'social_core.pipeline.user.create_user',
'accounts.views.save_profile',
'social_core.pipeline.social_auth.associate_user',
...
)
The def save_profile looks like :
def save_profile(backend, user, response, *args, **kwargs):
if backend.name == "google-oauth2":
# A dot in username will have url issues
username = user.username.replace(".","_")
user.username = username
user.first_name = user.first_name.capitalize()
user.last_name = user.last_name.capitalize()