Django:如何分配一个按钮来获取信息并保存()

gblwokeq  于 2023-02-10  发布在  Go
关注(0)|答案(1)|浏览(94)

是否有办法让按钮执行以下操作?当用户按下按钮时,它会获取当前用户的user.username,并自动从models.py填写BookInstance表格,然后将其保存到数据库中。
models.py开始:

class BookInstance(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    book = models.ForeignKey("Book", on_delete=models.RESTRICT, null=True)
    imprint = models.CharField(max_length=200, blank=True, null=True)
    due_back = models.DateField(blank=True, null=True)
    borrower = models.ForeignKey(
        User, on_delete=models.SET_NULL, blank=True, null=True)

    LOAN_STATUS = (
        ('m', 'Maintenance'),
        ('o', 'On Loan'),
        ('a', 'Available'),
        ('r', 'Reserved')
    )

    status = models.CharField(
        max_length=1, choices=LOAN_STATUS, blank=True, default='a')

    class Meta:
        ordering = ['due_back']

    def __str__(self):
        return f'{self.id} - {self.book.title}'

    def get_absolute_url(self):
        return reverse("catalog:book_list")
class Book(models.Model):

    title = models.CharField(max_length=50)
    author = models.ForeignKey(
        'Author', on_delete=models.SET_NULL, null=True)
    summary = models.TextField(
        max_length=500, help_text="Enter brief description")
    isbn = models.CharField('ISBN', max_length=13, unique=True)
    genre = models.ManyToManyField(Genre, help_text="Select genre")

    language = models.ForeignKey(
        "Language", on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("catalog:book_detail", kwargs={"pk": self.pk})

这是我从我的views.py

def borrowBook(request, pk):

    context = {
        'book_instance': BookInstance.objects.all()
    }

    success_url = reverse_lazy('catalog:index')
    if request.method == "POST":
        form = BorrowForm(request.POST or None)
        if form.is_valid():
            book_instance.id = BookInstance.objects.get(pk=pk)
            book_instance.book = BookInstance.objects.get(book=book)
            book_instance.borrower = request.user
            book_instance.status = 'o'
            book_borrowed_count = BookInstance.objects.filter(
                owner=request.user).count()
            if book_borrowed_count < 4:
                book_instance = form.save(commit=False)
                book_instance.save()
            else:
                print("Maximum limit reached!")
            return redirect('catalog:index')

    return render(request, 'catalog/book_detail.html', {'form': form})

下面是我forms.py中的BorrowForm

class BorrowForm(forms.ModelForm):
    class Meta:
        model = BookInstance
        fields = '__all__'

下面是我urls.py中的:

path("book_list/book/<int:pk>/borrow", views.borrowBook, name="borrowBook"),

我还尝试在这里使用CBV:

class BorrowBookView(PermissionRequiredMixin, CreateView):
    permission_required = 'login'
    model = BookInstance
    fields = '__all__'
    template_name = 'catalog/borrow_form.html'
    success_url = reverse_lazy('catalog:index')

    def post(self, request, *args, **kwargs):
        book_instance.id = BookInstance.objects.get(pk=pk)
        book_instance.book = BookInstance.objects.get(book=book)
        book_instance.borrower = request.user
        book_instance.status = 'o'
        book_instance = form.save(commit=False)
        book_instance.save()

来自urls.py的CBV路径:

path("book_list/book/<int:pk>/borrow/",
         views.BorrowBookView.as_view(), name="book_borrow"),

下面是我如何使用这里的建议来实现这个按钮:

<form action="#" method="post">
                    {% csrf_token %}
                    <button 
                        type="submit" 
                        class="btn btn-dark flex-shrink-0 " 
                        value="{{ book.id }}">Borrow
                    </button>

但当我按下它似乎并没有保存任何东西到数据库,只是弹出错误,虽然我可能会实现按钮或功能,从我的是错误的意见.感谢和赞赏提供的任何帮助.

bvjxkvbb

bvjxkvbb1#

你不需要一个Django form来完成这个任务。表单通常用于创建对象或编辑它的字段(比如在管理页面)。这里user不是编辑或创建对象(书),而是借用一个。
所以基本上,我们只需要列出所有可用的图书示例(status='a'),并有一个按钮来“借用”它,借用操作是将status更新为'r''o',并将借用者更新为当前的userLoginRequiredMixin保证request对象中存在该user
views.py

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import View
from django.contrib import messages
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404

from .models import BookInstance

class BorrowBook(LoginRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        book_id = kwargs['pk']
        available_books = BookInstance.objects.filter(book__pk=book_id, status='a')
        return render(request, 'borrow_book.html', {'available_books': available_books})

    def post(self, request, *args , **kwargs):
        book_instance_id = request.POST['id']
        obj = get_object_or_404(BookInstance, id=book_instance_id)
        obj.status = 'r'
        obj.borrower = request.user
        # Maybe also update due_back data
        # obj.due_back = ...
        obj.save()
        messages.success(request, "Your book is reserved.")
        # I used the redirection to the same template
        # But you probably want to send the user somewhere else
        return HttpResponseRedirect(reverse('core:borrow-book', kwargs={'pk': 1}))

borrow_book.html

{% extends 'base.html' %}

{% block content %}
    {% if messages %}
    <ul class="messages">
        {% for message in messages %}
        <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
        {% endfor %}
    </ul>
    {% endif %}

    {% for instance in available_books %}
    <form action="{% url 'core:borrow-book' instance.book.id %}" method="POST">
        {% csrf_token %}
        <input type="hidden" name="id" value="{{instance.id}}">
        <p>{{instance.book}}</p>
        <p>{{instance.book.language.name}}</p>
        <input type="submit" value="Borrow this book.">
    </form>
        
    {% endfor %}
{% endblock content %}

urls.py

from django.urls import path
from core import views

app_name = 'core'

urlpatterns = [
    path("book_list/book/<int:pk>/borrow/", views.BorrowBook.as_view(), name="borrow-book"),
]

相关问题