Django 1.10 - get site base url - python

How do you get base url of a site?
like - https://stackoverflow.com/
I would love to set it to settings.py
Thanks
Answer:
Really very sorry for such a poor question. :(
I was trying to link up a post by following code -
{{ related_question.question_text }}
it took me from current page url but i expected from base url. I thought, i would get a solution like site_url() like Wordpress and could use it in settings.py.
But i don't have to do that. Starting href with /.... starts from base url. So, above <a> tag should be -
{{ related_question.question_text }}
That's it.

I recommend you to write your own template context processor which will return a SITE_URL from your settings file.
See https://docs.djangoproject.com/en/1.10/ref/templates/api/#writing-your-own-context-processors
Your function simply has to return a dict such as {"SITE_URL": settings.SITE_URL} and then all your templates will have "SITE_URL" in the context.
Another option would be to add a method to the question model e.g. get_url() which returns a site url with a slug and then use related_question.get_url inside your template.
And you should probably use a "url" tag in your templates, such as {% url 'question' related_question.id %} instead of hardcoding the URLs.

Related

how to use dynamic templates in python pyramid

i've finished developing a website, it's working fine however i am trying to optimize my website by adding dynamic templates, and want to make sure that if it can be done on pyramid python.
for example, in my jinja template i have the following:
{% block article_detail %}
<form action="{{request.route_url('Sports_News_Action',action=action)}}" method="post" class="form">
{% if action =='edit' %}
{{ form.id() }}
example in my controller:
#view_config(route_name='Sports_News_Action', match_param='action=create',
renderer='StarAdmin:templates/edit_sports.jinja2')
def general_create(request):
entry = SportNews()
the request route will have to match the one in my controller in order to run the function. what i want to do is how do i replace the one in jinja with a dynamic variable, to use the one jinja template lets say for different views/controllers with different route_names.
I think in your situation the simplest solution is to leave action undefined and the browser will submit the request to the current url. You only need to specify action if you want to submit the form to a different url than the current. That being said, you can use lots of different options in pyramid to generate a url as well. For example, request.url is the current url, or request.matched_route.name is the name of the current matched route.

Frozen flask creates the files but gets the links wrong

Using frozen flask to make my website static, I have the following problem.
While all of my pages are being built (file//c:/correctpath/build/2014/page-title/index.html) the links to the pages are file:///c:/2014/page-title/.
Is there something I have missed?
EDIT:
In my template I have something like
{% for page in pages %}
{{ page.title }}
{% endfor %}
where .url() is a method on the page object:
return url_for('article', name=self.name, **kwargs)
url_for produces absolute paths (e. g. /2014/page-title) - when you open up your files in the browser it follows the rules regarding relative URL resolution and strips the extra file contents. If you just want to view your files as they will be seen on the server, Flask-Frozen has a run method that will let you preview your site after generating it.
Alternately, you can set FREEZER_RELATIVE_URLS to True to have Flask-Frozen generate links with index.html in them explicitly.
Rather than setting FREEZER_RELATIVE_URLS = True, with resulting URLs ending on index.html, you can also set FREEZER_BASE_URL to <http://your.website/subdir>.

How to parse Django templates for template tags

Situation
I'm writing a checker program that checks Django templates. For example I want to check if all Django templates that use url template tag, use it with quotes on first parameter so that it is Django 1.5 compatible. Also I want to check that they have included {% load url from future %} in their templates.
For example if my program parses the following Django template, I want it to raise an exception.
{% extends 'base.html' %}
<td>
<a href="{% url first second %}">
</a>
</td>
But this template should get parsed without exception.
{% extends 'base.html' %}
{% load url from future %}
<td>
<a href="{% url 'first' second %}">
</a>
</td>
I'm not limited to this simple example. I have other parsings to do. For example I want to check how many load template tags are present in the template.
Question
How can I elegantly solve this parsing problem?
I don't want to use regular expressions.
I this Django it self has some utilities in this regard. I think using them is a good idea, but I don't know how.
I want to run the program separately from Django. So I don't want Django to run the program itself (with render_to_response). (This is important)
Code
Please show me some code that can solve the example I mentioned. I want to detect whether {% load url from future %} is in the code. Also I want to check every url template tag and check if the first argument is quoted.
Bonus:
I want to be able to see the rendered HTML that Django generates from this template, and do my HTML parsing on it. (for example with PyQuery)
You say...
I want to check if all Django templates that use url
template tag, use it with quotes on first parameter so that it is
Django 1.5 compatible.
...and...
I don't want to use regular expressions.
...because...
the result of that might become a huge spaghetti code
...but, frankly, writing a parser from scratch is likely to be even messier than using a regular expression. I don't see what's so messy about a regex as simple as something like...
"{% *url +[^']"
...and I doubt there's a non-regex-based solution that's as terse as that.
With regards to...
Also I want to check that they have included
{% load url from future %} in their templates.
If your intention is to ensure Django 1.5 compatibility, this is pointless. According to the Django 1.5 release notes, the new-style url tag syntax is enabled by default, so the line {% load url from future %} won't have any effect.
And in versions prior to 1.5, it's much simpler just to put...
import django.template
django.template.add_to_builtins('django.templatetags.future')
...at the bottom of your settings.py and be done with it. :-)
You can also use the compile_string method.
>>> from django.template.base import *
>>> settings.configure()
>>> compile_string("<a href='ab'></a>{% cycle 'row1' 'row2' as rowcolors %}", None)
>>> [<Text Node: '<a href='ab'></a>'>, <django.template.defaulttags.CycleNode object at 0x10511b210>]
The compile string method is utilized by the Template class and is the method used to produce the node list.
Tested in Django 1.8 Alpha.
https://github.com/django/django/blob/1f8bb95cc2286a882e0f7a4692f77b285d811d11/django/template/base.py
Next code still uses django, but it can check if syntax is correct:
>>> from django.template import Template
>>> from django.template.defaulttags import URLNode
>>> t = Template("{% load url from future %}\n{% url projects_list company.slug %}")
>>> for node in t.nodelist:
... if isinstance(node, URLNode):
... for arg in node.args: print(arg)
...
company.slug
>>> t2 = Template('{% load url from future %}\n{% url "projects_list" company.slug }')
>>> for node in t2.nodelist:
... print(node)
...
<django.template.defaulttags.LoadNode object at 0x32145d0>
<Text Node: '
{% url "projects_list" c'>
>>>
As you see last node is not URLNode

Is there feature in Pyramid to specify a route in the template like Django templates?

For example in Django if I have a url named 'home' then I can put {% url home %} in the template and it will navigate to that url. I couldn't find anything specific in the Pyramid docs so I am looking to tou Stack Overflow.
Thanks
The brackets depend on the templating engine you are using, but request.route_url('home') is the Python code you need inside.
For example, in your desired template file:
jinja2--> {{ request.route_url('home') }}
mako/chameleon--> ${ request.route_url('home') }
If your route definition includes pattern matching, such as config.add_route('sometestpage', '/test/{pagename}'), then you would do request.route_url('sometestpage', pagename='myfavoritepage')

Django: Redirect to previous page *with query string* after login

I am using django.contrib.auth and would like to redirect to the previous page after logging in. I would like something like the following: Django: Redirect to previous page after login except the redirected-to URL can contain a query string.
Currently I have the following link in my template:
Login
user_login is the name of my login view.
I would like to use {{ request.get_full_path }} instead of {{ request.path }} to get the current path including the query string, but this would create a url with a query string within a query string (e.g. /login/?next=/my/original/path/?with=other&fun=query&string=parameters) which doesn't work.
I also tried adding a redirect_to argument to my login view and passing the url with the query string as a arument to the url template tag. However this gives me a NoReverseMatch error.
How about escaping the get parameters and then unquoting them in the view?
html
Login
login view
if successful_login:
url_with_get = urllib2.unquote(request.GET.get('next'))
return http.HttpResponseRedirect(url_with_get)
PS: I've stumbled across your blog many times looking for PIP help : )

Categories