def handle(self, *args, **options): for filename in os.listdir('files'): filename = os.path.join('files',filename) if os.path.isfile(filename): with open(filename, "rb") as f: b = Book() b.image = File(f) thumbnail = os.path.join(os.path.dirname(filename), 'thumbnails', os.path.splitext(os.path.basename(filename))[0] + '.png') with open(thumbnail, "rb") as tn: b.thumbnail = File(tn) b.save() shutil.move(filename, "files/done")
def _create_books(self): books_added = 0 for int_isbn in [9780140361216, 9780545010221, 9780590353427, 9780060809836, 9781894063012, 9780156027496, 9780373626045, 5040071159, 9780141183190, 9780099285663, 9780028600901, 9780618832934, 9780618832934, 9781101084571, 9781101099421, 9781101096451, 9780439800990, 9780141439686, 9780969522508, 9780669281149, 9780495793595, 9780199540280, 9780618832934, 9780486475677]: response, str_isbn = get_info_from_api(int_isbn) if not response: print("No book with this ISBN") continue else: books_added += 1 user = User.objects.order_by('?').first() title = response['ISBN:' + str_isbn]['title'] url = (response['ISBN:' + str_isbn]['url']) # year = int(response['ISBN:' + str_isbn]['publish_date'][-4:]) year = random.choice(range(1950, 2015)) date_published = datetime.date(year, 7, 12) if 'by_statement' in response['ISBN:' + str_isbn].keys(): body = response['ISBN:' + str_isbn]['by_statement'] if 'cover' in response['ISBN:' + str_isbn].keys(): image_link = response['ISBN:' + str_isbn]['cover']['large'] if image_link[-3:] != 'jpg': continue filename = random_generator() + ".jpg" urllib.request.urlretrieve(image_link, filename) print(title) condition = random.choice([x[1] for x in CONDITION_CHOICES]) exchange = random.choice([x[1] for x in EXCHANGE_CHOICES]) status = random.choice([x[1] for x in EXCHANGE_CHOICES]) book = Book(original_poster=user, title=title, pub_date=date_published, body=body, url=url, exchange_choices=exchange, condition_choices=condition, status_choices=status) book.image = File(open(filename, 'rb')) book.save() print(f"Successfully populated database with {books_added} new books!")
def save(self, data, request): """ Create new Book instance and save Args: data (BookForm data): Data validated by BookForm request (request): Original request with image file """ authors_string = data['authors'] categories_string = data['categories'] authors = self.get_authors(authors_string) categories = self.get_categories(categories_string) new_book = Book() new_book.title = data['title'] new_book.description = data['description'] new_book.image = request.FILES.get("image", None) new_book.save() new_book.authors.add(*authors) new_book.categories.add(*categories) new_book.save()