Tilføj group_exist, ændre insert_group i models.py

insert_group returnere den tilføjet gruppe. Så man kan tilføje brugeren til den nyoprettet gruppe
This commit is contained in:
Mikkel
2022-06-02 09:23:32 +02:00
parent dfc925d5c2
commit 9d02b2529a
2 changed files with 18 additions and 11 deletions

View File

@ -1,6 +1,6 @@
from flask import render_template, Blueprint, flash, redirect
from flask_login import current_user, login_required
from aula.models import get_group, insert_group
from aula.models import get_group, insert_group, group_exist
from aula.forms import CreateThreadForm, CreateGroupForm, CreatePostForm
Group = Blueprint('Group', __name__)
@ -30,10 +30,15 @@ def show(group_id):
def create():
form = CreateGroupForm()
if insert_group(form.title.data, form.mandatory.data):
flash('Gruppen blev oprettet', 'success')
else:
# Make sure we dont try to create group with same name as others
# Since name has UNIQUE constraint.
if group_exist(form.title.data):
flash('En gruppe med det navn findes allerede', 'danger')
return redirect(f"/groups")
group = insert_group(form.title.data, form.mandatory.data)
current_user.join_group(group.group_id)
flash('Gruppen blev oprettet', 'success')
return redirect(f"/groups")
@Group.route("/groups/join/<int:group_id>", methods=['GET'])

View File

@ -332,24 +332,26 @@ def insert_thread(group_id, title):
conn.commit()
cur.close()
def insert_group(name, mandatory):
# Make sure we dont try to create group with same name as others
# Since name has UNIQUE constraint.
def group_exist(name):
cur = conn.cursor()
sql = """
SELECT COUNT(*) FROM groups WHERE name = %s
"""
cur.execute(sql, (name,))
if cur.fetchone()[0] > 0: return False
return cur.fetchone()[0] > 0
# Do insertion
def insert_group(name, mandatory):
cur = conn.cursor()
sql = """
INSERT INTO groups(name, mandatory) VALUES (%s, %s)
INSERT INTO groups(name, mandatory) VALUES (%s, %s) RETURNING *
"""
cur.execute(sql, (name, mandatory))
result = Group(cur.fetchone()) if cur.rowcount > 0 else None
conn.commit()
cur.close()
return True
return result
def insert_post(group_id, author_id, title, content):
cur = conn.cursor()