예제 #1
0
def games():
    form = AddGameForm(request.form)
    if request.method == 'POST' and form.validate():
        if models.Game.query.filter_by(
                name=form.game_name.data.lower()).first():
            flash('Game already exists')
        else:
            game = models.Game(form.game_name.data)
            models.db.session.add(game)
            models.db.session.commit()
        return redirect(url_for('games'))
    return render_template('games.html',
                           games=models.Game.query.all(),
                           form=form)
예제 #2
0
def edit_game(game_id):
    form = AddGameForm()
    if 'username' not in session:
        return redirect('/index')
    game = Game.query.filter_by(game_id=game_id).first()
    genres = [(i.genre_name, i.genre_name) for i in Genre.query.all()]
    form.genre.choices = genres
    publishers = [(i.pub_name, i.pub_name) for i in Publisher.query.all()]
    form.publisher.choices = publishers
    if form.validate_on_submit():
        if form.image.data is not None:
            filename = secure_filename(form.image.data.filename)
            server_file = 'static/img/game_images/' + filename
            form.image.data.save(server_file)
            game_image = Image.open(server_file)
            game_image = game_image.resize((300, 159), Image.ANTIALIAS)
            game_image.save(server_file)
        else:
            filename = 'unknown_game.jpg'
        game.game_name = form.game_name.data
        game.genre = form.genre.data
        game.description = form.description.data
        game.system_req = form.system_req.data
        game.price = form.price.data
        game.languages = ', '.join(form.languages.data)
        game.game_year = form.game_year.data
        game.count = form.count.data
        game.image = filename
        game.publisher = form.publisher.data
        db.session.commit()
        return redirect('/admin_games')
    '''Устанавливаем дефолтные значения полей'''
    form.genre.data = game.genre
    form.game_name.data = game.game_name
    form.description.data = game.description
    form.system_req.data = game.system_req
    form.price.data = game.price
    form.game_year.data = game.game_year
    form.count.data = game.count
    form.languages.data = game.languages.split(',')
    form.publisher.data = game.publisher
    return render_template("edit_game.html",
                           title='Редактирование игры',
                           form=form,
                           username=session['username'],
                           image=game.image)
예제 #3
0
def add_game():
    """ Страница предназначенная для добавления игр в магазин администратором """
    if 'username' not in session:
        return redirect('/login')
    if session['username'] != 'admin':
        return redirect('/index')
    form = AddGameForm()
    genres = [(i.genre_name, i.genre_name) for i in Genre.query.all()]
    publishers = [(i.pub_name, i.pub_name) for i in Publisher.query.all()]
    form.genre.choices = genres
    form.publisher.choices = publishers
    if form.validate_on_submit():
        if form.image.data is not None:
            filename = secure_filename(form.image.data.filename)
            server_file = 'static/img/game_images/' + filename
            form.image.data.save(server_file)
            game_image = Image.open(server_file)
            game_image = game_image.resize((300, 159), Image.ANTIALIAS)
            game_image.save(server_file)
        else:
            filename = 'unknown_game.jpg'
        game = Game(game_name=form.game_name.data,
                    genre=form.genre.data,
                    description=form.description.data,
                    system_req=form.system_req.data,
                    price=form.price.data,
                    languages=', '.join(form.languages.data),
                    game_year=form.game_year.data,
                    image=filename,
                    count=form.count.data,
                    publisher=form.publisher.data)
        if Game.query.filter_by(game_name=game.game_name).first():
            flash('Игра с таким названием уже существует', 'warning')
        else:
            db.session.add(game)
            db.session.commit()
            return redirect('/index')
    return render_template("add_game.html",
                           title='Добавление игры',
                           form=form,
                           username=session['username'])
예제 #4
0
파일: views.py 프로젝트: ricree/Mafiastats
def edit(request, game_id):
    game = get_object_or_404(Game, pk=game_id)
    if request.method == "POST":
        form = AddGameForm(request.POST)
        teamForm = TeamFormSetEdit(request.POST, prefix="teamForm")
        roleForm = RoleFormSet(request.POST, prefix="roleForm")
        if form.is_valid() and teamForm.is_valid() and roleForm.is_valid():
            game = Game.objects.get(pk=form.cleaned_data["game_id"])
            game.title = form.cleaned_data["title"]
            game.url = form.cleaned_data["url"]
            game.gameType = form.cleaned_data["type"]
            moderator, created = Player.objects.get_or_create(
                name=form.cleaned_data["moderator"],
                site=game.site,
                defaults={"firstGame": game, "lastGame": game, "score": 0, "played": 0},
            )
            if created:
                moderator.save()
            game.moderator = moderator
            game.start_date = form.cleaned_data["start_date"]
            game.end_date = form.cleaned_data["end_date"]
            game.save()
            game.livedToEnd.clear()
            for pName in form.cleaned_data["livedToEnd"]:
                player, created = Player.objects.get_or_create(
                    name=pName, site=game.site, defaults={"firstGame": game, "lastGame": game}
                )
                if created:
                    player.save()
                game.livedToEnd.add(player)
            for t in Team.objects.filter(game=game):
                t.delete()
            for tForm in teamForm.forms:
                if ("title" in tForm.cleaned_data) and (tForm.cleaned_data["title"] != ""):
                    title = tForm.cleaned_data["title"]
                else:
                    title = tForm.cleaned_data["type"].title()
                team = Team(
                    game=game,
                    title=title,
                    category=Category.objects.get(title=tForm.cleaned_data["type"]),
                    site=game.site,
                    won=tForm.cleaned_data["won"],
                )
                team.save()
                for pName in tForm.cleaned_data["players"]:
                    p, created = Player.objects.get_or_create(
                        name=pName,
                        site=game.site,
                        defaults={"firstGame": game, "lastGame": game, "score": 0, "played": 0},
                    )
                    p.updateDates(game)
                    p.save()
                    team.players.add(p)
                team.save()
            for role in Role.objects.filter(game=game):
                role.delete()
            for rForm in roleForm.forms:
                if rForm.has_changed():
                    p, created = Player.objects.get_or_create(
                        name=rForm.cleaned_data["player"],
                        site=game.site,
                        defaults={"firstGame": game, "lastGame": game, "score": 0, "played": 0},
                    )
                    role = Role(game=game, player=p, text=rForm.cleaned_data["text"], title=rForm.cleaned_data["title"])
                    role.save()
            game.save()
            return HttpResponseRedirect(reverse("mafiastats_game", args=[game.id]))
    else:
        game = get_object_or_404(Game, pk=game_id)
        teams = Team.objects.filter(game=game)
        dateFormat = "%m/%d/%Y"
        gameData = {
            "title": game.title,
            "url": game.url,
            "livedToEnd": [p.name for p in game.livedToEnd.all()],
            "moderator": game.moderator.name,
            "start_date": game.start_date.strftime(dateFormat),
            "end_date": game.end_date.strftime(dateFormat),
            "type": game.gameType,
            "game_id": game.id,
        }
        teamData = [
            {
                "title": team.title,
                "won": team.won,
                "type": team.category.title,
                "team_id": team.id,
                "players": [p.name for p in team.players.all()],
            }
            for team in teams
        ]
        roleData = [
            {"title": role.title, "player": role.player.name, "text": role.text}
            for role in Role.objects.filter(game=game)
        ]
        form = AddGameForm(gameData)
        teamForm = TeamFormSetEdit(initial=teamData, prefix="teamForm")
        roleForm = RoleFormSet(initial=roleData, prefix="roleForm")
    left_attrs = [("Team Name:", "title"), ("Team Type:", "type"), ("Won:", "won")]
    for tform in teamForm.forms:
        tform.left_attrs = [(label, tform[property], property) for label, property in left_attrs]
    sheets = (form.media + teamForm.media + roleForm.media).render_css()
    bodyscripts = (form.media + teamForm.media + roleForm.media).render_js()
    return render_to_response(
        "addGame.html",
        {
            "game_form": form,
            "teamFormset": teamForm,
            "roleFormset": roleForm,
            "site": game.site,
            "sheets": sheets,
            "id": game.site.id,
            "bodyscripts": bodyscripts,
            "submit_link": reverse("mafiastats_edit", args=[int(game_id)]),
        },
        context_instance=RequestContext(request),
    )
예제 #5
0
파일: views.py 프로젝트: ricree/Mafiastats
def add(request, site_id=None):
    if request.method == "POST":
        form = AddGameForm(request.POST)
        teamFormset = TeamFormSet(request.POST, prefix="teamForm")
        roleFormset = RoleFormSet(request.POST, prefix="roleForm")
        if form.is_valid() and teamFormset.is_valid() and roleFormset.is_valid():
            try:
                # return HttpResponse(formset.forms[0].cleaned_data['players'])
                print "adding game to site", site_id
                print "Sites are", Site.objects.all()
                print "Players are", Player.objects.all()
                site = Site.objects.get(pk=site_id)
                name = teamFormset.forms[0].cleaned_data["players"]
                moderator, created = Player.objects.get_or_create(name=form.cleaned_data["moderator"], site=site)
                if created:
                    moderator.save()
                else:
                    moderator.clearCache()
                game = Game(
                    title=form.cleaned_data["title"],
                    moderator=moderator,
                    start_date=form.cleaned_data["start_date"],
                    end_date=form.cleaned_data["end_date"],
                    site=site,
                    gameType=form.cleaned_data["type"],
                )

                if form.cleaned_data["url"] is not "":
                    game.url = form.cleaned_data["url"]
                game.save()
                for pName in form.cleaned_data["livedToEnd"]:
                    player, created = Player.objects.get_or_create(
                        name=pName, site=site, defaults={"firstGame": game, "lastGame": game, "score": 0, "played": 1}
                    )
                    player.save()
                    game.livedToEnd.add(player)
                for tForm in teamFormset.forms:
                    if ("title" in tForm.cleaned_data) and (tForm.cleaned_data["title"] != ""):
                        title = tForm.cleaned_data["title"]
                    else:
                        title = tForm.cleaned_data["type"].title()
                    category = Category.objects.get(title=tForm.cleaned_data["type"])
                    # 				category = tForm.cleaned_data['type']
                    won = tForm.cleaned_data["won"]
                    players = [
                        Player.objects.get_or_create(name=p, site=site, defaults={"firstGame": game, "lastGame": game})[
                            0
                        ]
                        for p in tForm.cleaned_data["players"]
                    ]
                    for p in players:
                        p.save()
                    team = Team(title=title, category=category, site=site, won=won, game=game)
                    team.save()
                    for p in players:
                        team.players.add(p)
                        p.updateDates(game)
                        p.clearCache()
                    team.save()
                    game.team_set.add(team)
                for rForm in roleFormset.forms:
                    if rForm.has_changed():
                        title = rForm.cleaned_data["title"]
                        pName = rForm.cleaned_data["player"]
                        text = rForm.cleaned_data["text"]
                        player, created = Player.objects.get_or_create(
                            name=pName, site=site, defaults={"firstGame": game, "lastGame": game}
                        )
                        role, created = Role.objects.get_or_create(title=title, game=game, player=player, text=text)
                        role.save()
                game.save()
                return HttpResponseRedirect(reverse("mafiastats_game", args=[game.id]))
            except Exception as e:
                logging.exception(e.args[0])
                raise  # let the default behavior handle the error, we just want to log it
    else:
        form = AddGameForm()
        teamFormset = TeamFormSet(prefix="teamForm")
        roleFormset = RoleFormSet(prefix="roleForm")

    def boxIfString(val):  # render either returns an iterable or
        if type(val) is str:  # a string.  a string screws with the template
            retval = [val]  # so we must box strings up in a list
        else:
            retval = val
        return retval

    sheets = boxIfString((form.media + teamFormset.media).render_css())
    bodyscripts = boxIfString((form.media + teamFormset.media).render_js())
    if site_id:
        site = Site.objects.get(pk=site_id)
    else:
        site = None
    left_attrs = [("Team Name:", "title"), ("Team Type:", "type"), ("Won:", "won")]
    for tform in teamFormset.forms:
        tform.left_attrs = [(label, tform[property], property) for label, property in left_attrs]
    return render_to_response(
        "addGame.html",
        {
            "game_form": form,
            "roleFormset": roleFormset,
            "teamFormset": teamFormset,
            "bodyscripts": bodyscripts,
            "sheets": sheets,
            "site": site,
            "id": site_id,
            "submit_link": reverse("mafiastats_add", args=[site_id]),
        },
        context_instance=RequestContext(request),
    )