1

In my application, I will ask user to input some text with variable and store it into database. like this...

Url

id |     url                           |
---+-----------------------------------+
1  | http://example.com/?aaa={{para1}} |
2  | http://example.com/?aaa={{para2}} |
3  | http://example.com/?aaa={{para2}} |
4  | http://example.com/?aaa={{para1}} |

And there is a table with the actual value of those parameter.

Parameter

id |    para   |
---+-----------+
1  | 932580234 |
2  | 865234932 |

I want to render a html and replace the {{para1}} or {{para2}} on it.

views.py

def userpage(request):
    url_obj = Url.objects.filter(id=..not_important...)[0]
    url = url_obj.url

    para1_obj = Parameter.objects.filter(..not_important..)[0]
    para1 = para1_obj.para

    para2_obj = Parameter.objects.filter(..not_important..)[0]
    para2 = para2_obj.para

    return render(request, 'userpage.html', {'url':url, 'para1':para1, 'para2':para2})

templates/userpage.html

You URL is {{ url }}

My expectation is

You URL is http://example.com/?aaa=932580234

However, the actual html is

You URL is http://example.com/?aaa={{para1}}

How can I "pre render" the field in database before "return render...."? Or is there any other solution for this?

I'm using python 3.4 and django 2.0

Thanks!!

1 Answer 1

1

We can first construct the url as a template:

url_template = Template(url)

then we render it with the given parameters:

context = Context({'para1':para1, 'para2':para2})
our_url = url_template.render(context)

then our_url is rendered correctly, and we can insert it into our real template rendering:

return render(request, 'userpage.html', {'url': our_url})

So that means we get something like:

def userpage(request):
    url_obj = Url.objects.filter(id=..not_important...)[0]
    url = url_obj.url

    para1_obj = Parameter.objects.filter(..not_important..)[0]
    para1 = para1_obj.para

    para2_obj = Parameter.objects.filter(..not_important..)[0]
    para2 = para2_obj.para

    url_template = Template(url)
    context = Context({'para1':para1, 'para2':para2})
    our_url = url_template.render(context)
    return render(request, 'userpage.html', {'url': our_url})

Note that if you have a rather large table of parameters, you better construct the dictionary dynamically with:

para_dict = {
    'para{}'.format(para.id): para.para
    for para in Parameter.objects.all()
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just added to my existing code. It is exactly what I want! Thanks for your explanation and it is clear and let me understand more about django. I'm now enjoying to use django to write my own web application!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.