As I understand it you should always use a TextField
for a variable length string when your using a PostgreSQL database because the speed difference between a TextField
and a CharField
is negligible with PostgreSQL. I'm relativly new to Django, and was considering using a TextField
for variable length urls in my database. I was wondering if there are any advantages to using the URLField
? Would it be considered bad form to use a TextField
rather than a URLField
for urls?
3 Answers
URLField is actually CharField w/ supporting of Regexp-based URL pattern checking and a online validator(which was replaced by a RegEx based validator), you could use TextField if you don't care length-limitation of URL
from django.core.validators import URLValidator
# in model
field = models.TextField(validators=[URLValidator()])
Furthermore, using of CharField or TextField depends on whether you want max-length constraint on the field, and which element type is more suitable for editing: textarea or input. On PostgreSQL side, there is no significant difference.

- 23,575
- 5
- 83
- 90
-
16For the record, [IE can't load URLs longer than about 2,000 chars](https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers), so you could just set `max_length` to 2000 on a `URLField` and call it a day. – mlissner May 26 '15 at 17:55
-
Any reference to the deprecation of URLField ? – pravin Feb 07 '18 at 19:20
-
2@pravin It is not the URLField but its previous validator been deprecated. The validator was accessing the URL online to verify, for now it is replaced by a regex validator to check the validation of URL format. – okm Feb 09 '18 at 04:49
-
1URLField default to max_length of 200, unless you specify some other value – Vaibhav Vishal Jan 03 '19 at 07:00
Try this class:
class LongURLField(TextField):
description = 'Long URL'
def __init__(self, verbose_name=None, name=None, **kwargs):
TextField.__init__(self, verbose_name, name, **kwargs)
self.validators.append(validators.URLValidator())
def formfield(self, **kwargs):
# As with TextField, this will cause URL validation to be performed
# twice.
defaults = {
'form_class': forms.URLField,
}
defaults.update(kwargs)
return super(LongURLField, self).formfield(**defaults)

- 1,318
- 16
- 15
https://docs.djangoproject.com/en/dev/ref/models/fields/#urlfield Of course you can use CharField/TextField but handling user input and be sure whatever user enters is up-to you.
From the source code:
# As with CharField, this will cause URL validation to be performed
If you see the URLField source code you will find it's actually a CharField with URL validator.
Also there is other ready to use fields such as EmailField, ImageField, *Field!

- 674
- 7
- 19

- 3,462
- 3
- 26
- 36