5 lesser used Django template tags

We already know how to use for, if-else, filter and url template tags in Django. We can also create custom template tags in Django if any requirement is not getting fulfilled with existing tags. 

Here we are introducing you with 5 Django template tags which are lesser-known and used by beginner Django developers.

1. lorem

This template tag is used to insert random lorem ipsum Latin text in the template. This is useful when you want to show the sample data instead of blank space.

This tag accepts 3 optional parameters: count, method, and random.

The count is the number of words or paragraphs to produce. The method can have values w for words, p for HTML paragraphs and b for plain-text paragraphs. When the third parameter, random, is used, the text is generated randomly instead of using lorem ipsum text.

Refer to this Django template fiddle for example and demo.

2. templatetag

Double curly braces are used to display variables in Django templates. What if you want to display just curly braces in template. For this to achieve we can use templatetag template tag.

3. cycle

This tag accepts the variable number of arguments and outputs the next argument each time this tag is called. Once all arguments have been called, loop restarts from the starting.

We can use variables or string or a mix of both as arguments for this tag.

Refer to this Django template fiddle for example and demo. 

<!-- mylist is {"mylist":["Line 1","Line 2","Line 3","Line 4","Line 5","Line 6"]} -->
{% for item in mylist %}
    <div style="color:{% cycle 'red' 'green' 'blue' 'yellow' %}">
{% endfor %}


cycle tag in django template tags

4. firstof

This template tag accepts the variable number of arguments and returns the first argument which is not False i.e. which is not zero, empty string or False

Refer to this Django template fiddle for example and demo. 

5. phone2numeric

Converts any phone number to the numeric equivalent even if the phone number is not valid.

It will not convert any integer or boolean values.

Refer to this Django template fiddle for example and demo. 

Solving Python Error- KeyError: 'key_name'

As per Python 3 official documentation a key error is raised when a mapping (dictionary) key is not found in the set of existing keys.

This error is encountered when we are trying to get or delete the value of a key from a dictionary and that key doesn't exist in the dictionary.

rana@Brahma: ~$ python3
Python 3.5.2 (default, Jul 10 2019, 11:58:48) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = dict()
>>> a["key1"] = "value1"
>>> print(a["key2"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'key2'

Accessing dictionary keys:

To access dictionary keys we use square brackets [ ].

>>> gender = dict()
>>> gender["m"] = "Male"
>>> gender["f"] = "Female"
>>> gender["m"]

However, the above method i.e using square brackets have one drawback. If the key doesn't exists we get KeyError.

>>> gender["k"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'k'

Deleting not-existing key:

>>> del gender["h"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'h'

To handle such cases, we can use one of the below techniques based on the scenario.

- Use method get()
We can get the value of a key from the dictionary using the get method. If a key-value pair does not exist for the given key in the dictionary, then None is returned, else the value of corresponding to that key is returned. This is the recommended way.

>>> gender.get("m")
>>> gender.get("k")
>>> print(gender.get("k") is None)

You can pass the second optional parameter in the get() call which is the value returned if the key doesn't exist in the dictionary. The default value of this second parameter is None.

- Check the existence of the key

We may check if any particular key exists in the dictionary or not and then based on that can take action. For example:

gender = dict()
gender["m"] = "Male"
gender["f"] = "Female"

if "k" in gender:
  print("Key k exists in gender")
  print("Key k doesn't exists in gender")

- Use try-except

If you are not using or do not want to use get method to access the keys in the dictionary, use the try-except block.

gender = dict()
gender["m"] = "Male"
gender["f"] = "Female"

  value = gender["k"]
except KeyError:
  print("Key error. Do something else")
except Exception:
  print("Some other error")

- Get all keys and iterate over the dictionary

We can use the keys() method to get the list of all keys in the dictionary and then iterate over that list and access the values in the dictionary.

gender = dict()
gender["m"] = "Male"
gender["f"] = "Female"

keys = gender.keys()

for key in keys:

- Or you can directly iterate over the dictionary for key and value pairs using items() method.

gender = dict()
gender["m"] = "Male"
gender["f"] = "Female"

for item in gender.items():
  print(item[0], item[1])

Similarly for deleting a key-value from the dictionary, we can use the pop() method instead of del.

However, unlike get(), pop() method throws keyError if a key to be deleted doesn't exist and the second parameter is not passed.

So to avoid key error in case of key deletion, we must pass a default value to be returned, if the key is not found, as the second parameter to pop(),

>>> gender.pop("m")
>>> gender.keys()
>>> gender.pop("k")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'k'
>>> gender.pop("k", None)


Intellectual property Law and Coding

In the world of software, good code is a necessity, and great code can make the difference between a startup succeeding and failing. But how do you protect coding innovations that may be novel or unique?

Intellectual property law, or IP law, is the main legalistic framework that can answer many of those questions and more. Any business, and perhaps more crucially, any individual coder, should be aware of their options when it comes to maintaining the rights to their work. Here, we delve into some of the most important things to know about IP law and coding.

Where Does Intellectual Property Apply?

Intellectual property refers to intangible things that one can own. This can include the rights to a specific brand logo, a unique way of solving a software problem, or even composition.

There are four different types of intellectual property:

1. Copyrights, which cover anything legally termed “art,” i.e. songs, poems, paintings, etc.

2. Patents, which cover inventions, and enable a temporary monopoly on their production.
3. Trademarks, which deal with brand-related matters such as logos, catchphrases, and other things that can help consumers identify a company.
4. Trade Secrets, which, as their name implies, are any secrets or concepts that can give a business a competitive edge over another. 

So as a coder, which of these are important to your work?

Can I Patent My Code?

Software-related IP law can oftentimes be more tricky to figure out than IP law related to physical inventions because the concept of code and software itself is still relatively new.

Let’s say you come up with a much better, more efficient piece of code to perform a certain task that many other companies already perform. What domain of intellectual property would apply in this case?

For starters, you might be tempted to patent your idea. However, this would not work, for several reasons. The function of your code would fall under the “utility patent” umbrella, which covers the actual use and utility of an invention. Since other companies are already performing similar functions, just getting there in a different way, your utility would not be unique and novel, and therefore cannot be patented. 

So what is a viable option?

Copyrighting Code

Since you cannot patent the function of your code if it isn’t novel, what can you do about your new, more efficient process? It turns out that the code itself, not merely its function, has an important place in IP law.

Coding is a creative endeavor; therefore, it can be considered art just as much as a symphony or a book might be. It’s no coincidence that we refer to “writing” code. Given this aspect, you should probably copyright your work, right?

Wrong (maybe). Oftentimes, it is much more valuable to keep your code to yourself, especially the more unique your new process is. By copyrighting your code, you would make it publicly available. Even though you would have sole marketing rights in certain areas, other programmers would now know your secret, and could potentially build off that to enrich themselves.

J.D. Houvener, a Houston Patent Attorney, describes it this way:

“Really unique and effective code isn’t easy to make. I’ve spoken with many a programmer who has been tempted to copyright their work, partly because they want to show the world this new trick they came up with. But copyright is a one-way street: once you show people your secrets, they lose their novelty. Of course, for a coding technique that could be broadly applied to many industries and isn’t crucial to an employer, copyrighting is always an option, but the decision is a big one and should be approached with care!”

Code as a Trade Secret

Given all of this, treating your code as a trade secret may be your best bet. Remember, trade secrets are anything confidential that give a business a competitive edge. For code that accomplishes a task much more accurately or efficiently due to its ingenuity, that definition fits perfectly.

A lot of the time, the benefits from being able to be the best in your field due to great coding are much greater than what you would stand to gain if you bring your code to market and license or sell it. It’s always possible to “declassify” later on and bring your code into the public eye.

Filing your code as a trade secret gives you legal ammunition in case someone were to steal your code and use it for themselves, even with small tweaks and edits. Remember to do this as quickly as possible, and consult with a qualified IP law attorney.

In Summary

Intellectual property law is a crucial legal field to get familiar with the software industry. Coding is an art form and is not a skill that everyone has.

With any skill that requires ingenuity and creativity, IP law tends to get involved more, given the intellectual nature of the work. Remember to get well-informed on your options before sharing your code with anyone; you don’t want to give up something valuable for free!

Hopefully, this article helped explain some of the legal nuances that might affect you when it comes to coding. For more, visit our blog!

Host your Django application for free.

This guest post was written by Tori Lutz.

Please subscribe to get the latest articles in your mailbox.

Recent Posts:

© 2017-2019 Python Circle   Contact Us   Advertise with Us