Kymane Llewellyn
Kymane Llewellyn

Reputation: 51

How to save a django model to database? save() method is not working

Hi I'm having trouble saving a django model to my database.

My application uses Google signin for authentication and if the user's profile is not already in the database after authentication, it redirects them to a form where they can create a profile.

The problem is whenever a user creates a profile it's not saving to the database.

Below I've attached a picture of my admin page. (You will see that there is no Profile object) I've also attached my forms.py, models.py, and views.py

views.py

def register(request):

user_email = Profile.objects.filter(email = request.user.email).exists()
if request.user.is_authenticated:
    if user_email:
        return redirect('blog-home')
    else:
        if request.method == 'POST':
            profile = Profile()
            profile_form = CreateProfileForm(request.POST, instance=profile)
            if profile_form.is_valid():
                profile.user = request.user
                profile.email = request.user.email
                profile_form.save()
                messages.success(request, f'Your account has been created! You are now able to log in')
                return redirect('blog-home')
        else:
            profile_form = CreateProfileForm()

    context = { 'form': profile_form  }

return render(request, 'users/register.html', context)

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, null = True, on_delete=models.CASCADE)
    username = models.CharField(max_length = 15, default = '')
    first_name = models.CharField(max_length=20, default='')
    last_name = models.CharField(max_length=20, default='')
    email = models.CharField(max_length = 25, default = '')
    #image = models.ImageField(null=True, blank=True, upload_to='media/user/profile')
    #interests

    def __str__(self):
        return f'{self.first_name} Profile'

forms.py

class CreateProfileForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ['first_name', 'last_name', 'username']

enter image description here

Upvotes: 0

Views: 2355

Answers (1)

Ffion
Ffion

Reputation: 559

It looks as though you are getting mixed up with profile and profile_form and therefore overriding your changes. You should call profile.save() rather than profile_form.save(), as you have made the changes (adding user and email) to profile. There's no need to instantiate a new Profile() inside the is_valid() method. Try something like this:

if request.method == 'POST':
    profile_form = CreateProfileForm(request.POST)
    if profile_form.is_valid():
        profile = profile_form.save(commit=False)
        profile.user = request.user
        profile.email = request.user.email
        profile.save()
        messages.success(request, f'Your account has been created! You are now able to log in')
        return redirect('blog-home')

Upvotes: 1

Related Questions