3

Using a generic FormView I'd like to reflect something about the POST data that was submitted back to the user, but I'm not sure how best to do this.

class MyView(generic.FormView):
    form_class = MyForm
    def get_success_url(self):
        return reverse('success')

reverse('success') redirects to a simple

class SuccessView(generic.TemplateView):
    template_name = 'success.html'

Is there a way that I can access params object in SuccessView via the get_success_url call, or is there a better (and simpler) way to do this? TIA Dan

UPDATE (my solution, but thanks for the ideas)

I actually found that this was the simplest way (for me) to solve the problem:

class SuccessMixin(object):
    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form, **kwargs)

    def form_valid(self, form):
        # this is my post processing step which returns the
        # feedback data that I want to pass to the user
        form_data = form.get_some_data_from_form()
        return render_to_response('submitted.html', 
            {'form_data': form_data,}, 
            context_instance=RequestContext(self.request))

Each view inherits this mixin, and if the form is valid then I pull the feedback data from it and render it as a response - completely bypassing the get_success_url redirect. I've removed the get_success_url and SuccessView.

4

3 回答 3

5

将数据作为GET参数包含在您的成功 url 中。

def get_success_url(self):
   url = reverse('success')
   # maybe use urlencode for more complicated parameters
   return "%s?foo=%s" % (url, self.request.POST['bar'])

然后在您的模板中,访问 GET 数据中的参数。

foo: {{ request.GET.foo }}
于 2012-02-14T13:12:02.493 回答
2

我也试图弄清楚这一点,一个简单的解决方案是使用:

from django.contrib import messages

在 get_success_url(self) 你可以写

def get_success_url(self)
    messages.add_message(self.request, messages.SUCCESS, 'Contact Successfully Updated!')
    return reverse('contacts:contact_detail', args=(self.get_object().id,))

在您的模板中,您可以通过以下方式访问此消息

{% for message in messages %}
    {{ message }}
{% endfor %}
于 2015-01-08T01:01:02.030 回答
1

完成您想要做的事情的一种方法是使用 Sessions。在用户的会话对象上存储您需要的任何值,并从 SuccessView 中访问它们。查看Django 会话文档以获取更多详细信息。

于 2012-02-13T22:35:05.303 回答