[Answer]-Django – replacing string in whole project

0👍

After thinkig about this question I came to conclusion that the best option is the one with middleware.

class CustomWordsMiddleware(object):

   def process_response(self, request, response):

       if request.user.settings == 'lumberjack':
           response.content = response.content.replace("object", "tree")
           response.content = response.content.replace("objects", "trees")

       return response

Of course it is just example, I will also implement regexp instead of string replace. Moreover, I will use beautyful soup for parsing html to find classes where I should replace strings.

👤Arturo

1👍

Disclaimer: I think something wrong with your project if you have to do this. Did you consider using variables?

Under Linux, this command will replace “orange” to “whale” in all files under current directory

find -type f -exec sed -i s/orange/whale/ {} \;
👤Marat

0👍

I can think of 2 scenarios base your question

  1. A user can replace any string in the templates. (Here I am assuming strings can only be replaced in templates)
  2. Or you have predefined collection of strings which user can change or overwrite.

If your problem matches scenario 1 then it is very difficult to implement any simple and clean solution to solve your problem. May be you can give users an HTML editor to rewrite the contents of template.

But if your problem matches scenario 2 then you can put all these pre-defined keywords in any persistent storage in the form of key:value pairs and when a user logged in then load these key:value pairs for that user in memory. And make your templates get the values of predefined keys from the memory (may be through Django contextprocessor).

0👍

This is more like an project architecture problem.
The best way of doing what i “think” you want is to:

  1. create a list of the “strings” options in a database.
  2. In the user model create a field like “chosen_string”
  3. When the user selects the option to be used (the string) you just update the user model
  4. whenever you want to use the strings , just do a query.
👤LGama

Leave a comment