我开始了thread,并设法在昨天找出问题。
然而,又发生了另一个相关问题。
当我在模型中有第二个选择列表时,我选择' 8888'或' 9999'要在提交表单时删除/重置值,如何将第二个选择列表的值设置为默认值?
以下是我的models.py代码示例:
.....
DISPLAY_ONLY_AWARD_AND_GRANT_DESCRIPTION_WITH_PROMPT = 8888
DISPLAY_ONLY_AWARD_AND_GRANT_DESCRIPTION_WITHOUT_PROMPT = 9999
.....
AWARD_GRANT_TYPES = (
(SELECT_AWARD_AND_GRANT_TYPE, _('Select Type')),
....
(OTHER_GRANT, _('Other Grant')),
(WRITE_MY_OWN_AWARD_AND_GRANT_TYPE_DESCRIPTION, _('Write my own Type description')), #7777
(DISPLAY_ONLY_AWARD_AND_GRANT_DESCRIPTION_WITH_PROMPT, _('Display only Description with prompt')), #8888
(DISPLAY_ONLY_AWARD_AND_GRANT_DESCRIPTION_WITHOUT_PROMPT, _('Display only Description without prompt')) #9999
)
....
AWARD_GRANT_DISPLAY_COMMENCEMENT_DATE_AND_COMPLETION_DATE_AS_DATE_PROMPTS = 1
....
AWARD_GRANT_DETAILS_DATE_DISPLAY_TYPES = (
(AWARD_GRANT_DISPLAY_COMMENCEMENT_DATE_AND_COMPLETION_DATE_AS_DATE_PROMPTS, _('Display Commencement and Completion as date prompts')),
....
)
user = models.ForeignKey(User)
language_version = models.ForeignKey('LanguageVersion')
award_grant_type = models.PositiveIntegerField(choices=AWARD_GRANT_TYPES, default=SELECT_AWARD_AND_GRANT_TYPE, validators=[MinValueValidator(1)])
award_grant_type_description = models.CharField(null=True, blank=True, max_length=250)
award_grant_date = models.DateField(null=True, blank=True)
award_grant_date_display_type = models.PositiveIntegerField(choices=AWARD_GRANT_DETAILS_DATE_DISPLAY_TYPES, default=AWARD_GRANT_DISPLAY_COMMENCEMENT_DATE_AND_COMPLETION_DATE_AS_DATE_PROMPTS)
award_grant_description = models.TextField(null=False, blank=False, max_length=5000)
这是我的forms.py清洁代码,当用户在提交之前从选择列表award_grant_date_display_type
中选择8888
或9999
时,应将award_grant_type
重置为1到db:
def clean(self):
cd_agdf = super(AwardGrantDetailsForm, self).clean()
if 'award_grant_type' in cd_agdf:
if cd_agdf['award_grant_type'] == '':
self._errors['award_grant_type'] = self.error_class([_("You must select a Type.")])
elif cd_agdf['award_grant_type'] == '8888' or cd_agdf['award_grant_type'] == '9999':
# remove / reset the entered values when the award grant type only requires minimum data.
self.cleaned_data.pop('award_grant_type_description', None)
self.cleaned_data.pop('award_grant_date', None)
self.cleaned_data['award_grant_date_display_type'] = 1
else:
....
return cd_agdf
似乎会忽略代码行self.cleaned_data['award_grant_date_display_type'] = 1
并保留原始值。
我尝试将该值放在引号中,搜索SO,Google和django文档,但我无法弄明白。
修改
这是我要求的forms.py代码:
class AwardGrantDetailsForm(forms.ModelForm):
def __init__(self, available_languages, language_preference, *args, **kwargs):
"""
available_languages should be a valid choices list
"""
super(AwardGrantDetailsForm, self).__init__(*args, **kwargs)
self.fields['language_code'] = forms.ChoiceField(choices=available_languages, initial=language_preference, label=_('Language'),)
self.fields['award_grant_date'].input_formats = (settings.DATE_INPUT_FORMATS)
class Meta:
model = AwardGrantDetails
fields = (
'award_grant_type',
'award_grant_type_description',
'award_grant_date',
'award_grant_date_display_type',
'award_grant_description',
)
labels = {
'award_grant_type': _('Type'),
'award_grant_type_description': _('Type Description'),
'award_grant_date': _('Date'),
'award_grant_date_display_type': _('Date Prompts'),
'award_grant_description': _('Description'),
}
help_texts = {
'award_grant_description': _('5,000 character limit'),
}
input_formats = {
'award_grant_date': settings.DATE_INPUT_FORMATS,
}
widgets = {
#'award_grant_description': CKEditorWidget(),
'award_grant_date': forms.DateInput(attrs={'id': 'id_award_grant_date'}, format='%m/%Y'),
#'award_grant_date': forms.DateInput(attrs={'id': 'id_award_grant_date'}, format=settings.DATE_INPUT_FORMATS),
}
error_messages = {
'award_grant_type': {'validate_min': _('This field is required.')}, # validate_min used on award_grant_type in lieu of required field.
}
修改
这是我要求的views.py代码:
@login_required
@resume_menu_required(entry_number=settings.MENU_DETAIL_VALUE_AWARD_GRANT_DETAILS)
@complete_profile_required
def award_grant_details_edit(request, award_grant_details_id):
try:
award_grant_details = AwardGrantDetails.objects.get(pk=award_grant_details_id, user=request.user)
except AwardGrantDetails.DoesNotExist:
return redirect(settings.MENU_DETAIL_LINK_AWARD_GRANT_DETAILS)
language_versions = LanguageVersion.objects.filter(user=request.user).select_related('language_version')
available_languages = get_available_language_details(language_versions, request.user.userprofile.language_preference)
award_grant_details_num = request.user.awardgrantdetails_set.count()
language_code = award_grant_details.language_version.language_code
language_code_disabled = award_grant_details.language_version.language_code_disabled
preview_labels = get_award_grant_types(available_languages)
selected_resume_menu_entries = (request.user.userprofile.selected_resume_menu_entries)
if language_code_disabled:
return redirect(settings.MENU_DETAIL_LINK_AWARD_GRANT_DETAILS)
if request.method == 'GET':
language_code = award_grant_details.language_version.language_code
form = AwardGrantDetailsForm(
available_languages=available_languages,
language_preference=request.user.userprofile.language_preference,
initial=dict(model_to_dict(award_grant_details), language_code=language_code))
elif request.method == 'POST':
form = AwardGrantDetailsForm(
available_languages=available_languages,
language_preference=request.user.userprofile.language_preference,
data=request.POST)
if form.is_valid():
award_grant_details.fill(form.cleaned_data)
award_grant_details.save()
messages.success(request, _('successfully updated.'))
return redirect(settings.MENU_DETAIL_LINK_AWARD_GRANT_DETAILS)
return render(request,'resume_details/award_grant_details_edit.html',{
'address_details_count': get_address_details_count(request.user),
'award_grant_details': award_grant_details,
'award_grant_details_num': award_grant_details_num,
'contact_details_count': get_contact_details_count(request.user),
'display_default_language': display_default_language(request.user),
'form': form,
'language_versions': get_language_versions(user=request.user),
'language_versions_num': len(language_versions), # the count of all users Language Versions (enabled & disabled).
'languages': LANGUAGES,
'max_award_grant_details': settings.MAX_AWARD_GRANT_DETAILS,
'max_details_count': settings.MAX_AWARD_GRANT_DETAILS,
'name_details_count': get_name_details_count(request.user),
'preview_labels': preview_labels,
'resume_details_menu_link': settings.MENU_DETAIL_LINK_AWARD_GRANT_DETAILS,
'resume_details_menu_num': settings.MENU_DETAIL_VALUE_AWARD_GRANT_DETAILS,
'selected_resume_menu_entries': selected_resume_menu_entries,
})
答案 0 :(得分:0)
我从未发现这个问题的答案。
但是,解决方法是在选择8888或9999且没有错误的表单提交时,我使用jquery手动将值设置为1:
$('#id_of_element_type').val('1');
我希望这能帮助别人。