Luukas
Luukas

Reputation: 13

Django/Local Library. How to assign current user to a field?

I've started learning Django and im doing a local library. I have a problem. I've created a model Book, which has a borrower. When I want to save current user as a borrower value changes only on page, but not in admin panel. It also changes every single book's value, not just the specific one.

class Book(models.Model):

      title = models.CharField(max_length=100)
      author = models.CharField(max_length=60)
      ISBN = models.CharField(max_length=13,unique=True)
      genre = models.ForeignKey(Gatunek,related_name='Books',on_delete=models.PROTECT)
      borrower = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, default='')

      def __str__(self):
            return self.nazwa


class BookRent(ListView):
     model = Book
     template_name = "Books/Book_rent.html"

     def get_queryset(self):
          user = self.request.user
          Book.borrower = user
       

Upvotes: 1

Views: 80

Answers (1)

Mojtaba Arezoomand
Mojtaba Arezoomand

Reputation: 2380

if you want to change the fields of an object you need to use UpdateView instead of ListView.

class BookRent(UpdateView):
    model = Book
    template_name = "Books/update.html"
    fields = ["borrower"]

Upvotes: 1

Related Questions