Django. Python social auth. create profiles at the end of pipeline

2024/11/14 13:17:34

I want to add a function at the end of the auth pipeline, the function is meant to check if there is a "Profiles" table for that user, if there isn't it will create a table. The Profiles model is a table where I store some extra information about the user:

class Profiles(models.Model):user = models.OneToOneField(User, unique=True, null=True)description = models.CharField(max_length=250, blank=True, null=True)points = models.SmallIntegerField(default=0)posts_number = models.SmallIntegerField(default=0)

Each user must have a Profiles table. So, I added a function at the end of the pipeline:

SOCIAL_AUTH_PIPELINE = ('social.pipeline.social_auth.social_details','social.pipeline.social_auth.social_uid','social.pipeline.social_auth.auth_allowed','social.pipeline.social_auth.social_user','social.pipeline.user.get_username','social.pipeline.user.create_user','social.pipeline.social_auth.associate_user','social.pipeline.social_auth.load_extra_data','social.pipeline.user.user_details','app.utils.create_profile'  #Custom pipeline
)#utils.py 
def create_profile(strategy, details, response, user, *args, **kwargs):username = kwargs['details']['username']user_object = User.objects.get(username=username)if Profiles.ojects.filter(user=user_object).exists():passelse:new_profile = Profiles(user=user_object)new_profile.save()return kwargs

I get the error:

 KeyError at /complete/facebook/'details'...utils.py in create_profileusername = kwargs['details']['username']

I'm new to python social auth, and it looks that I'm missing something obvious. Any help will be appreciated.

Answer

Ok so I'll answer my own question just in case it is useful for someone in the future. I'm no expert but here it is:

I was following this tutorial, and becouse he does

 email = kwargs['details']['email']

I thought I could do

username = kwargs['details']['username']

But it didn't work, it gave my a KeyError.

Then I tried:

username = details['username']

And it worked. But I had a new problem, the username from the details dict was something like u'Firstname Lastname' and when I tried to get the User object

user_object = User.objects.get(username=username)

It was not found, becouse the username in the User model was u'FirstnameLastname' (without the space).

Finally I read the docs again and I found out that I could simply use the user object directly, it gets passed to the function as "user":

def create_profile(strategy, details, response, user, *args, **kwargs):if Profiles.objects.filter(usuario=user).exists():passelse:new_profile = Profiles(user=user)new_profile.save()return kwargs
https://en.xdnf.cn/q/72325.html

Related Q&A

What is a good audio library for validating files in Python?

Im already checking for content-type, size, and extension (Django (audio) File Validation), but I need a library to read the file and confirm that it is in fact what I hope it is (mp3 and mp4 mostly).I…

Python 3.6+: Nested multiprocessing managers cause FileNotFoundError

So Im trying to use multiprocessing Manager on a dict of dicts, this was my initial try:from multiprocessing import Process, Managerdef task(stat):test[z] += 1test[y][Y0] += 5if __name__ == __main__:te…

Convert python disassembly from dis.dis back to codeobject

Is there any way to create code object from its disassembly acquired with dis.dis?For example, I compiled some code using co = compile(print("lol"), <string>, exec) and then printed di…

Loop over a tensor and apply function to each element

I want to loop over a tensor which contains a list of Int, and apply a function to each of the elements. In the function every element will get the value from a dict of python. I have tried the easy wa…

How to quickly get the last line from a .csv file over a network drive?

I store thousands of time series in .csv files on a network drive. Before I update the files, I first get the last line of the file to see the timestamp and then I update with data after that timestamp…

Force use of scientific style for basemap colorbar labels

String formatting can by used to specify scientific notation for matplotlib.basemap colorbar labels:cb = m.colorbar(cs, ax=ax1, format=%.4e)But then each label is scientifically notated with the base.I…

VS Code Doesnt Recognize Python Virtual Environment

Im using VS Code on a Mac to write Python code. Ive created a virtual environment named venv inside my project folder and opened VS Code in my project folder. I can see the venv folder in the Explore…

Why codecs.iterdecode() eats empty strings?

Why the following two decoding methods return different results?>>> import codecs >>> >>> data = [, , a, ] >>> list(codecs.iterdecode(data, utf-8)) [ua] >>>…

How to keep NaN in pivot table?

Looking to preserve NaN values when changing the shape of the dataframe.These two questions may be related:How to preserve NaN instead of filling with zeros in pivot table? How to make two NaN as NaN …

Using Pandas df.where on multiple columns produces unexpected NaN values

Given the DataFrameimport pandas as pddf = pd.DataFrame({transformed: [left, right, left, right],left_f: [1, 2, 3, 4],right_f: [10, 20, 30, 40],left_t: [-1, -2, -3, -4],right_t: [-10, -20, -30, -40], }…