Django JsonResponse: User matching query does not exist - django

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),

Related

KeyError at /api/rooms/create-grade/ 'grade'

I don't understand this error one bit, I'm trying to do a basic create method but I get a KeyError what am i doing wrong
This is serializer.py code
class GradeCreateSerializer(serializers.ModelSerializer):
grade = serializers.ChoiceField(choices=GRADES, source="get_grade_display")
class Meta:
model = Grade
fields = ["grade"]
# ordering = ['-created_date']
def create(self, validated_data):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
try:
perms = Perm.objects.get(user=user)
except:
perms = None
if user.role in ['OWNER', 'PARTNER']:
school = user.owns.first()
elif perms is not None:
if user.role == 'STAFF' and perms.can_crt_grade_class:
school = user.works
instance = Grade.objects.create(
grade=validated_data['grade'],
school=school,
)
instance.save()
return instance
what am I doing wrong??
I have added the error traceback as requested
error traceback
Traceback (most recent call last):
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\views\generic\base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\mixins.py", line 19, in create
self.perform_create(serializer)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\mixins.py", line 24, in perform_create
serializer.save()
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "F:\Projects\SchoolProject\main\Classes\serializers.py", line 45, in create
grade=validated_data['grade'],
KeyError: 'grade'
it says that grade=validated_data['grade'], this the problem but i don't get it.
I have found a solution to my issue, it was because of grade = serializers.ChoiceField(choices=GRADES, source="get_grade_display") this means when using a ChoiceField to define your field you don't need to pass the source="" as the field uses the choice to determine it
So changing
grade = serializers.ChoiceField(choices=GRADES, source="get_grade_display")
to
grade = serializers.ChoiceField(choices=GRADES)
did the trick

I am trying to delete a user from the django database but there ir a IntegrityError at /admin/auth/user/ error occurs

I want to delete a user from the database that django comes with, i entered the admin site using my superuser but when i try to delete any user manually, which i created for testing purposes, it gives the error y mentioned above, the traceback inserted below is the one from the logs.
Error
Traceback (most recent call last):
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
sqlite3.IntegrityError: FOREIGN KEY constraint failed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 606, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/utils/decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 1727, in changelist_view
response = self.response_action(request, queryset=cl.get_queryset(request))
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 1397, in response_action
response = func(self, request, queryset)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/actions.py", line 40, in delete_selected
modeladmin.delete_queryset(request, queryset)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 1098, in delete_queryset
queryset.delete()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/models/query.py", line 711, in delete
deleted, _rows_count = collector.delete()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/models/deletion.py", line 318, in delete
sender=model, instance=obj, using=self.using
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/transaction.py", line 240, in __exit__
connection.commit()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 262, in commit
self._commit()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
[06/May/2020 02:47:33] "POST /admin/auth/user/ HTTP/1.1" 500 142907
These is my model
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserRegister(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
first_name = models.CharField(max_length=256, default='', blank=False,)
last_name = models.CharField(max_length=256, default='', blank=False)
email = models.EmailField(unique=True, blank=False,default='')
def __str__(self):
return self.user.username
This is my form
from django import forms
from .models import *
from django.contrib.auth.models import User
#Create your forms here!
class UserRegisterForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ('username','password')
class UserRegisterInfoForm(forms.ModelForm):
class Meta():
model = UserRegister
fields = ('first_name','last_name','email')
This is my view
def UserRegisterFormView(request):
registered = False
if request.method == 'POST':
userform = UserRegisterForm(data=request.POST)
userinfoform = UserRegisterInfoForm(data=request.POST)
if userform.is_valid() and userinfoform.is_valid():
user = userform.save()
user.set_password(user.password)
user.save()
profile = userinfoform.save(commit=False)
profile.user = user
profile.save()
registered = True
else:
print(userform.errors, userinfoform.errors)
else:
userform = UserRegisterForm
userinfoform = UserRegisterInfoForm
return render(request,'register/register.html'{'userform':userform,'userinfoform':userinfoform,'registered':registered})
You can delete the database except the init.py file. Then run makemigrations and migrate commands again.
If that dosen't fix it, then copy all the files in that folder into another folder, delete that folder, create a new one in your project directory, then pasted everything back in (be careful with your urls.py, don't forget to change them). Then run the makemigrations and migrate commands.

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 test case ValueError: The given username must be set

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.

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()