Home > other >  Edit multiple Models using one form or view in Django
Edit multiple Models using one form or view in Django

Time:02-15

I am using the default User model in Django and a OneToOneField in a Profile model where extra info such as user bio is stored.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)

I am able to create basic forms for the two models independently

from django.contrib.auth.models import User


class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ['username', 'email']

class ProfileForm(ModelForm):
    class Meta:
        model = Profile
        fields = ['bio']

What is the best method to create a page where a user can edit fields of either model?

So a User can edit Username,Email or Bio on the same page?

CodePudding user response:

You can put the 2 forms in one template and Django will manage filling forms with the right fields (only exception is the same field name in 2 forms)

def view(request):
    if request.method == "GET":
        context["userform"]=UserForm()
        context["profileform"] =ProfileForm()
    else:
         userform = UserForm(request.POST)
         profileform=ProfileForm(request.POST)
  • Related