Django CBV CreateView-从CreateView重定向到最后一页

时间:2018-10-15 19:30:07

标签: django django-forms django-views

我正在学习Django,并且从CreateView重定向回时遇到问题,我想重定向到BookDetail页面,该页面包含由CreateView创建的书实例列表。 models.py:

class BookInstance(models.Model):
    """Model representing a specific copy of a book (i.e. that can be borrowed from the library)."""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library')
    book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) 
    imprint = models.CharField(max_length=200)
    due_back = models.DateField(null=True, blank=True)
    borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    LOAN_STATUS = (
        ('m', 'Maintenance'),
        ('o', 'On loan'),
        ('a', 'Available'),
        ('r', 'Reserved'),
    )

    status = models.CharField(
        max_length=1,
        choices=LOAN_STATUS,
        blank=True,
        default='m',
        help_text='Book availability',
    )


    class Meta:
        ordering = ['due_back']
        permissions = (("can_mark_returned", "Set book as returned"),)  

    def __str__(self):
        """String for representing the Model object."""
        return f'{self.id} ({self.book.title})'

    @property
    def is_overdue(self):
        if self.due_back and date.today() > self.due_back:
            return True
        return False

views.py

class BookInstanceCreate(PermissionRequiredMixin, CreateView):
    model = BookInstance
    fields = '__all__'
    permission_required = 'catalog.can_mark_returned'
    initial = {'Book': Book}
    success_url = reverse_lazy('book-detail')

urls.py

urlpatterns += [
    path('book/create/instance', views.BookInstanceCreate.as_view(), name='book_create_instance'),
    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
]

success_url在这里似乎不起作用,因为重定向URL需要有关书主键的信息。我已经尝试了几种选择。 `

next = request.POST.get('next', '/')
return HttpResponseRedirect(next)

return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

但它似乎对我不起作用。有人可以指导我如何编辑视图,以便在提交表单后将其重定向吗?

编辑:有我的模板代码:

{% extends "base_generic.html" %}

{% block content %}
  <form action="" method="post">
    {% csrf_token %}
    <table>
    {{ form.as_table }}
    </table>
    <input type="submit" value="Submit" class='btn btn-dark'>
    <input type="hidden" name="next" value="{{ request.path }}">
  </form>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

您需要定义get_success_url方法,而不是静态的success_url属性:

class BookInstanceCreate(PermissionRequiredMixin, CreateView):
    ...
    def get_success_url(self):
        return reverse('book-detail', kwargs={'pk': self.object.pk})