问题
I'm trying to create a customized form in a modelformset_factory using jquery.formset.js
.
Here is a code:
Customized form class:
class CustomizedForm(forms.ModelForm):
date = forms.DateField(widget=JQueryUIDatepickerWidget, required=True )
time_begin = forms.TimeField(widget=JQueryUITimePickerWidget, required=True, initial=time(0, 0))
time_end = forms.TimeField(widget=JQueryUITimePickerWidget, required=True, initial=time(23,59))
def __init__(self, *args, **kwargs):
super(CustomizedForm, self).__init__(*args, **kwargs)
Custom formset class:
class FormSetWithInitialValues(BaseModelFormSet):
def __init__(self, initials, **kwargs):
super(FormSetWithInitialValues, self).__init__(**kwargs)
self.initials = initials
def save_new(self, form, commit=True):
for k, val in self.initials.items():
form.cleaned_data[k] = val
return form.save(commit=commit)
Formset factory:
Formset = modelformset_factory(
MyModel,
formset=FormSetWithInitialValues,
form=CustomizedForm,
can_delete=True,
extra=1,
)
The problem is next. When i init page all existing formsets initialize with widgets. But when I try to add new form to formset the form is create, but widgets don't tie with form's fields. The question is, how to tie widgets with new form's fields?
回答1:
Tural,
I don't understand your question. But, I post this bit of my code. I hope this can help to you. This is a first approach, we can refine answer.
formset_f = modelformset_factory( ItemQualitativa, extra=20 )
if request.method == 'POST':
formset = formset_f(request.POST)
if formset.is_valid():
formset.save()
else:
formset = formset_f()
for form in formset:
form.fields['text'].widget.attrs['size'] = 70 #<-try change widget here.
That I don't understand about your question is this sentence: "But when I try to add new form to formset the form is create". When do tou try to add new forms?
regards.
回答2:
Problem solving is next. When we add a new form to formset, jquery just copies hidden html row corresponding to form fields, cleans it, and gives new ids. But it doesn't copy information about widgets. So we should use js-callback function which is called after new form to formset add:
<script src="{{ STATIC_URL }}js/jquery.formset/jquery.formset.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
{% if formset %}
var datepickerConfig = {};
datepickerConfig.__proto__ = DatePickerConfig;
var timepickerConfig = {};
timepickerConfig.__proto__ = TimePickerConfig;
$('.calendar_formset_tr').formset({
prefix : '{{ formset.prefix|escapejs }}',
deleteText: ' <img src="{{ STATIC_URL }}images/icons/delete.png" />',
addText: ' <img src="{{ STATIC_URL }}images/icons/add.png" />',
addCssClass: 'add_link',
deleteCssClass: 'remove_link',
added: function (row) {
var datePicker = $(row).find('input[name$="date"]');
if (datePicker.length > 0) {
//привязка виджета
datePicker.datepicker('destroy').datepicker(datepickerConfig);
}
var timeBeginPicker = $(row).find('input[name$="time_begin"]');
var timeEndPicker = $(row).find('input[name$="time_end"]');
if (timeBeginPicker.length > 0 && timeEndPicker.length > 0) {
//привзяка виджета и проставление значения по-умолчанию
timeBeginPicker.val("00.00");
timeBeginPicker.timepicker('destroy').timepicker(timepickerConfig);
timeEndPicker.val("23.59");
timeEndPicker.timepicker('destroy').timepicker(timepickerConfig);
}
}
});
{% endif %}
});
</script>
来源:https://stackoverflow.com/questions/8940483/using-a-form-with-custom-field-widgets-in-a-modelformset-factory