开发者

DJango Passing in POST as a Context Argument

开发者 https://www.devze.com 2023-03-09 15:06 出处:网络
When making views in django, is it allowable to pass in POST data as context? That is: def view( request ):

When making views in django, is it allowable to pass in POST data as context? That is:

def view( request ):
    #view operations here
    #...

    c = Context({
        'POST':request.POST,
    })
    return render_to_response("/templatePath/", c, context_instance=Requ开发者_运维百科estContext(request))

My goal is to maintain data in fields already filled without having to save them to a db. That is, when you click the option to add additional field entries, the data you've put in is kept and automatically filled back into the forms. I feel this might be sloppy or perhaps unsafe. Is there any reason this is a bad or unsafe technique? Is there a better way to maintain data?


Although nothing is inherently bad about passing the request.POST variable to the template, everything you're trying to achieve is already handled by the stereotypical form view. If you go down your current path, you will end up with a buggy version of the recommended way to handle forms in Django.

See using a form in a view in the the Django documentation.

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form
    return render_to_response('contact.html', {
        'form': form,
    })

In you case, you'll want to make sure the redirect URL redirects to the same form. See django.shortcuts.redirect().

0

精彩评论

暂无评论...
验证码 换一张
取 消