开发者

cannot integrate little script inside django/python app... can you explain how urls.py works?

I'm not a programmer, but I've written few things in php/mysql. So I've grasp of programming, but I cannot understand logic of django apps... and python is so weirdly complicated! Please help me solve a little problem I'm having.

My script is simple, it displays random sentence. nothing fancy!

So I've:

random-quotes.py -->

import random

#Random
def random_quotes (request, template_name='header.html'):
    quotes = ["\"There are always two people in every picture: the photographer and the viewer.\"",
              "\"My portraits are more about me than they are about the people I photograph.\" <br><span class=\"author_span_style\">~ Richard Avedon</span>"]
    pick_quote = quotes[random.randint(0, len(quotes) - 1)]
    return render(request, template_name, {
                                           'random_quote': pick_quote,
                                           }) 

header.html -->

{{ random_quote }}

urls.py -->

url(r'^$', app.random-quotes.random_quotes, name='random_quotes'),

This url thingy is completely weird to me. I got the idea that it maps template call to the "action" file. But details and reasons just escape me!

Anyhow, I used url structure from existing django app, (where I'm integrating little script)

So, app.[random-quotes].{random_quotes} [is file name] and {is function name}

app. I'm not sure but I guess refers to the sub folder within my django app. I guessed it would be app. as in urls.py I discovered reference to the files in that folder.

For some strange reason, script doesn't work, it doesn't display anything... so I'm guessing problem should be the first part r'^$' and the fact 开发者_如何学编程that I didn't specify url.

please help me understand this concept...


The tutorial provides an excellent explanation of what is happening here.

In short, any URL that matches the regular expression in urls.py will be mapped to the specified function in views.py. views.py will execute any necessary logic, and will load a template (if specified).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜