سؤال

flask + wtforms

Hello, I have some problems with the transfer of data into a form

def edit_comment(n): 
    idlist = str(n)  
    if (r.exists('entries:%s' %idlist) != True):
        return abort(404)
    if 'user_id' not in session:
        return abort(401)    
    if (g.user['group_access'] == '1'):
        return abort(403)
    form = EditForm(idlist)
    return render_template('edit_comment.html',idlist = idlist, r = r, form = form)

...

class EditForm(Form):
    edit_title = TextField("Title",validators = [Required()] ,default =r.hget('entries:%s' %idlist, 'title'))
    edit_text = TextAreaField("Text",validators = [Required()],default =r.hget('entries:%s' %idlist, 'text'))

...

Traceback (most recent call last):
  File "run.py", line 129, in <module>
    class EditForm(Form):
  File "run.py", line 130, in EditForm
    edit_title = TextField("Title",validators = [Required()] ,default =r.hget('entries:%s' %idlist, 'title'))
NameError: name 'idlist' is not defined

here there are clear problems with data transmission. tried to pass through the constructor, but so far No results

هل كانت مفيدة؟

المحلول

You need to set the default value on the EditForm instance. Right now it' set at import time - clearly not what you want, even if the variable was defined. Actually, you don't even need the default field for it - just set it directly:

form = EditForm()
form.edit_title.data = r.hget('entries:%s' % idlist, 'title')
form.edit_text.data = r.hget('entries:%s' % idlist, 'text')
return render_template('edit_comment.html', idlist=idlist, r=r, form=form)

Note: Usually it's a good idea to have your view function to have a structure similar to this:

form = EditForm()
if form.validate_on_submit():
    # do whatever should be done on submit, then redirect somewhere
    return redirect(...)
elif request.method == 'GET':
    # Populate the form with initial values
    form.edit_title.data = ...
    form.edit_text.data = ...
return render_template(..., form=form)

That way whatever the user entered is preserved in case the validation fails, but if he opens the form for the first time it's populated with whatever default data (e.g. the current values from your db) you want.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top