[Answered ]-Keep old value input in django model form

1👍

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.

Leave a comment