Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages to using URLField over TextField?

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?

like image 611
HighLife Avatar asked Apr 07 '12 06:04

HighLife


2 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.

like image 169
okm Avatar answered Oct 20 '22 08:10

okm


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) 
like image 37
Vladislav Avatar answered Oct 20 '22 09:10

Vladislav