1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
from django import forms
from django.conf import settings
from django.contrib.auth.forms import UserCreationForm
from django.core.files.storage import default_storage
from .models import User, Book
import os
import hashlib
import io
class UserRegisterForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'phone', 'address', 'name']
def save(self, commit=True):
user = super().save(commit=False)
user.roles = ['user']
if commit:
user.save()
return user
class BookForm(forms.ModelForm):
cover_url = forms.URLField(required=False, label="Cover Image URL")
cover_upload = forms.ImageField(required=False, label="Cover Image File Upload")
class Meta:
model = Book
fields = ['title', 'author', 'publisher', 'price', 'stock', 'isbn', 'description']
def clean(self):
cleaned_data = super().clean()
cover_url = cleaned_data.get("cover_url")
cover_upload = cleaned_data.get("cover_upload")
if cover_url and cover_upload:
raise forms.ValidationError("Please provide either a URL or an upload, not both.")
return cleaned_data
def save(self, commit=True):
instance = super().save(commit=False)
cover_url = self.cleaned_data.get('cover_url')
cover_upload = self.cleaned_data.get('cover_upload')
if cover_url:
instance.cover = cover_url
elif cover_upload:
file_content = cover_upload.read()
file_hash = hashlib.md5(file_content).hexdigest()[:16] # Using first 16 chars for brevity
cover_upload.seek(0)
name, ext = os.path.splitext(cover_upload.name)
unique_filename = f"{name}_{file_hash}{ext}"
file_name = default_storage.save(os.path.join('covers', unique_filename), cover_upload)
instance.cover = os.path.join(settings.MEDIA_URL, file_name)
if commit:
instance.save()
return instance
class ImportBookForm(forms.Form):
file = forms.FileField(label="JSONL File")
|