简体   繁体   中英

Default/Initial value for Django forms field (required=True) after POST-request (bound forms)

I tried all the solutions here on Stackoverflow but they all use required=False. How can I set a default value for a required form-field every time, even after a post request (when the form is bound)?

# forms.py
class MyForm(forms.Form): 
   name = forms.CharField(required = True)

   def __init__(self, *args, **kwargs):
        
       super(editSonde_KundenAdminPanel, self).__init__(*args, **kwargs)
       self.initial['name'] = "foo bar"


#Views.py
def index(request):

   if request.method == 'GET':
        form = MyForm()

   if request.method == 'POST':
        form = MyForm(request.POST)
        #After this step, the form doesn't have an initial value anymore...
        if form.is_valid()
            #Do Stuff


The documentation says to create a new Form instance.

If you have a bound Form instance and want to change the data somehow, or if you want to bind an unbound Form instance to some data, create another Form instance. There is no way to change data in a Form instance. Once a Form instance has been created, you should consider its data immutable, whether it has data or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM