'Charfield with select2 input not populated in update view
I'm working on a form that gets the "Education" information from the user. The institute name is one of the fields in the model.
The initial configuration for the model:
class Education(models.Model):
owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False)
institute = models.CharField(max_length=50, null=True, blank=True)
program = models.CharField(max_length=50, null=True, blank=True)
level = models.CharField(max_length=1, choices=StudyLevel.choices, default=StudyLevel.UNSPECIFIED)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
I don't want to grant the users ability to give meaningless input. That's why I decided to let users "select" their university from an external API. Sample search: http://universities.hipolabs.com/search?name=johannes
I used jQuery Select2 with Ajax to fetch data from the API whenever user types a character in the field.
Ajax code:
$(document).ready(function () {
$('#id_institute').select2({
ajax: {
url: 'http://universities.hipolabs.com/search?',
data: function (params) {
return {
name: params.term
};
},
dataType: 'json',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {id: item.name, text: item.name};
})
};
}
},
width: '50%',
minimumInputLength: 1
});
And I had to overwrite the widget for the 'institute' field at the ModelForm as following:
class EducationForm(ModelForm):
class Meta:
model = Education
fields = '__all__'
exclude = ['owner']
widgets = {
'institute': forms.Select(),
}
It works as expected: create view
However, when I go to the update view of the model, the initial choice is not automatically selected. (other form fields are correctly populated) update view
I tried to modify the ModelForm init function but couldn't succeed.
I used select2 library for a model field with type models.ForeignKey (without ajax, with options from the database) and it has no problem loading the initial choice to the update view.
This made me question if the models.Charfield is a good way to store this kind of data in the model. What is the best way to store the users selection? If it the best way, what am I doing wrong?
Also, I realize that there is a specialized django-select2 library but I didn't use it. Does it make a difference other that avoiding to write ajax code etc. by myself?
Create and Update views of the model:
class EducationCreateView(LoginRequiredMixin, CreateView):
model = Education
form_class = EducationForm
success_url = '/account'
def form_valid(self, form):
form.instance.owner = self.request.user.profile
return super().form_valid(form)
class EducationUpdateView(LoginRequiredMixin, UpdateView):
model = Education
form_class = EducationForm
success_url = '/account'
HTML Form that I use for the ModelForm:
<form class="form" method="post" action="">
{% csrf_token %}
{% for field in form %}
<div class="form__field">
<label for="formInput#text">{{ field.label }} </label>
{{ field }}
</div>
{% endfor %}
<input class="btn btn--sub btn--lg my-md" type="submit" value="Submit"/>
</form>
Thank you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
