Django store regular expression in DB which then gets evaluated on page
- by John
Hi,
I want to store a number of url patterns in my django model which a user can provide parameters to which will create a url.
For example I might store these 3 urls in my db where %s is the variable parameter provided by the user:
www.thisissomewebsite.com?param=%s
www.anotherurl/%s/
www.lastexample.co.uk?param1=%s&fixedparam=2
As you can see from these examples the parameter can appear anywhere in the string and not in a fixed position.
I have 2 models, one holds the urls and one holds the variables:
class URLPatterns(models.Model):
pattern = models.CharField(max_length=255)
class URLVariables(models.Model):
pattern = models.ForeignKey(URLPatterns)
param = models.CharField(max_length=255)
What would be the best way to generate these urls by replacing the %s with the variable in the database.
would it just be a simple replace on the string e.g:
urlvariable = URLVariable.objects.get(pk=1)
pattern = url.pattern
url = pattern.replace("%s", urlvariable.param)
or is there a better way?
Thanks