[Answer]-Set form's default values from existing objects in Django

0👍

For future reference: I solved using Initial when rendering the form as showed here

👤Higure

1👍

Use a ModelForm instead of a regular Form. A ModelForm can be associated with an instance, which is the used to prepopulate the form. If you want to update both the User and the profile, you can use two ModelForms in one view. For example:

class UserModelForm(forms.ModelForm):
    repassword = ... # additional fields that have no represenation in the model

    class Meta:
        model = User
        fields = ["username", "password", ]  # ...

    def clean(self):
        # ... your validation logic

class ProfileForm(forms.ModelForm):
    class Meta:
        model = YourProfileModel
        fields = []  # ...

Then use both in the view:

def usermodify(request, user):
    # mod_user = ...

    user_form = UserModelForm(request.POST or None, instance=mod_user)
    profile_form = ProfileForm(request.POST or None, instance=mod_user.get_profile())
    if user_form.is_valid() and profile_form.is_valid():
        user_form.save()  # this saves to the associated mod_user, as passed via the `instance` argument
        profile_form.save() 
        # ... redirect etc.
    return render(..., {'user_form': user_form, 'profile_form': profile_form})  # pass both forms to the template

In the template, put both forms inside of one <form> tag. Be sure that they don’t have conflicting field names, or use a prefix.

👤sk1p

0👍

  1. If you are trying to get default values in the object. You can set that in your model, and these will carry over to your forms, and populate. Example:

    school_choices = models.CharField(blank=True, default=’HS’)

  2. Combine that with using Django’s CBV’s (Class Based Views) and the UdpdateView:

    https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-editing/#updateview

The UpdateView will pre-populate your forms for you.

Leave a comment