Reputation: 824
I have a django template that I want to display for the user. Now I am working on an editable version of an html template. I wanted to know if there is a way to prefill a django form with relative information that is grabbed from the database or query set. I know how to display and work with forms, but not prefilling a form with information.
Here is a simple form and queryset.
I want to fill the UserSettingsTwoForm()
with info from the currentProfile
queryset.
currentProfile = Profile.objects.get(user = currentUser)
userSettingTwo = UserSettingsTwoForm()
parameters = {
'userSettingTwo':userSettingTwo,
}
return render(request, 'tabs/user_settings.html', parameters)
Here is a sample html file:
{% extends "base.html" %}
{% block content %}
<h1>Settings</h1>
<form action="." method="POST">
{% csrf_token %}
{{ userSettingTwo.as_p }}
<input type="submit" name="submit" value="submit">
</form>
{% endblock %}
Upvotes: 0
Views: 94
Reputation: 1155
If UserSettingsTwoForm is Profile model form then you can load previous instance by just instance keyword and pass instance to it
currentProfile = Profile.objects.get(user = currentUser)
userSettingTwo = UserSettingsTwoForm(instance=current_profile)
parameters = {
'userSettingTwo':userSettingTwo,
}
return render(request, 'tabs/user_settings.html', parameters)
Otherwise Use Initial if UserSettingsTwoForm is not profile model form.
currentProfile = Profile.objects.get(user = currentUser)
userSettingTwo = UserSettingsTwoForm(initial = {'form_field': currentProfile.fieldname, 'form_second_field': currentProfile.fieldname})
parameters = {
'userSettingTwo':userSettingTwo,
}
return render(request, 'tabs/user_settings.html', parameters)
Thats' it.
Upvotes: 2