Django CBV CreateView-从CreateView重定向到最后一页 [英] Django CBV CreateView - Redirect from CreateView to last page

查看:69
本文介绍了Django CBV CreateView-从CreateView重定向到最后一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm learning Django and i have problem with redirecting back from CreateView I want to redirect to a BookDetail page which contains list of bookinstances which are created by 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在这里似乎不起作用,因为重定向网址需要有关书主键的信息。我已经尝试了几种选择。 `

success_url seems to not work here since redirect url needs information about book primary key. I have already tried few options ex. `

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

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

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

but it seems to not work for me. Can someone instruct me how to edit View so it will redirect after submiting a form?

编辑:有我的模板代码:

there is my template code:

{% 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 %}


推荐答案

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

You need to define the get_success_url method, rather than the static success_url attribute:

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

这篇关于Django CBV CreateView-从CreateView重定向到最后一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆