Saturday, 17 September 2022

Save values into another database table with one-to-one relationship in Django during form update

This is my models.py with 2 tables having a one-to-one table relationship. UserComputedInfo model has a one-to-one relationship with CustomUser model.

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.contrib.auth import get_user_model


class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)
    post_code = models.DecimalField(max_digits=9, decimal_places=6)

    def __str__(self):
        return self.username


class UserComputedInfo(models.Model):
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
    copy_input = models.DecimalField(max_digits=9, decimal_places=6)

    def __str__(self):
        return self.copy_input

Here is the relevant section of my views.py.

from django.shortcuts import redirect
from django.contrib import messages


def profile(request, username):
    if request.method == "POST":
        user = request.user
        form = UserUpdateForm(request.POST, request.FILES, instance=user)
        if form.is_valid():
            user_form = form.save()
            # How to save post_code to copy_input in UserComputedInfo model
            messages.success(request, f'{user_form.username}, Your profile has been updated!')
            return redirect("profile", user_form.username)

    return redirect("homepage")

After a user submits a form, profile function will be run and post_code in CustomUser model will be updated. What I want to do is copy the content of post_code to copy_input in UserComputedInfo model as well.

How do I do that inside my views.py?

I am running Django v4 and Windows 10.



from Save values into another database table with one-to-one relationship in Django during form update

No comments:

Post a Comment