简体   繁体   English

如何为WTForms-Alchemy指定unique = True?

[英]How do you specify unique=True for WTForms-Alchemy?

I have the following class: 我有以下课程:

class Cloaker(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  domain = db.Column(db.String(32), unique=True, nullable=False, info={
    'description': 'Raw Domain Only (no www). i.e. hello.com',
    'validators': raw_domain_validator,
  })

(Note the unique=True for domain) (请注意, 唯一=域正确)

With a form generated by WTForm: 使用WTForm生成的表单:

class CloakerForm(ModelForm):
  class Meta:
    model = Cloaker

I have the following code which handles CRUD for this model: 我有以下代码可以处理此模型的CRUD:

@cloaker_bp.route('/new/', methods=['GET', 'POST'])
@cloaker_bp.route('/<cloaker_id>/', methods=['GET', 'POST'])
def cloaker(cloaker_id=None):
  cloaker = Cloaker.query.get(cloaker_id) if cloaker_id else Cloaker()
  if request.method == 'GET':
    form = CloakerForm(obj=cloaker)
    form.populate_obj(cloaker)
  else:
    form = CloakerForm(request.form)
    if form.validate():
      form.populate_obj(cloaker)
      db.session.add(cloaker)
      db.session.commit()
      return redirect(url_for('.list_cloakers'))

  return render_template('cloaker/single.html', form=form, cloaker=cloaker)

When I update an object, I am consistently getting Already exists. 当我更新一个对象时,我一直在不断地Already exists. for domain. 用于域。

When I follow Using unique validator with existing objects on wtforms-alchemy's website: 当我在wtforms-alchemy网站上遵循对现有对象使用唯一验证器时

  ...(from the CRUD view)... 
  else:
    form = CloakerForm(obj=cloaker)
    #form = CloakerForm(request.form)
    form.populate_obj(cloaker)
    if form.validate():
      db.session.add(cloaker)
      db.session.commit()

I am getting This field is required. 我正在获取This field is required. for domain. 用于域。 I don't understand how WTForms-Alchemy is getting their data from request.form if I follow their recommendations. 如果我遵循他们的建议,我不理解WTForms-Alchemy如何从request.form获取他们的数据。

How can I get unique=True to work with my views? 如何获得唯一=正确使用我的视图?

Was having the "already exists" problem on POST/UPDATE as well. 在POST / UPDATE上也存在“已经存在”的问题。 But the doc's solution did help in my case: 但是在我的情况下, 文档的解决方案确实有所帮助:

obj = MyModel.query.get(1) form = MyForm(obj=obj) form.populate_obj(obj) form.validate()

Thanks, because this question helped me find the section in the docs. 谢谢,因为这个问题帮助我在文档中找到了该部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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