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 ModelForm
s 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
.
- [Answer]-How to use messages in Django?
- [Answer]-Django: Template logic not rendering query data, no errors given either
- [Answer]-Django: Implement View on google maps button on google maps
- [Answer]-Django throwing error with '/' in url
- [Answer]-How to implement bootstrapvalidation inDjango
0👍
-
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’)
-
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.