I'm actually coding a web app with django and just started to use django allauth to go a bit quicker in the creation of my user interface.
I've successfully changed the design of the templates by adding the templates from their github repo to my project. But I wanted to do the same with the translation because I want my app to be in french.
So I did the same : I added the "locale" folder to my project and edited some things in the .po files but no change happened.
Does someone know what to do, like what more is needed to override the ancient traductions ? Thanks in advance.
Overriteing code is not quicker way. In Django package allauth You got evrything you need. Read documantation:
https://django-allauth.readthedocs.io/en/latest/installation.html
But if you really wanna overrite code i dont recommend to copy all of file code from library. You can Simly overrite 1 function / class. If you will do that and pass diffrent arguments you get diffrent return sounds siple. But for reall Overrite code for me is hard option that you should do only when its need
Simple way how to overrite code:
class cl():
name = "Mephju"
def function(self, arg1, arg2):
print(arg1, arg2, self.name)
class overrite_cl():
name = "Mephju"
def function(self, arg1, arg2):
print(arg1, self.name)
print(overrite_cl)
This is bad example how to make it but i wanna make you understand. While Overriteing you pass same class parrent and then type function you wanna overrite.
Ok now my code example:
enter image description here
This is from library
enter image description here
red lines is thing that i changed. So as you can see This is same function but with diffrent return. I'm still returning this to same algorythm. But now its return something diffrent.
I dont know what are you trying to make in your web app but i'm shure thing you wanna make its allredy in django allauth.
Related
I am trying to add functionality similar to wordpress hooks in a flask application.
What I mean by that is that you could define extension points in your template where plugins could register callbacks to add/modify the output.
This is crazy, I know this is something I should not be doing, but I want to try anyway.
Basically, a hook would be called with something like that:
{{do('before_title')}}
<h1>{{title}}</h1>
{{do('after_title')}}
Hooks could be registered with:
hooked = defaultdict(lambda: [])
def do(event, *args):
return (cback(*args) for cback in hooked[event])
def add_action(event, cback):
hooked[event].append(cback)
app.jinja_env.globals['do'] = do
And when registering the hook, the code would look like that:
def print_stuff():
return 'some stuff to print'
add_action('before_title', print_stuff)
I was wondering if it would be possible to use the jinja environment to directly print the output, because, right now, if would have to loop in the templates, and it does not make for a fun api.
It would also be cool if I could register stuff like this:
def print_template(template):
# some magically obtained object representing the jinja template or env
template.include('before_title.html')
add_action('before_title', print_template)
It was actually quite simple.
def include_template():
return render_template('partials/before_title.html')
add_action('before_title', include_template)
And
def do(event, *args):
return ''.join(cback(*args) for cback in hooked[event])
So, I just started learning Django and I wanted to make an app. It's a simple app and I've just initialized my admin view and then I have a model named "Book". It's just like information about a book. The user can enter book name, author, description and upload a book cover image.
I got this working without a hiccup. But, currently, the image is being saved in the "/media" folder, because that's what I specified in the MEDIA_ROOT of the settings file (which is totally fine). Now, what I want is that instead of this in my models.py, it gets saved to it's own directory. For example :
Book Name : If god was a banker
I want the cover image to be saved in "/media/albums/If God Was A Banker".
How can I do this? I looked into the "upload_to" attribute of the "FileField". So, I tried something like this :
book_name = models.CharField(max_length=500, allow_blank=False,trim_whitespace=True)
comic_image = models.FileField(upload_to='%s/' % book_name)
and of course this didn't work, as book_name didn't return the str type (I knew it'll go wrong though). So, how can I get this to work? anything I'm missing or anything that I could do to achieve my goal?
upload_to argument can be callable.
So you can define function like this:
def upload_location(instance, filename):
return '{}/{}'.format(instance.book_name, filename)
and then use this function in model:
comic_image = models.FileField(upload_to=upload_location)
I'm studying the code of jinja2.ext.InternationalizationExtension provided with Jinja2.
I know that tags can be added via the tags attribute; Jinja2 template parser will relinquish control and call user code when one of those strings is the first token in a {% %} block.
class InternationalizationExtension(Extension):
"""This extension adds gettext support to Jinja2."""
tags = set(['trans'])
I learned from the code that an extension can add attributes to the environment by calling Environment.extend; for jinja2.ext.InternationalizationExtension this is done in the __init__ method:
def __init__(self, environment):
Extension.__init__(self, environment)
environment.globals['_'] = _gettext_alias
environment.extend(
install_gettext_translations=self._install,
install_null_translations=self._install_null,
install_gettext_callables=self._install_callables,
uninstall_gettext_translations=self._uninstall,
extract_translations=self._extract,
newstyle_gettext=False
)
I know that custom filters are added by registering functions into Environment.filters:
def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
return value.strftime(format)
environment.filters['datetimeformat'] = datetimeformat
The questions are:
Is it recommended that an extensions adds new filters, and not only tags and attributes to the environment? (The documentation suggests that this should be common practice)
Where in the extension subclass should this be done? In __init__ a reference to the environment is available, so in principle the above code could be put in the __init__ method.
Is it conceptually ok to do such thing in __init__? I personally don't like to alter objects states from within other objects' constructors, but in Jinja2 seems idiomatic enough to make it to an official extension (I'm talking about altering Environment.globals and calling Environment.extend from InternationalizationExtension.__init__).
Edit
A pattern to at least package filters nicely into a Python module. However this install function cannot be invoked from within a template (say, via a custom CallBlock created using an extension), because the environment should not be edited after the template has been instantiated.
def greet(value):
return "Hello %s!" % value
def curse(value):
return "Curse you, %s!" % value
def ohno(value):
return "Oh, No! %s!" % value
def install(env):
env.filters['greet'] = greet
env.filters['curse'] = curse
env.filters['ohno'] = ohno
Is it recommended that an extensions adds new filters, and not only tags and attributes to the environment?
Only if you need them. Otherwise, why overcomplicate your code? Filters are a very common use case for writing or extending other extensions, and the author most likely put that in there because they expect this to happen.
Where in the extension subclass should this be done?
It has to be done at call time, so if you don't directly put it in the __init__ you'll need to put it in a helper method called through __init__.
Is it conceptually ok to do such thing in __init__?
It's perfectly fine, so long as other users of your code can understand what it's doing. The simplest solution is usually the best.
I have two custom methods for a model manager in Django. One of them works. I recently added another and Django (and python) act like it doesn't exist. Here's the relevant part of the model:
class FigureServerManager(models.Manager):
#This method takes as input a user and grabs a figure that is not marked complete for which that user has not already submitted a result
def serve_to_user(self,user):
not_complete=super(FigureServerManager, self).get_query_set().filter(complete=0)
for Figure in not_complete:
checkifresult=User.objects.get(pk=user).result_set.all().filter(figure=Figure.id)
if not checkifresult:
return Figure
#This is a copy of the above method that I want to change to do something else, but I can't even get it to show up yet
def serve_training_task(self, user):
with_correct_ans=super(FigureServerManager, self).get_query_set().filter(complete=0)
for Figure in with_correct_ans:
checkifresult=User.objects.get(pk=user).result_set.all().filter(figure=Figure.id)
if not checkifresult:
return Figure
class Figure(models.Model):
doi=models.CharField(max_length=20)
url=models.CharField(max_length=200)
image=models.ImageField(upload_to='classify')
complete=models.BooleanField()
#include the default manager
objects=models.Manager()
#add the extra one for serving figures
serve_objects=FigureServerManager()
I get an error on the website (running the Django development server) like this:
'FigureServerManager' object has no attribute 'serve_training_task'
and if I run dir(FigureServerManager) in python the serve_training_task method does not appear but the serve_to_user method does appear. Why doesn't serve_training_task work?
Python Language Reference, ยง2.1.8: "Indentation"
I'm creating website based on Django (I know it's pure Python, so maybe it could be also answered by people who knows Python well) and I need to call some methods dynamically.
For example I have few applications (modules) in my website with the method "do_search()" in the views.py. Then I have one module called for example "search" and there I want to have an action which will be able to call all the existing "do_search()" in other applications. Of course I don't like to add each application to the import, then call it directly. I need some better way to do it dynamically.
I can read INSTALLED_APPS variable from settings and somehow run through all of the installed apps and look for the specific method? Piece of code will help here a lot :)
Thanks in advance!
Ignas
I'm not sure if I truly understand the question, but please clarify in a comment to my answer if I'm off.
# search.py
searchables = []
def search(search_string):
return [s.do_search(search_string) for s in searchables]
def register_search_engine(searchable):
if hasattr(searchable, 'do_search'):
# you want to see if this is callable also
searchables.append(searchable)
else:
# raise some error perhaps
# views.py
def do_search(search_string):
# search somehow, and return result
# models.py
# you need to ensure this method runs before any attempt at searching can begin
# like in models.py if this app is within installed_apps. the reason being that
# this module may not have been imported before the call to search.
import search
from views import do_search
search.register_search_engine(do_search)
As for where to register your search engine, there is some sort of helpful documentation in the signals docs for django which relates to this.
You can put signal handling and registration code anywhere you like. However, you'll need to make sure that the module it's in gets imported early on so that the signal handling gets registered before any signals need to be sent. This makes your app's models.py a good place to put registration of signal handlers.
So your models.py file should be a good place to register your search engine.
Alternative answer that I just thought of:
In your settings.py, you can have a setting that declares all your search functions. Like so:
# settings.py
SEARCH_ENGINES = ('app1.views.do_search', 'app2.views.do_search')
# search.py
from django.conf import settings
from django.utils import importlib
def search(search_string):
search_results = []
for engine in settings.SEARCH_ENGINES
i = engine.rfind('.')
module, attr = engine[:i], engine[i+1:]
mod = importlib.import_module(module)
do_search = getattr(mod, attr)
search_results.append(do_search(search_string))
return search_results
This works somewhat similar to registering MIDDLEWARE_CLASSES and TEMPLATE_CONTEXT_PROCESSORS. The above is all untested code, but if you look around the django source, you should be able to flesh this out and remove any errors.
If you can import the other applications through
import other_app
then it should be possible to perform
method = getattr(other_app, 'do_' + method_name)
result = method()
However your approach is questionable.