Search code examples
djangodjango-modelsdjango-formsdjango-allauth

How do I save to Django's database manually?


I'm trying to make a UserProfile model in Django. Half the information for the fields in this model will come directly from the user's input in a form, but the other half I'm importing from a social network that they authenticate when they login. How would I go about implementing this?

if form.is_valid():
    prefs = form.save(commit=False)
    prefs.user = request.user
    prefs.save()
    # if they logged in through social network there are other fields
    if socialacc:
        firstname = socialacc[0].extra_data['firstName']

So now I have the data for 'firstname' as a string. How should I save this to the same model? The model will include a field called firstname, which will be empty unless there is social authentication information available.

Thanks a lot for any help!


Solution

  • Since the save method returns an Model object, you can modify it again before definitively save it to the database :

    if form.is_valid():
        prefs = form.save(commit=False)
        prefs.user = request.user
        # if they logged in through social network there are other fields
        if socialacc:
            prefs.firstname = socialacc[0].extra_data['firstName']
            ...
        prefs.save()