成功网址到当前网址

时间:2018-11-26 10:23:24

标签: python django django-forms

我正在使用基于django类的视图和表单。提交新消息后,我希望视图保持在同一页面上。网址就像

localhost:8000/chat/messages/username/

其中“用户名”是向其发送消息的用户的用户名

class ThreadView(LoginRequiredMixin, FormMixin, DetailView):
    template_name = 'thread.html'
    form_class = ComposeForm

    def get_queryset(self):
        return Thread.objects.by_user(self.request.user)

    def get_object(self):
        other_username  = self.kwargs.get("username")
        obj, created    = Thread.objects.get_or_new(self.request.user, other_username)
        if obj == None:
            raise Http404
        return obj

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'] = self.get_form()
        return context

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponseForbidden()
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        thread = self.get_object()
        user = self.request.user
        message = form.cleaned_data.get("message")
        ChatMessage.objects.create(user=user, thread=thread, message=message)
        return super().form_valid(form)

urls.py:

app_name = 'chat'

urlpatterns = [
    path("", InboxView.as_view()),
    url(r'^messages/(?P<username>[\w.@+-]+)', ThreadView.as_view(), name="chaturl"),
]

如果我给success_url='./',它将转到locahost:8000/chat/messages/,这将导致404错误。

1 个答案:

答案 0 :(得分:1)

您可以覆盖get_success_url方法并反转网址:

from django.urls import reverse

def get_success_url(self):
    return reverse('chat:chaturl', kwargs={'username': self.kwargs['username']})

或者,如果您希望提交请求的路径,可以使用request.path

from django.urls import reverse

def get_success_url(self):
    return self.request.path