问题描述
我正在学习 Django,但在从 CreateView 重定向回来时遇到问题,我想重定向到包含由 CreateView 创建的 bookinstance 列表的 BookDetail 页面.模型.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 似乎在这里不起作用,因为重定向 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?
有我的模板代码:
{% 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 重定向到最后一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!