Exemplo n.º 1
0
def register(request):
  if request.method == "POST":
    data = json.loads(request.raw_post_data)
    uForm = UserForm(data = data)
    pForm = ProfileForm(data = data)
    aForm = None 
    if data['artist']:
      aForm = ArtistForm(data = data)
    if uForm.is_valid() and pForm.is_valid() and (aForm == None or aForm.is_valid()):
      user = uForm.save()
      user.save()
      profile = pForm.save(commit = False)
      profile.user = user
      if not profile.invites:
        profile.invites = 0
      profile.save()
      if aForm:
        artist = aForm.save(commit = False)
        artist.profile = profile
        artist.save()
      user = authenticate(username = data['username'],
                          password = data['password1'])
      login(request, user)
      resp = HttpResponse(json.dumps({'success': 'true'}), mimetype="application/json")
      resp.status_code = 201
      return resp 
    else:
      error = dict(uForm.errors.items()
                  + pForm.errors.items())
  else:
    error = "The request must be a POST"
  resp = HttpResponse(json.dumps({'error': error}), mimetype="applcation/json")
  resp.status_code = 400
  return resp
Exemplo n.º 2
0
def edit_artist_submission(artist_id):
    error_msg = ''
    try:
        f = request.form
        af = ArtistForm(f)
        if not af.validate():
            for key, val in af.errors.items():
                error_msg += key + ": " + ';'.join(val)
        assert af.validate()
        at = Artist.query.get(artist_id)
        at.name = f["name"]
        at.city = f["city"]
        at.state = f["state"]
        at.phone = f["phone"]
        at.facebook_link = f["facebook_link"]
        at.website = f["website"]
        at.image_link = f["image_link"]
        at.seeking_venue = bool('seeking_venue' in f)
        at.seeking_description = f['seeking_description']
        g_ids = [int(i) for i in f.getlist('genres')]
        at.genres = db.session.query(Genre).filter(Genre.id.in_(g_ids)).all()
        db.session.commit()
    except AssertionError:
        db.session.rollback()
        print(sys.exc_info())
        flash('The form is invalid.' + error_msg)
    except SQLAlchemyError:
        db.session.rollback()
        print(sys.exc_info())
        flash('A database error occurred. This artist could not be updated.')
    finally:
        db.session.close()

    return redirect(url_for('rt.show_artist', artist_id=artist_id))
Exemplo n.º 3
0
def create_artist_submission():
    error = False
    form = ArtistForm()
    try:
        if form.validate_on_submit():
            if form.seeking_venue.data == 'True':
                seeking = True
            else:
                seeking = False
            artist = Artist(name=form.name.data,
                            city=form.city.data,
                            state=form.state.data,
                            phone=form.phone.data,
                            image_link='',
                            facebook_link=form.facebook_link.data,
                            genres=form.genres.data,
                            website=form.website.data,
                            seeking_venue=seeking,
                            seeking_description=form.seeking_description.data)
            db.session.add(artist)
            db.session.commit()
            flash('Artist {} was successfully listed!'.format(form.name.data))
            return redirect(url_for('index'))
        flash('An error occurred. Artist {} could not be listed. {}'.format(
            form.name.data, form.errors))
    except ():
        db.session.rollback()
        error = True
        print(sys.exc_info())
    finally:
        db.session.close()
    if error:
        abort(500)
        flash('There was an error, please try again.')
    return render_template('forms/new_artist.html', form=form)
Exemplo n.º 4
0
def edit_artist(artist_id):
    at = Artist.query.get(artist_id)
    artist = {
        "id": at.id,
        "name": at.name,
        "city": at.city,
        "state": at.state,
        "phone": at.phone,
        "website": at.website,
        "facebook_link": at.facebook_link,
        "seeking_venue": at.seeking_venue,
        "seeking_description": at.seeking_description,
        "image_link": at.image_link,
        "genres": [g.id for g in at.genres]
    }
    form = ArtistForm(**artist)
    error_msg = ''
    form.validate()
    for key, val in form.errors.items():
        if key != 'csrf_token':
            error_msg += key + ": " + ';'.join(val)
    if error_msg:
        flash(
            'There are few errors in the old artist info. Please fix them first! '
            + error_msg)

    return render_template('forms/edit_artist.html', form=form, artist=artist)
Exemplo n.º 5
0
def create_artist_submission():
    # validate form
    form = ArtistForm(request.form)
    if not form.validate():
        return render_template('forms/new_artist.html', form=form)

    # create artist
    error = False
    try:
        artist = Artist()
        artist.set_data(form_data=request.form)
        db.session.add(artist)
        db.session.commit()
    except:
        error = True
        db.session.rollback()
        print(sys.exc_info())
    finally:
        db.session.close()

    if error:
        flash('An error occurred. Artist ' + request.form.get('name', '') +
              ' could not be listed.')
    else:
        flash('Artist ' + request.form.get('name', '') +
              ' was successfully listed!')

    return render_template('pages/home.html')
Exemplo n.º 6
0
def edit_artist(artist_id):
    # it must be imported here to avoid circular import
    from forms import ArtistForm
    artist = Artist.query.get_or_404(artist_id)
    form = ArtistForm(obj=artist)
    artist_name = artist.name
    if form.validate_on_submit():
        form.populate_obj(artist)
        try:
            db.session.add(artist)
            db.session.commit()
        except SQLAlchemyError:
            flash('An error occurred. Artist ' + artist_name +
                  ' could not be edited.')
            print(sys.exc_info())
            db.session.rollback()
            db.session.close()
            return render_template('forms/edit_artist.html',
                                   form=form,
                                   artist_name=artist_name)
        return redirect(url_for('show_artist', artist_id=artist_id))

    return render_template('forms/edit_artist.html',
                           form=form,
                           artist_name=artist_name)
Exemplo n.º 7
0
def create_artist_submission():
    form = ArtistForm()
    if form.validate_on_submit():
        try:
            artist = Artist()
            artist.name = request.form['name']
            artist.city = request.form['city']
            artist.state = request.form['state']
            artist.phone = request.form['phone']
            artist.image_link = request.form['image_link']
            artist.genres = request.form.getlist('genres')
            artist.facebook_link = request.form['facebook_link']
            artist.website = request.form['website']
            artist.seeking_venue = True if 'seeking_venue' in request.form else False
            artist.seeking_description = request.form['seeking_description']
            db.session.add(artist)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            flash(
                'An error occurred. Artist {} Could not be listed!, {}'.format(
                    request.form['name'], str(e)))
        finally:
            db.session.close()
            flash('Artist {} was successfully listed!'.format(
                request.form['name']))
            return redirect(url_for('artists'))
    return render_template('forms/new_artist.html', form=form)
Exemplo n.º 8
0
Arquivo: app.py Projeto: adengz/fyyur
def edit_artist_submission(artist_id):
    artist = Artist.query.get(artist_id)
    if Artist is None:
        abort(404)
    name = Artist.name
    form = ArtistForm()
    if not form.validate_on_submit():
        flash('Invalid value found in ' + ', '.join(form.errors.keys()) +
              ' field(s).')
        return render_template('forms/edit_artist.html',
                               form=form,
                               artist=artist)
    else:
        error = False
        try:
            edited = Artist()
            form.populate_obj(edited)
            for col in Artist.__table__.columns.keys():
                if col != 'id':
                    setattr(artist, col, getattr(edited, col))
            name = artist.name
            artist.phone = format_phone(artist.phone)
            db.session.commit()
        except:
            error = True
            db.session.rollback()
        finally:
            db.session.close()
        if error:
            flash('An error occurred. Artist ' + name +
                  ' could not be updated.')
            return redirect(url_for('index'))
        else:
            flash('Artist ' + name + ' was successfully updated!')
            return redirect(url_for('show_artist', artist_id=artist_id))
Exemplo n.º 9
0
def create_artist():
    """Either load the blank form or submit a filled form to create a new artist."""

    form = ArtistForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            artist = Artist(name=form.name.data,
                            genres=json.dumps(form.genres.data),
                            city=form.city.data,
                            state=form.state.data,
                            phone=form.phone.data,
                            facebook_link=form.facebook_link.data,
                            website=form.website.data,
                            seeking_venue=form.seeking_venue.data,
                            seeking_description=form.seeking_description.data,
                            email=form.email.data,
                            image_link=form.image_link.data)
            try:
                db.session.add(artist)
                db.session.commit()
                message = f'Artist {artist.name} was successfully listed!', 'info'
            except:
                db.session.rollback()
                message = f'An error occurred. Artist {artist.name} could not be listed.', 'danger'

            flash(*message)
            return redirect(url_for('index'))
        else:
            errors = form.errors
            for e in errors:
                flash(f'{e}: {errors[e][0]}', 'danger')
    return render_template('forms/new_artist.html', form=form)
Exemplo n.º 10
0
def create_artist_submission():
  # called upon submitting the new artist listing form
  form = ArtistForm(request.form)
  # TODO: insert form data as a new Venue record in the db, instead
  if form.validate_on_submit():
    try:
      name = form.name.data
      city = form.city.data
      state = form.state.data
      phone = form.phone.data
      facebook_link = form.facebook_link.data
      genres = form.genres.data
      image_link = form.image_link.data
      website = form.website.data
      seeking_venue = form.seeking_venue.data
      seeking_description = form.seeking_description.data
      artist = Artist(name=name, city=city, state=state, phone=phone, facebook_link=facebook_link, genres=genres,
      image_link=image_link, website=website, seeking_venue=bool(seeking_venue), seeking_description=seeking_description)
      db.session.add(artist)
      db.session.commit()
    # TODO: modify data to be the data object returned from db insertion
    # on successful db insert, flash success
      flash('Artist ' + request.form['name'] + ' was successfully listed!')
    # TODO: on unsuccessful db insert, flash an error instead.
    except:
      flash('An error occurred. Artist ' + form.name.data + ' could not be listed.')
      db.session.rollback()
      print(sys.exc_info())
    finally:
      db.session.close()
    return render_template('pages/home.html')
  else:
    print(form.errors)
    return render_template('forms/new_artist.html', form=form)
Exemplo n.º 11
0
def edit_artist_submission(artist_id):
  form = ArtistForm(request.form)
  # TODO: take values from the form submitted, and update existing
  if form.validate_on_submit():
    try:
      a = db.session.query(Artist).get(artist_id)
      a.name = form.name.data
      a.city = form.city.data
      a.state = form.state.data
      a.phone = form.phone.data
      a.facebook_link = form.facebook_link.data
      a.genres = form.genres.data
      a.image_link = form.image_link.data
      a.website = form.website.data
      a.seeking_venue = bool(form.seeking_venue.data)
      a.seeking_description = form.seeking_description.data
    # artist record with ID <artist_id> using the new attributes
      db.session.commit()
      flash('Artist ' + request.form['name'] + ' was successfully updated!')
    # TODO: on unsuccessful db insert, flash an error instead.
    except:
      flash('An error occurred. Artist ' + form.name.data + ' could not be updated.')
      db.session.rollback()
      print(sys.exc_info())
    finally:
      db.session.close()
    return redirect(url_for('show_artist', artist_id=artist_id))
  else:
    print(form.errors)
    return render_template('forms/edit_artist.html', form=form)
Exemplo n.º 12
0
def edit_artist(artist_id):
    artist = Artist.query.get(artist_id)
    form = ArtistForm(obj=artist)
    if form.validate():
        form.populate_obj(artist)
    # TODO: populate form with fields from artist with ID <artist_id>
    return render_template("forms/edit_artist.html", form=form, artist=artist)
Exemplo n.º 13
0
Arquivo: app.py Projeto: jurayev/fyyur
def edit_artist_submission(artist_id):
    form = ArtistForm()

    if form.validate_on_submit():
        data = request.form
        try:
            is_seeking_venue = True if data['seeking_description'].strip(
            ) else False
            artist = Artist.query.get(artist_id)
            artist.name = data['name']
            artist.city = data['city']
            artist.state = data['state']
            artist.genres = request.form.getlist('genres')
            artist.phone = data['phone']
            artist.image_link = data['image_link']
            artist.facebook_link = data['facebook_link']
            artist.website = data['website']
            artist.seeking_venue = is_seeking_venue
            artist.seeking_description = data['seeking_description']
            db.session.commit()
            flash(f'Artist {data["name"]} was successfully edited!')
        except:
            db.session.rollback()
            flash(
                f'An error occurred. Artist {data["name"]} could not be edited.'
            )
        finally:
            db.session.close()
    # Flashing form validation errors
    for input, errors in form.errors.items():
        flash(f'Invalid value for "{input}". {"".join(errors)}')

    return redirect(url_for('show_artist', artist_id=artist_id))
def edit_artist_submission(artist_id):
    """ Submit call back for edit artist form """
    # Get form data
    name = request.form['name']
    city = request.form['city']
    state = request.form['state']
    phone = request.form['phone']
    image_link = request.form['image_link']
    facebook_link = request.form['facebook_link']
    website = request.form['website']
    seeking_venue = request.form['seeking_venue'] == 'Yes'
    seeking_description = request.form['seeking_description']
    # genres is a list
    genres = request.form.getlist('genres')

    form = ArtistForm()
    # Validate form data
    if not form.validate_on_submit():
        flash(form.errors)
        return redirect(url_for('edit_artist_submission'))

    error = False
    try:
        # Update artist instance with form data
        artist = Artist.query.get(artist_id)
        artist.name = name
        artist.city = city
        artist.state = state
        artist.phone = phone
        artist.image_link = image_link
        artist.facebook_link = facebook_link
        artist.website = website
        artist.seeking_venue = seeking_venue
        artist.seeking_description = seeking_description
        db.session.add(artist)

        # Delete old generes
        for x in artist.genres:
            db.session.delete(x)

        # Creating Artist generes instances and assigning using backref
        for genre in genres:
            new_genre = ArtistsGenres(genre=genre)
            new_genre.artist = artist  # backref
            db.session.add(new_genre)

        db.session.commit()
    except Exception as err:
        print(err)
        db.session.rollback()
        error = True
    finally:
        db.session.close()

    if error:
        flash(f'An error occurred. Artist {name} could not be updated.')
        abort(500)

    flash(f'Artist {name} updated successfully')
    return redirect(url_for('show_artist', artist_id=artist_id))
Exemplo n.º 15
0
def create_artist_submission():
  # called upon submitting the new artist listing form
  # TODO: insert form data as a new Venue record in the db, instead
  # TODO: modify data to be the data object returned from db insertion
  # TODO: on unsuccessful db insert, flash an error instead.
  # e.g., flash('An error occurred. Artist ' + data.name + ' could not be listed.')

  form = ArtistForm(request.form, meta = {'csrf': False})
  if form.validate():
    try:
      artist = Artist()
      form.populate_obj(artist)
      db.session.add(artist)
      db.session.commit()
      flash('Artist ' + request.form['name'] + ' was successfully listed!')
    except ValueError as e:
      print(e)
      flash('Error in listing artist. Please try again.')
      db.session.rollback()
    finally:
      db.session.close()
  else:
    err_msg = []
    for field, err in form.errors.items():
      err_msg.append(field + '-' + '|'.join(err))
    flash('Errors: ' + str(err_msg))

  return render_template('pages/home.html')
Exemplo n.º 16
0
def edit_artist_submission(artist_id):
    artist = Artist.query.get(artist_id)
    form = ArtistForm()
    error = False
    try:
        if form.validate_on_submit():
            artist.name = form.name.data
            artist.genres = form.genres.data
            artist.city = form.city.data
            artist.state = form.state.data
            artist.phone = form.phone.data
            artist.website = form.website.data
            artist.facebook_link = form.facebook_link.data
            artist.seeking_venue = form.seeking_venue.data
            artist.seeking_description = form.seeking_description.data
            artist.image_link = form.image_link.data
            db.session.add(artist)
            db.session.commit()
        else:
            raise Exception('Form validation failed')
    except Exception as e:
        print('edit_artist_submission: ', e)
        db.session.rollback()
        print(sys.exc_info())
        error = True
    finally:
        db.session.close()
    if error:
        flash('An error occurred. Artist ' + request.form['name'] + ' could not be updated.')
        return render_template('forms/edit_artist.html', form=form, artist=artist)
    else:
        flash('Artist ' + request.form['name'] + ' was successfully updated!')
        return redirect(url_for('show_artist', artist_id=artist_id))
Exemplo n.º 17
0
def create_artist_submission():
    # called upon submitting the new artist listing form
    # insert form data as a new Venue record in the db, instead
    # modify data to be the data object returned from db insertion

    form = ArtistForm(request.form, meta={"csrf": False})

    if form.validate_on_submit():
        try:
            artist: Artist = Artist()
            form.populate_obj(artist)
            db.session.add(artist)
            db.session.commit()
            # on successful db insert, flash success
            flash(f"Artist {request.form['name']} was successfully listed!")
        except ValueError as e:
            print(sys.exc_info())
            db.session.rollback()
            # on unsuccessful db insert, flash an error instead.
            flash(f"An error occurred: {str(e)}")
        finally:
            db.session.close()

    else:
        error_msg = []
        for field, error in form.errors.items():
            error_msg.append(f"{field}: {str(error)}")
        flash(f"Error occurred: {str(error_msg)}")

    return render_template('pages/home.html')
Exemplo n.º 18
0
def create_artist_submission():
    form = ArtistForm()
    if form.validate_on_submit():
        try:
            artist = Artist(
                name=form.name.data,
                city=form.city.data,
                state=form.state.data,
                phone=form.phone.data,
                image_link=form.image_link.data
                if form.image_link.data else None,
                facebook_link=form.facebook_link.data
                if form.facebook_link.data else None,
                genres=form.genres.data,
                website=form.website.data if form.website.data else None,
                seeking_venue=True
                if form.seeking_venue_description.data else False,
                seeking_description=form.seeking_venue_description.data
                if form.seeking_venue_description.data else None)
            db.session.add(artist)
            db.session.commit()
            flash('Artist ' + form.name.data + ' was successfully listed!')
            return render_template('pages/home.html')
        except Exception:
            db.session.rollback()
            print(sys.exc_info())
            flash('An error occurred. Artist ' + form.name.data +
                  ' could not be listed.')
            return render_template('pages/home.html')
        finally:
            db.session.close()
    else:
        return render_template('forms/new_artist.html', form=form)
Exemplo n.º 19
0
def editArtist(artist_id):
    # Checking if user is logged in
    if 'email' not in login_session:
        return redirect('/login')
    editedArtist = db.session.query(Artist).filter_by(id=artist_id).one()
    # Checking if artist belongs to logged in user
    if editedArtist.user_id != login_session['user_id']:
        return """<script>function myFunction()
        {alert('You are not authorized to edit this artist.
         Please create your own artist in order to edit.');}
        </script><body onload='myFunction()'>"""
    # Using the same form as artist creation for artist editing
    form = ArtistForm(request.form, editedArtist)
    if request.method == 'POST' and form.validate():
        editedArtist.name = form.name.data
        editedArtist.year_of_birth = form.year_of_birth.data
        editedArtist.year_of_death = form.year_of_death.data
        editedArtist.country = form.country.data
        editedArtist.movement = form.art_movement.data
        db.session.add(editedArtist)
        db.session.commit()
        return redirect(url_for('showArtists'))
    else:
        return render_template('editArtist.html',
                               form=form,
                               artist=editedArtist)
Exemplo n.º 20
0
def edit_artist_submission(artist_id):
    try:
        request_data = {**request.form}
        request_data['genres'] = ','.join(request.form.getlist('genres') or [])
        request_data['seeking_venue'] = (request_data.get('seeking_venue')
                                         or '').lower() == 'y'

        form = ArtistForm(**request_data)
        if not form.validate_on_submit():
            artist = Artist.query.filter_by(id=artist_id).first()
            return render_template('forms/edit_artist.html',
                                   form=form,
                                   artist=artist)

        request_data.pop('csrf_token', None)

        Artist.query.filter_by(id=artist_id).update(request_data)
        db.session.commit()
        flash(f'Artist {request.form["name"]} was successfully updated!')
    except:
        flash(f'Artist {request.form["name"]} was not updated!')
        db.session.rollback()
    finally:
        db.session.close()

    return redirect(url_for('show_artist', artist_id=artist_id))
Exemplo n.º 21
0
def create_artist_submission():
    # called upon submitting the new artist listing form
    # TODO: insert form data as a new Venue record in the db, instead
    # TODO: modify data to be the data object returned from db insertion
    form = ArtistForm(request.form)
    try:
        form.validate()

        artist = Artist(
            name=form.name.data,
            city=form.city.data,
            state=form.state.data.name,
            phone=form.phone.data,
            image_link=form.image_link.data,
            facebook_link=form.facebook_link.data,
            genres=[genre.name for genre in form.genres.data],
            website=form.website.data,
            seeking_venue=form.seeking_venue.data,
            seeking_description=form.seeking_description.data,
        )
        db.session.add(artist)
        db.session.commit()
        # on successful db insert, flash success
        flash('Artist ' + form.name.data + ' was successfully listed!')
    # TODO: on unsuccessful db insert, flash an error instead.
    # e.g., flash('An error occurred. Artist ' + data.name + ' could not be listed.')
    except Exception as e:
        print(e)
        db.session.rollback()
        flash('An error occurred. Artist ' + form.name.data +
              ' could not be listed.')
    return render_template('pages/home.html')
Exemplo n.º 22
0
def edit_artist_submission(artist_id):
    # TODO: take values from the form submitted, and update existing
    # artist record with ID <artist_id> using the new attributes
    form = ArtistForm(request.form)
    try:
        form.validate()

        artist = Artist.query.filter(Artist.id == artist_id).first()
        artist.name = form.name.data
        artist.city = form.city.data
        artist.state = form.state.data.name
        artist.phone = form.phone.data
        artist.image_link = form.image_link.data
        artist.facebook_link = form.facebook_link.data
        artist.genres = [genre.name for genre in form.genres.data]
        artist.website = form.website.data
        artist.seeking_venue = form.seeking_venue.data
        artist.seeking_description = form.seeking_description.data

        db.session.commit()

    except Exception as e:
        print(e)
        db.session.rollback()

    finally:
        db.session.close()

    return redirect(url_for('show_artist', artist_id=artist_id))
Exemplo n.º 23
0
Arquivo: app.py Projeto: jurayev/fyyur
def create_artist_submission():
    form = ArtistForm()
    if form.validate_on_submit():
        data = request.form
        try:
            is_seeking_venue = True if data['seeking_description'].strip(
            ) else False
            artist = Artist(name=data['name'],
                            city=data['city'],
                            state=data['state'],
                            genres=request.form.getlist('genres'),
                            phone=data['phone'],
                            image_link=data['image_link'],
                            facebook_link=data['facebook_link'],
                            website=data['website'],
                            seeking_venue=is_seeking_venue,
                            seeking_description=data['seeking_description'])
            db.session.add(artist)
            db.session.commit()
            flash(f'Artist {data["name"]} was successfully listed!')
        except:
            db.session.rollback()
            flash(
                f'An error occurred. Artist {data["name"]} could not be listed.'
            )
        finally:
            db.session.close()
        return render_template('pages/home.html')
    # Flashing current errors
    for input, errors in form.errors.items():
        flash(f'Invalid value for "{input}". {"".join(errors)}')
    return render_template('forms/new_artist.html', form=form)
Exemplo n.º 24
0
Arquivo: app.py Projeto: adengz/fyyur
def create_artist_submission():
    artist = Artist()
    form = ArtistForm()
    if not form.validate_on_submit():
        flash('Invalid value found in ' + ', '.join(form.errors.keys()) +
              ' field(s).')
        return render_template('forms/new_artist.html', form=form)
    else:
        error = False
        try:
            form.populate_obj(artist)
            artist.phone = format_phone(artist.phone)
            db.session.add(artist)
            db.session.flush()
            artist_id = artist.id
            db.session.commit()
        except:
            error = True
            db.session.rollback()
        finally:
            db.session.close()
        if error:
            flash('An error occurred. Artist ' + artist.name +
                  ' could not be listed.')
            return redirect(url_for('index'))
        else:
            flash('Artist ' + request.form['name'] +
                  ' was successfully listed!')
            return redirect(url_for('show_artist', artist_id=artist_id))
Exemplo n.º 25
0
def create_artist_submission():
    form = ArtistForm(request.form)
    if form.validate_phone(form.phone):
        try:
            new_artist = Artist(
                name=form.name.data,
                city=form.city.data,
                state=form.state.data,
                phone=form.phone.data,
                genres=form.genres.data,
                facebook_link=form.facebook_link.data,
                image_link=form.image_link.data,
                website=form.website.data,
                seeking_venue=form.seeking_venue.data,
                seeking_description=form.seeking_description.data)
            Artist.create(new_artist)
            flash(
                'Artist ' + request.form['name'] + ' was successfully listed!',
                "success")
        except:
            flash(
                'An error occurred. Artist ' + form.name +
                ' could not be listed.', "danger")
    else:
        flash("Phone number is not valid", "warning")

    return render_template('pages/home.html')
Exemplo n.º 26
0
def create_artist_submission():
    error = False
    form = ArtistForm()

    # Form validation
    if not form.validate():
        for fieldName, errorMessages in form.errors.items():
            show_form_errors(fieldName, errorMessages)

        return redirect(url_for('create_artist_form'))

    # Get data
    name = request.form['name']
    city = request.form['city']
    state = request.form['state']
    phone = request.form['phone']
    genres = request.form.getlist('genres')
    image_link = request.form['image_link']
    facebook_link = request.form['facebook_link']
    website = request.form['website']
    seeking_venue = True if 'seeking_venue' in request.form else False
    seeking_description = request.form['seeking_description']

    try:
        # Create model
        artist = Artist(
            name=name,
            city=city,
            state=state,
            phone=phone,
            genres=genres,
            image_link=image_link,
            facebook_link=facebook_link,
            website=website,
            seeking_venue=seeking_venue,
            seeking_description=seeking_description,
        )

        # Update DB
        db.session.add(artist)
        db.session.commit()
    except Exception:
        error = True
        db.session.rollback()
        print(sys.exc_info())
    finally:
        db.session.close()

    # Show banner
    if error:
        abort(400)
        flash('An error occurred. Artist ' + name + ' could not be listed.',
              'danger')
    if not error:
        flash('Artist ' + name + ' was successfully listed!', 'success')

    return render_template('pages/home.html')
def create_artist_submission():
    """ Submit callback for create artists form """
    # Get form data
    name = request.form['name']
    city = request.form['city']
    state = request.form['state']
    phone = request.form['phone']
    image_link = request.form['image_link']
    facebook_link = request.form['facebook_link']
    website = request.form['website']
    seeking_venue = request.form['seeking_venue'] == 'Yes'
    seeking_description = request.form['seeking_description']
    # genres is a list
    genres = request.form.getlist('genres')

    form = ArtistForm()
    # Validate form data
    if not form.validate_on_submit():
        flash(form.errors)
        return redirect(url_for('create_artist_submission'))

    error = False
    try:
        # Create a venue instance using form data
        artist = Artist(
            name=name,
            city=city,
            state=state,
            phone=phone,
            image_link=image_link,
            facebook_link=facebook_link,
            website=website,
            seeking_venue=seeking_venue,
            seeking_description=seeking_description
        )
        db.session.add(artist)

        # Creating Artist generes instances and assigning using backref
        for genre in genres:
            new_genre = ArtistsGenres(genre=genre)
            new_genre.artist = artist             # backref
            db.session.add(new_genre)

        db.session.commit()
    except Exception as err:
        print(err)
        db.session.rollback()
        error = True
    finally:
        db.session.close()

    if error:
        flash(f'An error occurred. Artist {name} could not be listed.')
        abort(500)

    flash(f'Artist {name} listed successfully')
    return render_template('pages/home.html')
Exemplo n.º 28
0
def enter_band():
    """
    Display the artist entry page to the user and handle their input.
    """
    form = ArtistForm()
    
    if form.validate_on_submit():
        return band_info(form.name.data)
    else:
        return render_template('enter_band.html', form=form)
Exemplo n.º 29
0
def edit_artist_submission(artist_id):
    # LASTXX2: take values from the form submitted, and update existing
    # artist record with ID <artist_id> using the new attributes
    form = ArtistForm()
    name = form.name.data
    city = form.city.data
    state = form.state.data
    phone = form.phone.data
    genres = form.genres.data
    facebook_link = form.facebook_link.data
    image_link = form.image_link.data
    web_site = form.web_site.data
    seeking_venue = True if form.seeking_venue.data == 'Yes' else False
    seeking_description = form.seeking_description.data

    if not form.validate():
        flash(form.errors)
        return redirect(url_for('edit_artist_submission', artist_id=artist_id))

    else:
        error_in_update = False
        try:
            artist = Artist.query.get(artist_id)
            artist.name = name
            artist.city = city
            artist.state = state
            artist.phone = phone
            artist.facebook_link = facebook_link
            artist.image_link = image_link
            artist.web_site = web_site
            artist.seeking_venue = seeking_venue
            artist.seeking_description = seeking_description
            artist.genres = []
            for genre in genres:
                artist.genres.append(genre)

            db.session.commit()
        except Exception:
            error_in_update = True
            print(f'Exception "{Exception}" in edit_artist_submission()')
            db.session.rollback()
        finally:
            db.session.close()

        if not error_in_update:
            # on successful db update, flash success
            flash('Artist ' + request.form['name'] +
                  ' was successfully updated!')
            return redirect(url_for('show_artist', artist_id=artist_id))

        else:
            flash('An error occurred. Artist ' + name +
                  ' could not be updated.')
            print("Error in edit_artist_submission()")
            return render_template('errors/500.html')
Exemplo n.º 30
0
def create_artist_submission():

    form = ArtistForm(request.form)

    if form.validate():

        try:

            seeking_venue = False
            name = request.form['name']
            city = request.form['city']
            state = request.form['state']
            phone = request.form['phone']
            genres = request.form['genres']
            facebook_link = request.form['facebook_link']
            image_link = request.form['image_link']
            website = request.form['website']
            seeking_venue = request.form['seeking_venue']
            seeking_description = request.form['seeking_description']

            artist = Artist(name=name,
                            city=city,
                            state=state,
                            phone=phone,
                            genres=genres,
                            facebook_link=facebook_link,
                            image_link=image_link,
                            website=website,
                            seeking_venue=seeking_venue,
                            seeking_description=seeking_description)

            db.session.add(artist)

            db.session.commit()

            flash('Artist ' + request.form['name'] +
                  ' was successfully listed!')

        except ValueError as e:
            flash('Artist ' + request.form['name'] +
                  ' was not successfully listed!')
            db.session.rollback()
            print(e)

        finally:
            db.session.close()

    else:
        #get eror message
        message = []
        for field, err in form.errors.items():
            message.append(field + '' + '|'.join(err))
        flash('Errors ' + str(message))

    return render_template('pages/home.html')
Exemplo n.º 31
0
def edit_artist(artist_id):
    """
    Edit an existing artist. GET to load the preexisting data and POST to
    save the new data entered by the user.
    """

    artist = Artist.query.get(artist_id)
    if artist:
        if request.method == 'GET':
            form = ArtistForm()
            data = {
                "id": artist.id,
                "name": artist.name,
                "genres": json.loads(artist.genres),
                "city": artist.city,
                "state": artist.state,
                "phone": artist.phone,
                "website": artist.website,
                "facebook_link": artist.facebook_link,
                "seeking_venue": artist.seeking_venue,
                "seeking_description": artist.seeking_description,
                "image_link": artist.image_link,
                "email": artist.email
            }
            return render_template('forms/edit_artist.html',
                                   form=form,
                                   artist=data)
        elif request.method == 'POST':
            form = ArtistForm(request.form)
            try:
                artist.name = form.name.data
                artist.genres = json.dumps(form.genres.data)
                artist.city = form.city.data
                artist.state = form.state.data
                artist.phone = form.phone.data
                artist.website = form.website.data
                artist.facebook_link = form.facebook_link.data
                artist.seeking_venue = form.seeking_venue.data
                artist.seeking_description = form.seeking_description.data
                artist.image_link = form.image_link.data
                artist.email = form.email.data

                db.session.commit()
                message = f'Artist ID {artist.id} was updated!', 'info'
            except Exception as e:
                app.logger.error(e)
                db.session.rollback()
                message = f'An error occurred. Changes not saved :(', 'danger'

            flash(*message)

            return redirect(url_for('show_artist', artist_id=artist_id))
    else:
        abort(404)
Exemplo n.º 32
0
def artiststracks1(request):
    from pyechonest import artist
    if request.method == 'POST':
        form = ArtistForm(request.POST)
        if form.is_valid():
            similar_artists = []
            a = form.cleaned_data['artist_name']
            artist = artist.Artist(a)
            for person in artist.similar:
                similar_artists.append([person.name])
            data = {'similar_artists': similar_artists}
            return render(request, "postlogin/artiststracks1b.html", data)

    else:
        form = ArtistForm()
    data = {'form':form}

    return render(request, 'postlogin/artiststracks1.html', data)