1

我相信这是一个简单的问题,只是无法找到解决方案。我有一个视图,它在服务器上做了一些工作,然后将用户传回另一个视图,通常是原始调用视图。

我现在渲染它的方式,url 没有被重定向,即它是原始接收视图的 url。因此,在用户刷新的情况下,他们将再次运行该服务器代码。

class CountSomethingView(LoginRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        # so some counting
        view = MyDetailView.as_view()
        return view(request, *args, **kwargs)
4

4 回答 4

1

我强烈建议不要覆盖getpost方法。相反,覆盖dispatch. 因此,要扩展 Platinum Azure 的答案:

class CountSomethingView(LoginRequiredMixin, RedirectView):
    permanent = False

    def get_redirect_url(self, **kwargs):
        url = you_can_define_the_url_however_you_want(**kwargs)
        return url

    def dispatch(self, request, *args, **kwargs):
        # do something
        return super(CountSomethingView, self).dispatch(request, *args, **kwargs)
于 2013-09-03T19:30:13.207 回答
0

在基于 Django 类的视图中执行重定向很容易。

只需做一个return redirect('your url goes here').

但是,我相信这不是您想要做的。我看到你正在使用get(). 通常,在谈到 HTTP 时,GET很少会在请求之后进行重定向。请求之后通常POST会进行重定向,因为当用户向后退时,您不想再次提交相同的数据。

那你想做什么?我认为你想要做的是:

def get(self, request, *args, **kwargs):
   return render_to_response('your template', data)

甚至更好

def get(self, request, *args, **kwargs):
    return render(request, self.template_name, data)
于 2013-09-02T19:14:13.817 回答
0

If you're creating or updating a model, consider inheriting from CreateView or UpdateView and specifying a success_url.

If you're really doing a redirect off of an HTTP GET action, you can inherit from RedirectView and override the get method (optionally also specifying permanent = False):

class CountSomethingView(LoginRequiredMixin, RedirectView):
    permanent = False

    def get(self, request, *args, **kwargs):
        # do something
        return super(CountSomethingView, self).get(self, request, *args, **kwargs)

Note that it's really bad practice to have a get action with side-effects (unless it's just populating a cache or modifying non-essential data). In most cases, you should consider using a form-based or model-form-based view, such as CreateView or UpdateView as suggested above.

于 2013-09-02T19:33:53.370 回答
0

当用户执行操作并且我需要将他重定向到同一页面时,首先我使用 templateView 显示一个简单的“谢谢”(例如)然后提供一个链接以返回上一页{% url %}

例如 :

from django.views.generic import CreateView, TemplateView
from django.http import HttpResponseRedirect

class UserServiceCreateView(CreateView):
    form_class = UserServiceForm
    template_name = "services/add_service.html"

    def form_valid(self, form):
    [...]

    return HttpResponseRedirect('/service/add/thanks/')

class UserServiceAddedTemplateView(TemplateView):
     template_name = "services/thanks_service.html"

    def get_context_data(self, **kw):
        context = super(UserServiceAddedTemplateView, self).\
            get_context_data(**kw)
        context['sentance'] = 'Your service has been successfully created'
        return context

在模板Thanks_service.html 中我{% url %}用来返回预期页面

希望这可以帮助

于 2013-09-02T19:08:35.950 回答