Categories
Python Answers

How to get the protocol + host name from URL with Python?

To get the protocol + host name from URL with Python, we can use the urlparse function.

For instance, we write

from urllib.parse import urlparse

parsed_uri = urlparse('http://example.com/questions/1234567/blah-blah-blah-blah' )
result = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
print(result)

to call urlparse with a URL.

And then we get the protocol with uri.scheme.

And the host name is stored in the uri.netloc property.

Categories
Python Answers

How to import csv data into Python Django models?

To import csv data into Python Django models, we can call csv.reader.

For instance, we write

with open(path) as f:
        reader = csv.reader(f)
        for row in reader:
            _, created = Teacher.objects.get_or_create(
                first_name=row[0],
                last_name=row[1],
                middle_name=row[2],
                )

to open the file at path with open.

Then we call csv.reader with file f.

And then we loop through the rows and call the get_or_create method to create items that don’t exist in the database from the rows.

Categories
Python Answers

How to get the full or absolute URL (with domain) in Python Django?

To get the full or absolute URL (with domain) in Python Django, we can use the build_absolute_uri method.

For instance, we write

request.build_absolute_uri(reverse('view_name', args=(obj.pk, )))

to call request.build_absolute_uri with reverse('view_name', args=(obj.pk, ) to get the path of the view with reverse.

Then we call “request.build_absolute_uri` with the view path to return the full URL of the view.

Categories
Python Answers

How to render a template variable as HTML with Python Django?

To render a template variable as HTML with Python Django, we can use autoescape off or safe.

For instance, we write

{{ myhtml |safe }}

to use the safe filter to render myhtml as HTML.

Or we use

{% autoescape off %}
    {{ myhtml }}
{% endautoescape %}

to use the autoescape off to render myhtml as HTML.

Categories
Python Answers

How to add optional URL parameters with Python Django?

To add optional URL parameters with Python Django, we call add multiple rules for the same URL.

For instance, we write

urlpatterns = patterns('',
    url(r'^project_config/$', views.foo),
    url(r'^project_config/(?P<product>\w+)/$', views.foo),
    url(r'^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$', views.foo),
)

to add 3 URL patterns that has no URL parameters, the product parameter only, and the product and project_id` parameters.

And we map all 3 to the same view.