简体   繁体   English

如何将数据库中的特定值显示为第一个下拉列表选择选项

[英]How to display a specific value from a database as the first drop-down list selection option

I have an application which takes in user data, saves it to a database, and then allows users to edit that data.我有一个应用程序,它接收用户数据,将其保存到数据库中,然后允许用户编辑该数据。 I have one variable which is populated using a drop-down list.我有一个使用下拉列表填充的变量。 When users go to edit data, I would like their selection from the database to show at the top of the drop-down list.当用户 go 编辑数据时,我希望他们从数据库中的选择显示在下拉列表的顶部。 For example, if they created a new user (Jane Smith) for company "CoolCompany" and is now editing Jane Smith, I'd like it to show "CoolCompany" as the first drop-down list selection.例如,如果他们为公司“CoolCompany”创建了一个新用户(Jane Smith)并且现在正在编辑 Jane Smith,我希望它显示“CoolCompany”作为第一个下拉列表选择。 Currently it's showing the list in alphabetical order ("AwesomeCompany").目前它按字母顺序显示列表(“AwesomeCompany”)。 I suspect this is because of the way my AddUserForm is set up.我怀疑这是因为我的 AddUserForm 的设置方式。 Can I adjust that in my view?我可以在我看来调整它吗? We have enough companies listed that it needs to stay alphabetical when users add data.我们列出了足够多的公司,当用户添加数据时,它需要保持字母顺序。

Models:楷模:

from location import db
from location.folders.models import Company

class ProductUsers(db.Model):
    __table__ = db.Model.metadata.tables['product_users']
  
    company = db.relationship('Company', foreign_keys='ProductUsers.prod_id')

    def __init__(self, first_nm, last_nm, prod_id):

        self.first_nm = first_nm
        self.last_nm = last_nm
        self.prod_id = prod_id

    def get_id(self):
        return int(self.prod_user_key)

Forms: Forms:

from location.otherfolders.models import ProductUsers
from location.folders.models import Company

class AddUsersForm(FlaskForm):
    company = SelectField(
        'Company*', 
        validators=[DataRequired()],
        choices=[(comp.prod_id, comp.comp_display_name) for comp in Company.query.filter(Company.member_status!=500).order_by('comp_display_name').all()])
    first_nm = StringField('First Name*', validators=[DataRequired()])
    last_nm = StringField('Last Name*', validators=[DataRequired()])
   
    submit = SubmitField('Submit User')

class UpdateProductUserForm(AddUsersForm):
    first_nm = StringField('First Name*', validators=[DataRequired()])
    last_nm = StringField('Last Name*', validators=[DataRequired()])

    disable = SubmitField('Deactivate')

Views to update user:更新用户的视图:

from location.otherfolders.models import ProductUsers
from location.folders.models import Company

from location.otherfolders.forms import AddUsersForm, UpdateProductUserForm

approvals = Blueprint('approvals', __name__)

@approvals.route('/productapproval/addproductUser/<int:prod_user_key>', methods=['GET', 'POST'])
def edit_product_users(prod_user_key):
    
    productUser = ProductUsers.query.get_or_404(prod_user_key)

    form = UpdateProductUserForm()

    if form.validate_on_submit():

        productUser = ProductUsers.query.filter_by(prod_user_key=prod_user_key).first()

        productUser.org_id = form.company.data
        productUser.first_nm = form.first_nm.data
        productUser.last_nm = form.last_nm.data
   
        db.session.commit()

        flash('User Account Updated', 'success')

        return redirect(url_for('approvals.users', prod_user_key=prod_user_key))

    form.company.data = productUser.prod_id
    form.first_nm.data = productUser.first_nm
    form.last_nm.data = productUser.last_nm


    return render_template('/productapproval/addusers.html', form=form)

Template:模板:

{% extends "base.html" %}

{% block form_content %}

<form class="form form-horizontal" method="POST">

  {{ form.hidden_tag() }}

  <div class="form-group row">
    {{ form.company.label(class="col-sm-3 col-form-label font-weight-bold") }}
    <div class="col-sm-9">
      {{ form.company(class="listStyleComp") }}
    </div>
  </div>

  <div class="form-group row">
    {{ form.first_nm.label(class="col-sm-3 col-form-label font-weight-bold") }}
    <div class="col-sm-9">
      {{ form.first_nm(class="form-control sm-text listStyleComp", placeholder="First Name") }}
    </div>
  </div>

  <div class="form-group row">
    {{ form.last_nm.label(class="col-sm-3 col-form-label font-weight-bold") }}
    <div class="col-sm-9">
      {{ form.last_nm(class="form-control sm-text listStyleComp", placeholder="Last Name") }}
    </div>
  </div>

<!-- BUTTONS -->
 <div class="form-group row">
  <div class="col-sm-10">
    {{ form.submit(class="btn btn-success") }}
  </div>
</div>

</form>

{% endblock %}

First, I think you are missing the company field from your UpdateProductUserForm .首先,我认为您缺少UpdateProductUserForm中的company字段。

Add that in there:在那里添加:

class UpdateProductUserForm(AddUsersForm):
    first_nm = StringField('First Name*', validators=[DataRequired()])
    last_nm = StringField('Last Name*', validators=[DataRequired()])
    company = SelectField('Company*', validators=[DataRequired()], choices=[])
    disable = SubmitField('Deactivate')

Notice that we define it as an empty list.请注意,我们将其定义为一个空列表。 Then we update it however we want in the view:然后我们更新它,但是我们想要在视图中:

@approvals.route('/productapproval/addproductUser/<int:prod_user_key>', methods=['GET', 'POST'])
def edit_product_users(prod_user_key):
    
    productUser = ProductUsers.query.get_or_404(prod_user_key)

    # get all the companies
    companies = [comp.prod_id for comp in Company.query.filter(Company.member_status!=500).all()]
 
    # move current company item to start of list
    current_company_index = companies.index(productUser.prod_id)
    companies.insert(0, companies.pop(current_company_index))

    form = UpdateProductUserForm()
    form.company.choices = companies
    form.first_nm.data = productUser.first_nm
    form.last_nm.data = productUser.last_nm

    if form.validate_on_submit():
        productUser.org_id = form.company.data
        productUser.first_nm = form.first_nm.data
        productUser.last_nm = form.last_nm.data

        db.session.add(productUser)
        db.session.commit()
        flash('User Account Updated', 'success')

        return redirect(url_for('approvals.users', prod_user_key=prod_user_key))

    return render_template('/productapproval/addusers.html', form=form)

I noticed you were fetching the user twice.我注意到您正在获取用户两次。 You don't need to do that.你不需要这样做。 Also you weren't properly adding the updated user to the database session.此外,您没有正确地将更新的用户添加到数据库 session。 I've fixed those things in the above code.我已经在上面的代码中修复了这些东西。

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

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