How to Create a URLField in Django



Python


In this article, we show how to create a URLField in Django.

A URLField is a field (of a database table or a form) that stores only URLs.

This could be useful for all types of reasons. One glaring example is to let a user enter his or her website.

Maybe you have a database table called Users, which has several fields of information about the user. This may include first name, last name, email, and the user's website (such as the user's personal website or linkedin home page, etc.).

The URLField in Django provides built-in validation so that only valid URLs can be entered.

So let's go over a database table now named ClubMember.

In this database table (model), ClubMember, we have the fields, first name, last name, email, and website.

The code for this table is shown below.



Okay, so again we have a database table called ClubMember.

The fields are the user's first name, last name, email and website.

So after doing the necessary migrations, including makemigrations and migrate commands, we have the following output shown below in admin.

Django URLField with an invalid URL

So this is the message we get after we type in an invalid URL into the URLField.

Once we have typed in a valid URL, the entry will be saved. If we now go back into the entry, we will get the following shown below.

Django URLField with a valid URL

So this is how URLFields work in Django.

It's a great way if you want to store any website or web address or any file on the web to make sure it is valid.

You don't have to write a validation function to decipher whether a URL is valid or not. Django has this built-in functionality in the URLField.


Related Resources

How to Insert Images into a Database Table with Python in Django

How to Insert Files into a Database Table with Python in Django

How to Insert Videos into a Database Table with Python in Django



HTML Comment Box is loading comments...