Reputation: 2370
I have some external data (SOAP) that I want to show in a model-based-form.
The Model:
class UserProfile(User):
profile_email = models.EmailField()
company_name = models.CharField()
coc_number = models.CharField()
gender = models.CharField()
#etc
The Form:
class UserDetailsForm(forms.ModelForm):
class Meta:
model = UserProfile
The data is a dictionary:
u = {}
u['profile_email'] = 'monkey'
u['company_name'] = 'tiger'
u['coc_number'] = 'some number'
u['gender'] = 'M'
My question is: What is the best way to put the data into the form? What I have so far:
form = UserDetailsForm(initial=u)
This results in a form with all the data. 1) But is this the right way to fill a model-bases-form with external data? 2) How can I set the right value in a select option (Choose country for instance)?
Upvotes: 0
Views: 250
Reputation: 53326
Yes, this is appropriate way.
You need to set value for select/choices field in the dict similar to approach 1.
For example:
COUNTRY_CHOICES = (
('IN', 'India'),
('US', 'USA'),
)
....
#model field
country = models.CharField(choices=COUNTRY_CHOICES)
# then set it in dict as
u = {}
u['country'] = 'IN'
u['profile_email'] = 'monkey'
u['company_name'] = 'tiger'
u['coc_number'] = 'some number'
u['gender'] = 'M'
...
Upvotes: 1