mirror of
https://gitlab.crans.org/mediatek/med.git
synced 2025-07-06 06:43:56 +02:00
Add ISBN data downloader
This commit is contained in:
@ -2,6 +2,9 @@
|
||||
# Copyright (C) 2017-2019 by BDE ENS Paris-Saclay
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import json
|
||||
import urllib.request
|
||||
|
||||
from django.forms import ModelForm
|
||||
|
||||
from .models import Emprunt
|
||||
@ -11,3 +14,45 @@ class EmpruntForm(ModelForm):
|
||||
class Meta:
|
||||
model = Emprunt
|
||||
fields = ['media']
|
||||
|
||||
|
||||
class MediaAdminForm(ModelForm):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['isbn'].widget.template_name = "media/isbn_button.html"
|
||||
|
||||
def download_data(self, isbn):
|
||||
"""
|
||||
Download data from ISBN
|
||||
"""
|
||||
api_url = "https://openlibrary.org/api/books?bibkeys=ISBN:{}" \
|
||||
"&format=json&jscmd=data".format(isbn)
|
||||
with urllib.request.urlopen(api_url) as url:
|
||||
data = json.loads(url.read().decode())
|
||||
if data and data['ISBN:' + isbn]:
|
||||
data = data['ISBN:' + isbn]
|
||||
|
||||
# Fill the data
|
||||
# TODO implement authors
|
||||
if data['title']:
|
||||
self.cleaned_data['title'] = data['title']
|
||||
self.cleaned_data['side_title'] = data['title']
|
||||
if data['subtitle']:
|
||||
self.cleaned_data['subtitle'] = data['subtitle']
|
||||
if data['url']:
|
||||
self.cleaned_data['external_url'] = data['url']
|
||||
if data['number_of_pages']:
|
||||
self.cleaned_data['number_of_pages'] = \
|
||||
data['number_of_pages']
|
||||
|
||||
def clean(self):
|
||||
"""
|
||||
If user fetch ISBN data, then download data before validating the form
|
||||
"""
|
||||
if "_continue" in self.request.POST:
|
||||
isbn = self.cleaned_data.get('isbn')
|
||||
if isbn:
|
||||
# ISBN is present
|
||||
self.download_data(isbn)
|
||||
|
||||
return super().clean()
|
||||
|
Reference in New Issue
Block a user