I am working on a project that allows me to upload books to database and sort them by them their collection. The problem is that whenever i upload and try to filter out books from a particular collection i get the error Field 'id' expected a number but got 'autobiography'
models.py
class BookDetails(models.Model):
collections = models.CharField(max_length=255, choices=COLLECTION, default="")
class Meta:
verbose_name_plural = "BookDetails"
def __str__(self):
return self.collections
class Books(models.Model):
"""
This is for models.py
"""
book_title = models.CharField(max_length=255, default="", primary_key=True)
book = models.FileField(default="", upload_to="books", validators=[validate_book_extension], verbose_name="books")
collection = models.ForeignKey(BookDetails, on_delete=models.CASCADE, default="")
class Meta:
verbose_name_plural = "Books"
def __str__(self):
return self.book_title
forms.py
class BookInfo(forms.ModelForm):
class Meta:
model = BookDetails
fields = ["collections",]
class BookFile(BookInfo):
book = forms.FileField(widget = forms.ClearableFileInput(attrs={"multiple":True}))
class Meta(BookInfo.Meta):
fields = BookInfo.Meta.fields ["book",]
views.py
def books(request):
if request.method == "POST":
form = BookFile(request.POST, request.FILES)
files = request.FILES.getlist("book")
try:
if form.is_valid():
collection = form.save(commit=False)
collection.save()
if files:
for f in files:
names = str(f)
name = names.strip(".pdf")
Books.objects.create(collection=collection, book_title=name, book=f)
return redirect(index)
except IntegrityError:
messages.error(request, "value exist in database")
return redirect(books)
else:
form = BookFile()
return render(request, "books.html", {"form":form})
def test(request):
data = Books.objects.filter(collection="autobiography")
template = loader.get_template('test.html')
context = {"data":data}
return HttpResponse(template.render(context, request))
so basically what i am trying to achieve is to be able to filter the books based on their collections
CodePudding user response:
Since you pass collections
field value in filter value. So it give errors. You can use below queryset.
data = Books.objects.filter(collection__collections="autobiography")