BigRetroMike BigRetroMike - 1 year ago 64
jQuery Question

Switch between data presentation in template of django

Im new to django.
I don't know if thing that I ask if available in pure django tempates.

I have main page of my application that load data from database.
It output information in

which then use bootstrap for better look.
In that div I have Image and Title.

Is there a way to give user ability to switch between
so they could pick if they like to have
's or for example
with titles only ?

I know that ajax-based frameworks had something like that but never used them.

Also I would like to preserve data from model while switching view, because I would like to not ask db for data when view is switched.

Is it possible? or the only way to do it is make separate template and add
for /view/ so I redirect user to different page with different template and handle viewing as new page (with reloading model)

Answer Source

I'm not sure this is a good practice but if you really want it to be in the same html file:

Using the Django Template LAnguage to evaluate which "view" the user wants.

Modify your html file to include this in the body. First we make a form where we ask the user what view he wants and then we evaluate with data from the context dictionary

<form role="form" id="view_form" method="post" action="<same url>">
        <input type="radio" name="view" value="view1" checked> View #1 <br> <!-- this one will be checked by default -->
        <input type="radio" name="view" value="view2"> View #2 <br>
        <input type="radio" name="view" value="view3"> View #3 <br>
        <button type="submit" name="submit">Change View</button>

    {% if view == view1  %}
        <!-- your code here -->
    {% elif view == view2 %}    
        <!-- your code here -->
    {% endif %}

Modify your view in to capture and add the data from the form to the context dictionary.

def page(request):
    context_dict = []
    if request.method=='POST':
        view = request.POST.get['view']
        context_dict['view'] = str(view)

    #The rest of your code here    

However I think it is better to evaluate the view value in your view function and render a different template for each value

def page(request):
    # Your code first

    view_value = None
    if request.method=='POST':
        view = request.POST.get['view']

    if view = 'view1':
        render(request, 'your_template.html', context_dict) # If you don't have a context, simply don't include it in this line
    elif view = 'view2':
        render(request, 'your_template2.html', context_dict)

    ... # All your other possible views

        render(request, 'default_template.html', context_dict) # If there's no match, load the default one.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download