我有一个具有表组织和另一个表站点的数据库。如何使用Flask-WTF将创建的新站点映射到组织

时间:2019-06-12 09:49:55

标签: python-3.x flask flask-sqlalchemy flask-wtforms

我已经建立了一对多关系,但是我不确定如何将下拉菜单中选择的组织与已创建的新站点详细信息一起发布。

基本页面布局将被下拉,其中包含已经创建并存储在数据库的组织表中的组织名称。最终用户选择一个组织,然后为站点键入新名称,然后单击提交。

代码在下面,非常感谢您的帮助。

App.py

    $science = Auth::user()->science_id;

    $client = new Client(['headers' => ['Accept' => 'application/json']]);

    $request = $client->get(
        'https://url_to_the_api/'.$science.'/degree',
        [
            'auth'          => ['client', 'secret'],
        ]

    );

    $data = $request->getBody()->getContents();

    return $data;

forms.py


@app.route('/add_site')
def add_site():
    """ Find and show field from db for the user to fill in """

    form = AddSite()
    organisations = db.session.query(Organisation)
    return render_template('add_site.html', form=form, 
    organisations=organisations)


@app.route('/insert_site', methods=['GET', 'POST'])
def insert_site():
    """ Insert populated fills from add_site to db """

    form = AddSite()
    site_name = Site(site_name=form.site_name.data)
    db.session.add(site_name)
    db.session.commit()
    return redirect(url_for('get_org'))

Models.py

class AddSite(FlaskForm):
    """ Adding new site """

    site_name = StringField('Site Name', validators=[DataRequired()])
    submit = SubmitField('Add Site')

add_site.html

class Organisation(db.Model):
    """ Table to store organisation details """

    id = db.Column(db.Integer, primary_key=True, index=True, 
    unique=True)
    org_name = db.Column(db.String())
    timestamp = db.Column(db.DateTime, index=True, 
    default=datetime.utcnow)
    sites = db.relationship('Site', backref='org_name', lazy='dynamic')

    def __init__(self, org_name):
        self.org_name = org_name


class Site(db.Model):
    """ Table to store site details """

    id = db.Column(db.Integer, primary_key=True)
    site_name = db.Column(db.String())
    timestamp = db.Column(db.DateTime, index=True, 
    default=datetime.utcnow)
    org_id = db.Column(db.Integer, db.ForeignKey('organisation.id'))

    def __init__(self, site_name):
        self.site_name = site_name

最终结果是将多个站点映射到组织。这样一来,我可以创建一个页面,其中将显示组织下的所有站点。

1 个答案:

答案 0 :(得分:0)

在您的脚本中尝试

App.py

std::any

forms.py

from flask import (request, render_template, redirect_url,
                   url_for)
from app.Models import db, Site  # Use proper import here for your app


@app.route('/add_site', methods=['GET', 'POST'])
def add_site():
    form = AddSite(request.form)
    if request.method == 'POST' and form.validate():
        site = Site(
            site_name=form.site_name.data,
            org_id=form.organisation.data
        )
        db.session.add(site)
        db.session.commit()
        return redirect(url_for('get_org'))
    return render_template('add_site.html', form=form)

Models.py

from flask_wtf import FlaskForm as Form
from wtforms import (SelectField, StringField, SubmitField)
from wtforms.validators import DataRequired as Required
from app.Models import Organisation  # Use proper import here for your app


class AddSite(Form):
    """ Adding new site """

    site_name = StringField('Site Name',
                            validators=[Required('Site name is required')])
    organisation = SelectField('Organisation', coerce=int,
                               validators=[
                                   Required('Please select an organisation')])
    submit = SubmitField('Add Site')

    def __init__(self, *args, **kwargs):
        super(AddSite, self).__init__(*args, **kwargs)
        organisations = Organisation.query.with_entities(
            Organisation.id, Organisation.org_name). \
            order_by(Organisation.org_name).all()
        self.organisation.choices = [
            (organisation.id, organisation.org_name)
            for organisation in organisations
        ]

add_site.html

class Organisation(db.Model):
    """ Table to store organisation details """

    __tablename__ = 'organisation'

    id = db.Column(db.Integer, primary_key=True)
    org_name = db.Column(db.String(100))
    timestamp = db.Column(db.DateTime, index=True,
                          default=datetime.utcnow)
    sites = db.relationship('Site', backref='organisation', lazy='dynamic')

    def __repr__(self):
        return '<Organisation: {!r}'.format(self.org_name)


class Site(db.Model):
    """ Table to store site details """

    __tablename__ = 'site'

    id = db.Column(db.Integer, primary_key=True)
    site_name = db.Column(db.String())
    timestamp = db.Column(db.DateTime, index=True,
                          default=datetime.utcnow)
    org_id = db.Column(db.Integer, db.ForeignKey('organisation.id'))

    def __repr__(self):
        return '<Site: {!r}'.format(self.site_name)