英文:
keep old value input in django model form
问题
在Django表单模型中,要实现在验证失败时保留先前输入的值,你可以使用initial
参数来设置字段的初始值。这将确保即使验证失败,输入字段将保持以前的值,而不需要重新输入。以下是如何在你的Django表单模型中使用initial
参数:
class AddMenuForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AddMenuForm, self).__init__(*args, **kwargs)
if self.instance:
# 如果表单已经与一个实例相关联,使用实例的值作为初始值
self.initial['title'] = self.instance.title
self.initial['url'] = self.instance.url
class Meta:
model = Menu
fields = "__all__"
widgets = {
'title': forms.TextInput(attrs={
'class': 'form-control',
'id': 'inputname',
'placeholder': 'نام آیتم'
}),
'url': forms.TextInput(attrs={
'class': 'form-control',
'id': 'inputurl',
'placeholder': ' mr-keshi.ir /'
}),
}
在这个示例中,我们在__init__
方法中检查是否表单已经与一个实例相关联,如果是的话,我们将使用实例的值作为字段的初始值。这将确保在验证失败时,输入字段将保持以前的值,而不需要重新输入。
这样,当提交无效的表单时,字段将保持相同的无效值。
英文:
In Laravel, we used old('field_name') to display previous input values. How can I do this in Django form model? I mean If the validation is unsuccessful the input value will be deleted. I want its previous value to be preserved and not need to be typed.
mean when submitting invalid form, field fields should keep the same invalid value in input value.
class AddMenuForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
x=super(AddMenuForm, self).__init__(*args, **kwargs)
return x
class Meta:
model=Menu
fields="__all__"
widgets = {
'title': forms.TextInput(attrs={
'class': 'form-control',
'id':'inputname',
'placeholder': "نام آیتم"
}),
'url': forms.TextInput(attrs={
'class': 'form-control',
'id': 'inputurl',
'placeholder': " mr-keshi.ir /"
}),
view :
class addMenu(FormView):
template_name = 'Menu/addMenu.html'
success_url = reverse_lazy('Menu')
form_class = AddMenuForm
def get_context_data(self, **kwargs):
if (self.kwargs['menu'] not in Menu.placeMenu):
# Todo: send error message
pass
data = super(addMenu, self).get_context_data(**kwargs)
data['places'] = Menu.placeMenu
data['place'] = self.kwargs['menu']
return data
def form_valid(self, form):
print("form valid")
menu = self.kwargs.get('menu')
if (menu in Menu.placeMenu):
form.save()
else:
pass
# Todo: send error message
# Todo:send success message
return True
def form_invalid(self, form):
print("form is not valid")
return super(addMenu, self).form_invalid(form)
html template
<form method="post" action="{% url 'addMenu' menu=place%}">
{% csrf_token %}
<div class="form-row mb-4">
<div class="form-group col-md-6">
<label for="inputname">نام آیتم</label>
{{ form.title }}
{% if form.title.errors %}
<div style="color: #ef2d2d;margin-bottom: -60px !important;" class="alert alert-arrow-right alert-icon-right alert-light-danger mb-2 mt-2" role="alert">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-alert-circle"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12" y2="16"></line></svg>
<strong>هشدار!</strong>{{ form.title.errors }}
</div>
{% endif %}
</form>
答案1
得分: 1
你可以使用initial
参数来设置字段的初始值,即使表单提交失败,该值也会显示在表单中,代码如下:
class AddMenuForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance:
self.fields['title'].initial = self.instance.title
class Meta:
model = Menu
fields = "__all__"
widgets = {
'title': forms.TextInput(attrs={
'class': 'form-control',
'id': 'inputname',
'placeholder': 'نام آیتم'
}),
'url': forms.TextInput(attrs={
'class': 'form-control',
'id': 'inputurl',
'placeholder': 'mr-keshi.ir /'
}),
}
在这里,self.instance.title
将是title
字段的当前值。
然后,在你的当前模板中,使用{{form.title}}
(你已经有了它)将显示initial
值。
英文:
You can use the initial
parameter to set the initial value for a field, which will be displayed even if the form is submitted unsuccessfully so in forms:
class AddMenuForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance:
self.fields['title'].initial = self.instance.title
class Meta:
model = Menu
fields = "__all__"
widgets = {
'title': forms.TextInput(attrs={
'class': 'form-control',
'id': 'inputname',
'placeholder': 'نام آیتم'
}),
'url': forms.TextInput(attrs={
'class': 'form-control',
'id': 'inputurl',
'placeholder': 'mr-keshi.ir /'
}),
}
Here, self.instance.title
will be the current value of the title
field.
Then with your current template, using {{form.title}}
(which you already had it) it will display initial
value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论