Beispiel #1
0
def edit_artist(artist_id):
  form = ArtistForm()
  artist={
    "id": 4,
    "name": "Guns N Petals",
    "genres": ["Rock n Roll"],
    "city": "San Francisco",
    "state": "CA",
    "phone": "326-123-5000",
    "website": "https://www.gunsnpetalsband.com",
    "facebook_link": "https://www.facebook.com/GunsNPetals",
    "seeking_venue": True,
    "seeking_description": "Looking for shows to perform at in the San Francisco Bay Area!",
    "image_link": "https://images.unsplash.com/photo-1549213783-8284d0336c4f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=300&q=80"
  }
  # TODO: populate form with fields from artist with ID <artist_id>
  form = ArtistForm()
  artist = Artist.query.filter_by(id=artist_id).first()
  form.genres.default = artist.genres
  form.state.default = artist.state
  form.process()
  form.name.data = artist.name
  form.city.data = artist.city
  form.phone.data = artist.phone
  form.address.data = artist.address
  form.website.data = artist.website
  form.facebook_link.data = artist.facebock_link
  form.seeking_talent.data = artist.seeking_talent
  form.sseeking_description.data = artist.seeking_description
  form.image_link.data = artist.image_link

  return render_template('forms/edit_artist.html', form=form, artist=artist)
Beispiel #2
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)
Beispiel #3
0
def edit_artist(artist_id: int):
    """
    Edit an artist
    :param artist_id: id of the artist to edit

    A GET returns the form to be edited
    A POST persists the updates
    """
    artist, as_type, no_availability = artist_to_edit(artist_id)
    model = MultiDict(artist)

    availability = availability_by_artist(artist_id, as_type=as_type)
    if availability is None:
        availability = no_availability

    if request.method == 'GET':
        for key, value in model_items(availability,
                                      ignore=IGNORE_AVAILABILITY):
            if key == 'from_date':
                model.add(key, datetime_to_str(current_datetime()))
            elif is_available_time_key(key) and value is not None:
                model.add(key, time_to_str(value))

        form = ArtistForm(formdata=model)
        genres = model.getlist("genres")

    else:
        form = ArtistForm()
        genres = form.genres.data

    # set choices & validators based on possible options
    set_genre_field_options(form.genres, genres)

    if request.method == 'POST' and form.validate_on_submit():
        success, artist_name = update_artist(artist["id"], form, availability)

        return update_result(success, artist_name, 'Artist',
                             url_for('display_artist', artist_id=artist_id))

    return render_template('forms/edit_artist.html',
                           form=form,
                           artist_name=model["name"],
                           title='Edit Artist',
                           submit_action=url_for('edit_artist',
                                                 artist_id=artist_id),
                           cancel_url=url_for('display_artist',
                                              artist_id=artist_id),
                           submit_text='Update',
                           submit_title='Update artist')
Beispiel #4
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))
Beispiel #5
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)
Beispiel #6
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))
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))
Beispiel #8
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))
Beispiel #9
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')
Beispiel #10
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')
Beispiel #11
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)
Beispiel #12
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)
Beispiel #13
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)
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)
Beispiel #15
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
Beispiel #16
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)
Beispiel #17
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')
Beispiel #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)
Beispiel #19
0
def edit_artist(artist_id):
    artist = Artist.query.get(artist_id)
    if artist:
        form = ArtistForm(obj=artist)
        artist = {
            "id": artist_id,
            "name": artist.name,
            "genres": [artist.genres],
            "city": artist.city,
            "state": artist.city,
            "phone": artist.phone,
            "web_site": artist.web_site,
            "facebook_link": artist.facebook_link,
            "seeking_venue": artist.seeking_venue,
            "seeking_description": artist.seeking_description,
            "image_link": artist.image_link
        }
        # DONE: populate form with fields from artist with ID <artist_id>
        return render_template('forms/edit_artist.html',
                               form=form,
                               artist=artist)
    else:
        flash('An error occurred. Artist ' + request.form['name'] +
              ' could not be edited.')
        return redirect(url_for('index'))
Beispiel #20
0
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))
Beispiel #21
0
def edit_artist_submission(artist_id):
    try:
        form = ArtistForm()
        artist = Artist.query.get(artist_id)
        artist.name = form.name.data
        artist.phone = form.phone.data
        artist.state = form.state.data
        artist.city = form.city.data
        artist.genres = form.genres.data
        artist.facebook_link = form.facebook_link.data
        artist.website = form.website.data
        artist.image_link = form.image_link.data
        artist.seeking_venue = form.seeking_venue.data
        artist.seeking_description = form.seeking_description.data

        db.session.commit()
        flash('The Artist ' + request.form['name'] +
              ' has been successfully updated!')
    except ():
        db.session.rollback()
        flash('An Error has occured and the update unsuccessful')
    finally:
        db.session.close()

    return redirect(url_for('show_artist', artist_id=artist_id))
Beispiel #22
0
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))
Beispiel #23
0
def create_artist_submission():
    form = ArtistForm(request.form)

    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!')

    except ValueError:  # FIXME melhorar essa exception

        flash('An error occurred. Artist ' + form.name +
              ' could not be listed.')

    return render_template('pages/home.html')
Beispiel #24
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)
Beispiel #25
0
def create_artist_submission():
    error = False
    form = ArtistForm(request.form)
    try:
        artist = Artist()
        artist.name = form.name.data
        artist.city = form.city.data
        artist.state = form.state.data
        artist.phone = form.phone.data
        artist.facebook_link = form.facebook_link.data
        artist.image_link = form.image_link.data
        artist.seeking_description = form.seeking_description.data
        venues.seeking_venue = True if form.seeking_venue.data == "True" else False

        # Convert List To String Speated By ,
        artist.genres = ','.join(form.genres.data)

        db.session.add(artist)
        db.session.commit()
    except BaseException:
        db.session.rollback()
        error = True
        print(sys.exc_info())
    finally:
        db.session.close()
        if error:
            flash('Error In Inserting')
        else:
            flash("Artist " + request.form['name'] + ' Was Inserted Succ!')
    return render_template('pages/home.html')
Beispiel #26
0
def create_artist_submission():
    form = ArtistForm()
    error = False
    print("About to go into venue creation")
    try:
        print("Instantiating artist")
        data = Artist(
            name=form.name.data,
            city=form.city.data,
            genres=form.genres.data,
            state=form.state.data,
            phone=form.phone.data,
            image_link=form.image_link.data,
            facebook_link=form.facebook_link.data
        )
        print("Adding to database")
        db.session.add(data)
        print("Committing data")
        db.session.commit()
        print("Persisted data")
        flash('Artist ' + request.form['name'] + ' was successfully listed!')
    except Exception as e:
        print(("Rolling back transaction"))
        print(e)
        print(e.args)
        error = True
        db.session.rollback()
        flash('An error occurred. Artist ' +
              data.name + ' could not be listed.')
        return render_template('pages/home.html')
        print(sys.exc_info())
    finally:
        print("Closing session")
        db.session.close()
        return render_template('pages/home.html')
Beispiel #27
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))
Beispiel #28
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)
Beispiel #29
0
def edit_artist_submission(artist_id):
    form = ArtistForm(request.form)
    artist = Artist.query.get(artist_id)
    error = False
    try:
        artist.name = request.form['name']
        artist.city = request.form['city']
        artist.state = request.form['state']
        artist.phone = request.form['phone']
        artist.genres = request.form.getlist('genres')
        artist.facebook_link = request.form['facebook_link']
        artist.website_link = request.form['website_link']
        artist.seeking_description = request.form['seeking_description']
        artist.image_link = request.form['image_link']
        artist.seeking_venue = request.form['seeking_venue']
        if (artist.seeking_venue == 'y'):
            setattr(artist, 'seeking_venue', True)
        else:
            setattr(artist, 'seeking_venue', False)
    except:
        error = True
    finally:
        if not error:
            db.session.commit()
            flash('Artist ' + request.form['name'] +
                  ' was successfully updated!')
        else:
            flash('An error occured. Artist ' + artist.name +
                  ' could not be updated.')
            db.session.rollback()
    # FINISHED: take values from the form submitted, and update existing
    # artist record with ID <artist_id> using the new attributes
    return redirect(url_for('show_artist', artist_id=artist_id))
Beispiel #30
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')