Reputation: 603
I am creating user profiles in which Profile have OnetoMany relationship with Work_experience. I have tried
{{ form.experience.job_title }}
but it didn't work. How do I access Work_Experience fields and render them as TextInput?
Django version: 2.0
Models
class Work_Experience(models.Model):
job_title = models.CharField(max_length=100, null=True, blank=True)
company = models.CharField(max_length=100, null=True, blank=True)
description = models.CharField(max_length=300, null=True, blank=True)
exp_start_date = models.DateField(null=True, blank=True)
exp_end_date = models.DateField(null=True, blank=True)
class Profile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
full_name = models.CharField(max_length=30, null=True, blank=True)
experience = models.ForeignKey(Work_Experience, on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return str(self.user.username)
Template
<div class="field">
<label>Job title<span class="red-txt">*</span></label>
{{ form.experience }}
</div>
Form
class ProfileSettingsForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['full_name','experience']
widgets = {
'full_name' : forms.TextInput({'class': 'form-control'}),
'experience' : forms.TextInput({'class':'form-control'})
}
Upvotes: 3
Views: 85
Reputation: 603
Solved it by overriding save() method.
class ProfileSettingsForm(forms.ModelForm):
job_title = forms.CharField(max_length=40, required=False)
def __init__(self, *args, **kwargs):
super(ProfileSettingsForm, self).__init__(*args, **kwargs)
self.fields['job_title'].initial = self.instance.experience.job_title
def save(self, commit=True):
model = super(ProfileSettingsForm, self).save(commit=False)
jt = self.cleaned_data['job_title']
if model.experience:
model.experience.job_title = jt
model.experience.save()
else:
model.experience = Work_Experience.objects.create(job_title=jt)
if commit:
model.save()
return model
class Meta:
model = Profile
fields = ['full_name']
widgets = {
'full_name' : forms.TextInput({'class': 'form-control'}),
}
Upvotes: 1