Sree Ram Sree Ram - 3 months ago 6
Python Question

Form Data not refreshing with newest entries

When I add a new customer in customer table and access AddOrderForm form, I don't get the new customer in the choices.But on server restart I am able to get the new customer in the choices list.Any reason ?

Customer Table

class Customer(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True)
mobile_num = db.Column(db.String(13), unique=True)
name = db.Column(db.String(120))
marketing_source = db.Column(db.String(120))
date_of_birth = db.Column(db.DateTime)
gender = db.Column(db.String(13))
store_id = db.Column(db.Integer, db.ForeignKey('store.id'))

def __init__(self,email,mobile_num,name,marketing_source,date_of_birth, gender,store_id):
self.email = email
self.mobile_num = mobile_num
self.name = name
self.marketing_source = marketing_source
self.date_of_birth = date_of_birth
self.gender = gender
self.store_id = store_id
def __repr__(self):
return '%r, %s ' % (self.name.encode('utf-8'), self.mobile_num)


AddOrderForm

class AddOrderForm(Form):
order_id = TextField('Website Order Id', [validators.length(min=4, max=120)])
item_name = TextField('Item Name', [validators.length(min=4, max=120)])
item_cost = DecimalField('Item Cost' , [validators.Required()])
custmer_id = SelectField('Customer',coerce=int,choices= convert_list_wtforms_choices(Customer.query.all()))
order_category = SelectField('Order Category',coerce=int,choices=[(1,'Mobiles'), (2,'Clothing')])
linq_shipping_cost = DecimalField('Linq Shipping Cost' , [validators.Required()])
website_shipping_cost = DecimalField('Website Shipping Cost' , [validators.Required()])
advance_amount = DecimalField('Advance Amount' , [validators.Required()])
website = SelectField('Website', coerce=int,choices=[(1,'Amazon'), (2,'Flipkart')] )
other = TextField('Any Other Information')


While accessing the form from a view I don't get the latest added customer in the custmer_id choices. Any idea to fix this?

Answer

You're only setting the choices once, when you define the form. Instead, re-select them every time you instantiate the form.

class AddOrderForm(Form): customer_id = SelectField('Customer', coerce=int)

def __init__(self, *args, **kwargs):
    super(AddOrderForm, self).__init__(*args, **kwargs)
    self.customer_id.choices = convert_list_wtforms_choices(Customer.query.all())