Roman
Roman

Reputation: 3941

Python Flask SQLalchemy Foreign key isn't saved in database - One to Many

So I have a form where a user can submit a room, ofcourse a user should be able to submit multiple rooms, but the rooms all belong to this user, so we have a one-to-many relation here (for understanding):

room1 - foreignkey(user1) room2 - foreignkey(user1)

The problem:

When submiting the form, the database recognizes that there is a foreignkey function but the users_id is empty, but there should be the actual id of the user who submited the room.

enter image description here

The code:

I try to show only relevant pieces

Here are my models:

class User(UserMixin, Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)

    # foreign key
    addresses = relationship('Zimmer', back_populates="users")

class Zimmer(Base):
    __tablename__ = 'zimmer'
    id = Column(Integer, primary_key=True)

    # foreign key
    users_id = Column(Integer, ForeignKey('users.id'))
    users = relationship("User", back_populates="addresses")

That is the code which populates the database:

@app.route("/zimmer_einstellen", methods=['GET', 'POST'])
@login_required
@check_confirmed
def zimmer_einstellen():
    form = ZimmerForm()
    if form.validate_on_submit():
        new_zimmer = Zimmer(art=form.art.data, personen=form.personen.data,              preis=form.preis.data, infofeld=form.infofeld.data, land=form.land.data, bundesland=form.bundesland.data,
                    stadt=form.stadt.data, strasse=form.strasse.data, hausnr=form.hausnr.data, haustiere_erlaubt=form.haustiere_erlaubt.data,
                    bettwaesche_wird_gestellt=form.bettwaesche_wird_gestellt.data, grill_vorhanden=form.grill_vorhanden.data, safe_vorhanden=form.safe_vorhanden.data, kuehlschrank_vorhanden=form.kuehlschrank_vorhanden.data, rauchen_erlaubt=form.rauchen_erlaubt.data, 
                    parkplatz_vorhanden=form.parkplatz_vorhanden.data, kochmoeglichkeit_vorhanden=form.kochmoeglichkeit_vorhanden.data, restaurant_im_haus_vorhanden=form.restaurant_im_haus_vorhanden.data, handtuecher_werden_gestellt=form.handtuecher_werden_gestellt.data, tv_vorhanden=form.tv_vorhanden.data, 
                    waschmoeglichkeit_vorhanden=form.waschmoeglichkeit_vorhanden.data, wlan_vorhanden=form.wlan_vorhanden.data)

    if new_zimmer:
        db_session.add(new_zimmer)
        db_session.commit()

        flash('Zimmer wurde erfolgreich eingestellt')
        return redirect(url_for('zimmer_einstellen'))
    else:
            flash('Etwas ist schief gelaufen mit dem Einstellen des Zimmers')
return render_template('zimmer_einstellen.html', form=form)

But as far as I understand it should be enough to create the foreign key relation and that should be it.

Or do I have to use something like an additional hidden tag in the actual form in html, here is generally what I use (without all the other inputs):

<form id="regi" method="POST" action="{{ url_for('zimmer_einstellen', next=request.args.get('next')) }}">
{{ form.hidden_tag() }}
<div class="form-group">
   {{ form.art.label }} 
   {{ form.art(size=30, class = "form-control") }} 
</div>


 </div>
 <div class="col-lg-12 col-md-12">
 <button type="submit" class="btn btn-success"> Zimmer einstellen </button>
 </div>

Upvotes: 1

Views: 533

Answers (1)

Amin Alaee
Amin Alaee

Reputation: 1915

If I understand your problem correctly, you have not created a Zimmer object with a proper users_id: You need to do something like this:

new_zimmer = Zimmer(..., users_id=user_id)

And since you don't have access to the users_id, you need to get it. One option as you mentioned is putting it in your html as a hidden input and getting it in zimmer_einstellen function.

UPDATE: From your User declaration I guess you're using the Flask-Login extension which provides a current_user in your application. If that's the case, you can use current_user.id in your views to get the current user's id.

Upvotes: 1

Related Questions