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?
EDIT It would also be nice if the user could choose to store either a single variable or a list of variables which would then replace a number of variables in the string e.g.
u = URLPatterns(pattern='www.url?param=%s¶m2=%s¶m3=%s')
v = URLVariables(pattern=u, param='[2,6,3]')
url = SOME WAY TO REPLACE THE 3 %s WITH THE 3 VARIABLES IN THE ARRAY (this would need to be converted from a string in someway)
Thanks