Change name of the "Authentication and Authorization" menu in Django/python - python

I'm learning python/Django and setting up my first project. All is going well but I've been searching like crazy on something very simple.
There is a default menu item "Authentication and Authorization" and I want to change the name. I've searched in the template if I need to extend something, I've searched if there's a .po file or what not but I can't find it nor a hint on which parameter I should overwrite in admin.py to set it.
I'm not trying to install multi language or some advanced localization, just want to change the name of that one menu item :)
Any ideas?

To follow up on Lorenzo's answer (Django 3.0):
Create a file with your custom AppConfig somewhere in your project
# 'authconfig.py'
from django.apps import AppConfig
class CustomAuthConfig(AppConfig):
name = 'django.contrib.auth'
verbose_name = 'my super special auth name'
Then, in settings.py:
INSTALLED_APPS = [
...
#'django.contrib.auth', # comment out to avoid duplicate apps
'authconfig.CustomAuthConfig', # add this in for custom config of auth module
...
]

Create a custom AppConfig pointing to original django.auth module and override verbose_name. Then use your custom AppConfig in INSTALLED_APPS instead of original auth app.
https://docs.djangoproject.com/en/1.10/ref/applications/#configuring-applications

This can't be done at least cleanly via templates..
You can put the auth app verbose name "authentication and authorization" in your own .po file (& follow Django docs on translation)
This way Django will normally use your name.

If you are using a custom locale (refer to How to override the django admin translation?) then the best way is to add these lines to the django.po file:
msgid "Authentication and Authorization"
msgstr "Your text for the auth app"
For some reason many localization files fail to include a translation for the "Authentication and Authorization" string. Adding it like that (and using the compilemessages command as mentioned in the link above) should work just fine.

Related

How can I redirect in django middleware? global name 'view' is not defined

Django newbie here, need help on basic middleware to redirect to another view if a certain model field is empty.
I am creating a terms of agreement page that users must get redirected to right after they signup to the platform if their filed_terms field on their Profile model is empty.
I am using middleware for this. However I am unable to get this to work. This is my middleware class:
class TermsMiddleware(object):
def process_request(self, request):
if request.user.profile.filled_terms is None:
return redirect(reverse(terms))
This gives me the following error:
global name 'terms' is not defined
I also have the url matcher that works perfectly when I navigate to it manually:
url(r'^terms/', 'my_app.views.terms')
I have a terms.html template and a terms view in my views.py file that is working perfectly in all other respects. I have also added it to the settings middleware requirements to make sure it loads.
Do I have to import something from views or url dispatcher into my middleware file? If so what would that be? I have been at this for a while an cannot find anything helpful.
reverse function takes url name instead on the regex. So you need to add name on your url configuration. Here is the example.
url(r'^terms/', 'my_app.views.terms', name='terms')
Add this in your views.py
from django.core.urlresolvers import reverse
And you need to fix your reverse function into.
return redirect(reverse('terms'))
Python interpret your terms as a variable and you have no variable named terms while you need to put string on reverse.

Django Postman Messaging

So i've got django-postman installed in my project. I've got the app installed and the urls are added but it's still not working.
When I try and send a message to the user test for example it's saying "Some usernames are unknown or no more active: test." which makes me think it's trying to use the wrong user model because the username exists in the database, it just can't find it.
I've got these in my settings if it helps.
POSTMAN_DISALLOW_ANONYMOUS = False
POSTMAN_DISALLOW_MULTIRECIPIENTS = False
AUTH_USER_MODEL = 'accounts.User'
Looking at the code for django-postman I have found out the issue. In postman.future_1_5.py it just imports User instead of what I need.
How can I change this code? Is there a way I can keep a file within my application and use that instead?
I'm thinking this will fix my issue:
from __future__ import unicode_literals
from accounts.models import MyUser
MyUser.USERNAME_FIELD = 'username'
MyUser.get_username = lambda self: self.username
def get_user_model():
return MyUser
Modifying future_1_5.py is not the solution to your issue, and is a very bad idea anyway. As its name implies, this file is intended to make the code runnable with Django before version 1.5.
I suppose you're running at least Django 1.5, so if this fallback is fired it means that your custom user model could not be imported.
The right explanation is that your setting is wrong. It has to name the effective model:
AUTH_USER_MODEL = 'accounts.MyUser'

how to render django template from code instead of file on Google App Engine

I am writing a Google App Engine webapp that renders some html to a Django template. I want to either render the template using either a file or just some json thats very similar to that in file. Is it possible to use Django to render this to a file that is read in and stored in database?
The oldAPI.HTML is just an old version of api.html but with some small changes. Rendering Django to the api-html file works fine.
I understand that you can't store files on GAE, how can i dynamically use Django to render to HTML stored in memory?
path = ""
oldAPI = APIVersion().get_by_key_name(version)
if oldAPI is None:
path = os.path.join(os.path.dirname(__file__), "api.html")
template_values = {
'responseDict': responseDict,
}
if path:
self.response.out.write(template.render(path, template_values))
else:
self.response.out.write(template.render(oldAPI.html,template_values))
In order to render a template 'in memory', there are a few things you'll need to do:
App Engine Setup
First of all, you'll need to ensure that everything is set up correctly for Django. There's a lot of information on the Third-party libraries page, but I'll include it here for your benefit.
In main.py, or (whatever your script handler is), you'll need to add the following lines:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.2') # Change to a different version as you like
Don't forget to include django in your app.yaml:
libraries:
- name: django
version: "1.2"
Code Setup
Second of all, you'll need to create a Template object, as denoted in the Google App Engine template documentation. For example:
from google.appengine.ext.webapp import template
# Your code...
template_string = "Hello World"
my_template = template.Template(template_string)
# `context` is optional, but will be useful!
# `context` is what will contain any variables, etc. you use in the template
rendered_output = template.render(context)
# Now, do what you like with `rendered_output`!
You can instantiate a template from text in Django with just template.Template(my_text).
Unfortunately, there's no (builtin) way to do so, but you can get inspired from the function google.appengine.ext.webapp.template._load_user_django (GAE with Python 2.5) or google.appengine.ext.webapp.template._load_internal_django (GAE with Python 2.7) and write your very own wrapper overriding settings and rendering like GAE source does.

Django changing app name of Photologue

i have installed photologue - A customizable plug-in photo management application for the Django web framework here into my project without problem...
now i want to change app name in admin page which is photologue. for this i have used ugettext_lazy but i got an error when i define this to all Meta:
from django.utils.translation import ugettext_lazy as _
class Meta:
app_label = _('newappname')
Error:
ValueError at /admin/
Cannot create form field for 'effect' yet, because its related model
'PhotoEffect' has not been loaded yet
Is there any easy way for changing app name, i have looked a lot but didnt find...
Django does not support app renaming in the admin right now, but ticket #3591 was raised to add that functionality, so hopefully it will be added.
There are several ways of acomplishing that. The simplest and preferred would be changing the main admin template and using whatever name you want as the app name there.
Other solutions:
How to change the name of a Django app?
https://stackoverflow.com/a/6312798/342473
http://djangosnippets.org/snippets/1882/

Django: Getting list of all URL regexes [duplicate]

Is there a way to get the complete django url configuration?
For example Django's debugging 404 page does not show included url configs, so this is not the complete configuration.
Django extensions provides a utility to do this as a manage.py command.
pip install django-extensions
Then add django_extensions to your INSTALLED_APPS in settings.py. then from the console just type the following
python manage.py show_urls
Django is Python, so introspection is your friend.
In the shell, import urls. By looping through urls.urlpatterns, and drilling down through as many layers of included url configurations as possible, you can build the complete url configuration.
import urls
urls.urlpatterns
The list urls.urlpatterns contains RegexURLPattern and RegexURLResolver objects.
For a RegexURLPattern object p you can display the regular expression with
p.regex.pattern
For a RegexURLResolver object q, which represents an included url configuration, you can display the first part of the regular expression with
q.regex.pattern
Then use
q.url_patterns
which will return a further list of RegexURLResolver and RegexURLPattern objects.
At the risk of adding a "me too" answer, I am posting a modified version of the above submitted script that gives you a view listing all the URLs in the project, somewhat prettified and sorted alphabetically, and the views that they call. More of a developer tool than a production page.
def all_urls_view(request):
from your_site.urls import urlpatterns #this import should be inside the function to avoid an import loop
nice_urls = get_urls(urlpatterns) #build the list of urls recursively and then sort it alphabetically
return render(request, "yourapp/links.html", {"links":nice_urls})
def get_urls(raw_urls, nice_urls=[], urlbase=''):
'''Recursively builds a list of all the urls in the current project and the name of their associated view'''
from operator import itemgetter
for entry in raw_urls:
fullurl = (urlbase + entry.regex.pattern).replace('^','')
if entry.callback: #if it points to a view
viewname = entry.callback.func_name
nice_urls.append({"pattern": fullurl,
"location": viewname})
else: #if it points to another urlconf, recur!
get_urls(entry.url_patterns, nice_urls, fullurl)
nice_urls = sorted(nice_urls, key=itemgetter('pattern')) #sort alphabetically
return nice_urls
and the template:
<ul>
{% for link in links %}
<li>
{{link.pattern}} ----- {{link.location}}
</li>
{% endfor%}
</ul>
If you wanted to get real fancy you could render the list with input boxes for any of the regexes that take variables to pass to the view (again as a developer tool rather than production page).
This question is a bit old, but I ran into the same problem and I thought I would discuss my solution. A given Django project obviously needs a means of knowing about all its URLs and needs to be able to do a couple things:
map from a url -> view
map from a named url -> url (then 1 is used to get the view)
map from a view name -> url (then 1 is used to get the view)
Django accomplishes this mostly through an object called a RegexURLResolver.
RegexURLResolver.resolve (map from a url -> view)
RegexURLResolver.reverse
You can get your hands on one of these objects the following way:
from my_proj import urls
from django.core.urlresolvers import get_resolver
resolver = get_resolver(urls)
Then, you can simply print out your urls the following way:
for view, regexes in resolver.reverse_dict.iteritems():
print "%s: %s" % (view, regexes)
That said, Alasdair's solution is perfectly fine and has some advantages, as it prints out some what more nicely than this method. But knowing about and getting your hands on a RegexURLResolver object is something nice to know about, especially if you are interested in Django internals.
The easiest way to get a complete list of registered URLs is to install contrib.admindocs then check the "Views" section. Very easy to set up, and also gives you fully browsable docs on all of your template tags, models, etc.
I have submitted a package (django-showurls) that adds this functionality to any Django project, it's a simple new management command that integrates well with manage.py:
$ python manage.py showurls
^admin/
^$
^login/$
^logout/$
.. etc ..
You can install it through pip:
pip install django-showurls
And then add it to your installed apps in your Django project settings.py file:
INSTALLED_APPS = [
..
'django_showurls',
..
]
And you're ready to go.
More info here -
https://github.com/Niklas9/django-showurls
If you want a list of all the urls in your project, first you need to install django-extensions
You can simply install using command.
pip install django-extensions
For more information related to package goto django-extensions
After that, add django_extensions in INSTALLED_APPS in your settings.py file like this:
INSTALLED_APPS = (
...
'django_extensions',
...
)
urls.py example:
from django.urls import path, include
from . import views
from . import health_views
urlpatterns = [
path('get_url_info', views.get_url_func),
path('health', health_views.service_health_check),
path('service-session/status', views.service_session_status)
]
And then, run any of the command in your terminal
python manage.py show_urls
or
./manage.py show_urls
Sample output example based on config urls.py:
/get_url_info django_app.views.get_url_func
/health django_app.health_views.service_health_check
/service-session/status django_app.views.service_session_status
For more information you can check the documentation.
Are you looking for the urls evaluated or not evaluated as shown in the DEBUG mode? For evaluated, django.contrib.sitemaps can help you there, otherwise it might involve some reverse engineering with Django's code.
When I tried the other answers here, I got this error:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
It looks like the problem comes from using django.contrib.admin.autodiscover() in my urls.py, so I can either comment that out, or load Django properly before dumping the URL's. Of course if I want to see the admin URL's in the mapping, I can't comment them out.
The way I found was to create a custom management command that dumps the urls.
# install this file in mysite/myapp/management/commands/urldump.py
from django.core.management.base import BaseCommand
from kive import urls
class Command(BaseCommand):
help = "Dumps all URL's."
def handle(self, *args, **options):
self.show_urls(urls.urlpatterns)
def show_urls(self, urllist, depth=0):
for entry in urllist:
print ' '.join((" " * depth, entry.regex.pattern,
entry.callback and entry.callback.__module__ or '',
entry.callback and entry.callback.func_name or ''))
if hasattr(entry, 'url_patterns'):
self.show_urls(entry.url_patterns, depth + 1)
If you are running Django in debug mode (have DEBUG = True in your settings) and then type a non-existent URL you will get an error page listing the complete URL configuration.

Categories

Resources