kvesteri / wtforms-alchemy

Tools for creating wtforms from sqlalchemy models
Other
245 stars 59 forks source link

Unique Validator not working for Update #116

Open vincentwhales opened 7 years ago

vincentwhales commented 7 years ago

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:

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

I have the following code which handles CRUD for this model:

@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. for domain.

When I follow Using unique validator with existing objects on wtforms-alchemy's website:

  ...(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. for domain. I don't understand how WTForms-Alchemy is getting their data from request.form if I follow their recommendations.

How can I get unique=True to work with my views?

spraetz commented 6 years ago

I am having the exact same problem right now.

scath999 commented 2 years ago

This still doesn't work properly.

The help at https://wtforms-alchemy.readthedocs.io/en/latest/validators.html is confusing (and grammatically incorrect).

It looks like the PR submitted by @GregoryVigoTorres was either closed before merging, or did not properly address this particular issue.

Can we get some guidance on how updating records with validators that require uniqueness of row entries are supposed to work?

iameru commented 2 years ago

I second this. It should be a rather straight forward thing to update an existing entry. The provided Information does not work.

It happens quite often that a table with a unique value exists and needs to get changed, this could be more straightforward. But functioning or accurate documentation would be a good step.

edit: sorry was having a hickup. I validated BEFORE populating the obj.