简体   繁体   中英

View with form and context dict

I don't know how return a form and a context_dict in the same view

My view:

def myview(request):    
    context_dict = {}
    u = request.user
    context_dict['user'] = u

    ...
    form = form.myformForm()
    #return render(request, 'mytemplate.html', context_dict)
    return render(request, 'mytemplate.html', {'form': form })

Also I need to use the context_dict in a base template (for a navbar) so I would like to have access to the context in this format, if it is possible, without other prefix/path:

{{ user.username }}

Here is a really simple form view that might help as a template:

def simpleView(request):
    if request.method == "POST":
        myform = MyForm(request.POST)
        if myform.is_valid():
            #process form data
            pass
        else:
            # process form errors
            pass
    else:
        myform = MyForm()
    return render(request, "template.html", {"form": myform})

Also, you shouldn't need to pass the user through the context dictionary, in the template I believe you can do {% request.user.username %}

To answer the question directly, 'I don't know how return a form and a context_dict in the same view', you just put the form in the context dictionary along with all the data that you put in.

The if request.method == "POST statement in the view above means that the view can handle both GET and POST requests. The GET request being when the page is loaded, and the POST request being when someone submits the form on that page.

A neat way to give the user feedback on the status of the form processing is by using the messaging functionality in Django.

You can send messages to the user on the web page by calling:

messages.error(request, "some message here")

(where error could be success or one of the other message types).

You can then access and display them in the template really easily:

{% if messages %}
    {% for message in messages %}
        # DISPLAY USING HTML OR SOMETHING HERE
    {% endfor %}
{% endif %}

There might be a better way of doing the message processing but thats just a way I have found that seems quite neat!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM