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),
})
Related
When creating a view using FormView class and using get_context_data to display some data on the test html page alongside the form ,
Error is received when the form gets invalid , and context data is not retrieved
in get_context_data
context['username'] = data['username']
KeyError: 'username'
Key Error is thrown when the form invalidates
class TestView(LoginRequiredMixin,FormView):
form_class = TestForm
template_name = 'test.html'
def get_context_data(self, **kwargs):
context = super(CredentialsView, self).get_context_data(**kwargs)
if self.request.user.is_authenticated:
data = TestViewSet.as_view({'get': 'list'})(self.request).data
context['username'] = data['username']
context['firstname'] = data['firstname']
context['lastname'] = data['lastname']
return context
def form_valid(self, form):
password = form.cleaned_data['password']
if form.is_valid():
return self.query_api(password)
else:
return super(TestView, self).form_valid(form)
here is the traceback
Traceback (most recent call last): File
"/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py",
line 34, in inner response = get_response(request) File
"/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py",
line 115, in _get_response response =
self.process_exception_by_middleware(e, request) File
"/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py",
line 113, in _get_response response = wrapped_callback(request,
*callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py",
line 71, in view return self.dispatch(request, *args, **kwargs) File
"/usr/local/lib/python3.6/dist-packages/django/contrib/auth/mixins.py",
line 52, in dispatch return super().dispatch(request, *args,
**kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py",
line 97, in dispatch return handler(request, *args, **kwargs) File
"./ssh/views.py", line 91, in post return self.form_invalid(form,
**kwargs) File "./ssh/views.py", line 77, in form_invalid context = self.get_context_data(**kwargs) File "./ssh/views.py", line 97, in
get_context_data kwargs['username'] = data['username'] KeyError:
'username'
In the Scenario Above ,
How can we get the context data when the form is invalid ?
How can we send the form errors back to html page when the form is
invalid ?
get_context_data is called before your form_valid function.
On the loading of the page you try to fetch the value of data["username"] while it's still not completed.
Basically :
GET on your View
-> get_context_data is called --> The form isn't completed yet
You could get your args on a post function.
def post(self, request, *args, **kwargs):
form = TestForm(request.POST)
if form.is_valid():
# Do Stuff
else:
# Something else
return render(ThePageWithTheForm)
I'm trying to send a post request from PostMan into my Django view and I'm getting this error. "AttributeError: 'QueryDict' object has no attribute '_meta'"
From what I've gathered it has something to do with the form.save() as seen in traceba
I've searched all over to find a solution or even a better way to achieve an image post from a external web client to a Django server.
All help is very much appreciated.
Traceback
Capture.PNG
form is valid
Internal Server Error: /getimg/
Traceback (most recent call last):
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\decorators.py", line 50, in handler
return func(*args, **kwargs)
File "C:\Users\Gedit\Desktop\django\indivproj\getimg\api\views.py", line 21, in getimg
form.save()
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", line 207, in save
self.instance = self.update(self.instance, validated_data)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", line 979, in update
info = model_meta.get_field_info(instance)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\utils\model_meta.py", line 35, in get_field_info
opts = model._meta.concrete_model._meta
AttributeError: 'QueryDict' object has no attribute '_meta'
[24/Mar/2020 13:39:25] "POST /getimg/ HTTP/1.1" 500 20251
Views.py
#api_view(['POST',])
def getimg(request):
if request.method == 'POST':
form = ImageSerializer(request.POST, request.FILES)
logger.warning(request.FILES['img'])
if form.is_valid():
#raise_exception=True
logger.warning('form is valid')
form.save()
logger.warning()
response_dict = {'post': 'success'}
return HttpResponse(simplejson.dumps(response_dict), content_type='application/javascript')
else:
logger.warning(form.errors)
else:
form = ImageSerializer()
return render(request, 'getimg.html', {'form': form})
Serializers.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = '__all__'
Models.py
class Image(models.Model):
# name = models.CharField(default='name', max_length=30)
img = models.ImageField(upload_to='images/', max_length=1000)
Urls.py
app_name = 'getimg'
urlpatterns = [
# ex: /polls/
path('', views.getimg, name='getimg'),
path('gettext/', views.gettext, name='gettext'),
path('success', views.success, name = 'success'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Postman
so after looking around as a smart individual I realized i have not defined what save() function is... so now i do
The code that fixed the error but still not working
def save(self):
img = Image(
img =self.validated_data['img'],
)
Notification are already working in the view class. But not working in admin.py
I do send the puh notification after the save record in save_model. but not working here is my method
class EventAdmin(admin.ModelAdmin):
list_display = ('event_name', 'event_type', 'event_city', 'event_organizer', 'start_date',
'start_time', 'end_date', 'end_time', 'is_approved', 'is_active', 'created_at')
fields = ('main_image', 'event_name', 'event_organizer', 'event_type', 'event_city', 'event_tag', 'event_address', 'event_description',
'event_notes', 'start_date', 'start_time', 'end_date', 'end_time', 'age_max', 'age_min', 'event_lat', 'event_lng', 'website', 'is_approved', 'is_active', 'created_at')
def save_model(self, request, instance, form, change):
user = request.user
instance = form.save(commit=False)
if not change or not instance.created_by:
instance.created_by = user
# Here is notification class
notifiClass = Notifications()
notifiClass.sendNotifications(instance)
else:
instance.is_updated = True
instance.modified_by = user
instance.save()
form.save_m2m()
return instance
here is my Notification class in admin.py
class Notifications(object):
def sendNotifications(self, data):
users = models.NewEventNotification.objects.all().filter(is_notify=1)
serializer = NewEventNotificationSerializer(users, many=True)
tokens = []
for user in serializer.data:
tokens.append(user['user_token'])
if tokens:
push_service = FCMNotification(api_key=api_key)
message_title = "New Event"
message_body = data
result = push_service.notify_multiple_devices(
registration_ids=tokens, message_title=message_title, message_body=message_body)
print(result)
this shows the result in browser
TypeError at /admin/events/event/add/
Object of type Event is not JSON serializable
Request Method: POST
Request URL: http://192.168.0.104:8000/admin/events/event/add/
Django Version: 2.1.5
Exception Type: TypeError
Exception Value:
Object of type Event is not JSON serializable
Exception Location: C:\Python\Python37-32\lib\json\encoder.py in default, line 179
Python Executable: C:\Python\Python37-32\python.exe
Python Version: 3.7.4
Python Path:
['D:\\python\\emsbackend',
'C:\\Python\\Python37-32\\python37.zip',
'C:\\Python\\Python37-32\\DLLs',
'C:\\Python\\Python37-32\\lib',
'C:\\Python\\Python37-32',
'C:\\Users\\laptop '
'genration\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Python\\Python37-32\\lib\\site-packages',
'C:\\Python\\Python37-32\\lib\\site-packages\\pip-19.2.3-py3.7.egg']
Server time: Fri, 20 Dec 2019 18:32:51 +0500
and in console
Internal Server Error: /admin/events/event/add/
Traceback (most recent call last):
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 604, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1637, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1525, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1564, in _changeform_view
self.save_model(request, new_object, form, not add)
File "D:\python\emsbackend\events\admin.py", line 296, in save_model
notifiClass.sendNotifications(instance)
File "D:\python\emsbackend\events\admin.py", line 382, in sendNotifications
registration_id=tokens[0], message_title=message_title, message_body=message_body)
File "C:\Python\Python37-32\lib\site-packages\pyfcm\fcm.py", line 113, in notify_single_device
**extra_kwargs
File "C:\Python\Python37-32\lib\site-packages\pyfcm\baseapi.py", line 299, in parse_payload
return self.json_dumps(fcm_payload)
File "C:\Python\Python37-32\lib\site-packages\pyfcm\baseapi.py", line 120, in json_dumps
ensure_ascii=False
File "C:\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Python\Python37-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python\Python37-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python\Python37-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Event is not JSON serializable
after searching got this solution. on notification class
# Here is notification class
notifiClass = Notifications()
notifiClass.sendNotifications(instance)
change to this
# make serializer class of that event
serializer = eventSerializer(instance)
notifiClass = Notifications()
notifiClass.sendNotifications(serializer)
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.
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()