Django CBV CreateView - Redirect from CreateView to last page

ⅰ亾dé卋堺 提交于 2020-06-29 03:30:11

问题


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 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?

Edit: 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 %}

回答1:


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})


来源:https://stackoverflow.com/questions/52823548/django-cbv-createview-redirect-from-createview-to-last-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!