Using Django 1.10 I'd like to allow the \ character in a username because I'm working in a Windows environment utilizing 'django.contrib.auth.middleware.RemoteUserMiddleware', and the remote user comes in as domain\username (I have no desire to drop the domain as it is used in some business logic).
I can change django\contrib\auth\validators.py easily enough and have the desired affect by amending the line regex = r'^[\w.#+-]+$' to be regex = r'^[\w.#+-\\]+$' however, I thought one could override this class easily but I failed.
I've found some useful links (and many other similar here on SO):
https://stackoverflow.com/a/39820162/4872140
https://stackoverflow.com/a/1214660/4872140
https://docs.djangoproject.com/en/1.10/releases/1.10/#official-support-for-unicode-usernames
https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.User.username_validator
But the info is dated, or doesn't quite show exactly/completely how to solve my issue (in the case of the last two). I'm well into the app so changing the AUTH_USER_MODEL is not attractive.
settings.py:
AUTH_USER_MODEL = 'myapp.MyUser'
I tried anyway, thinking I may be able to use proxy on the User model like the following which results in the error "cannot proxy the swapped model 'myapp.DomainUser'":
class DomainASCIIUsernameValidator(ASCIIUsernameValidator):
regex = r'^[\w.#+-\\]+$'
class DomainUser(User):
username_validator = DomainASCIIUsernameValidator()
class Meta:
proxy = True
Is there a way to replace the regex in ASCIIUsernameValidator (and UnicodeUsernameValidator) in a way that the User model stays as is. If you subclass the user model as described at https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.User.username_validator are you stuck with specifying that in AUTH_USER_MODEL?
I've read through the discussion at https://groups.google.com/forum/#!topic/django-developers/MBSWXcQBP3k/discussion and feel like creating a custom user from the start may be way to go as a default case.
It took me an entire day and many different answers to get this working. I split up the code into the different parts. First, we have our validator:
validators.py
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.utils.translation import ugettext_lazy as _
class DomainUnicodeUsernameValidator(UnicodeUsernameValidator):
"""Allows \."""
regex = r'^[\w.#+-\\]+$'
message = _(
'Enter a valid username. This value may contain only letters, '
'numbers, and \/#/./+/-/_ characters.'
)
I added changes for the message to also say \ was allowed. You can also easily add DomainASCIIUsernameValidator.
models.py
from django.contrib.auth.models import User
from .validators import DomainUnicodeUsernameValidator
class DomainUser(User):
class Meta:
proxy = True
def __init__(self, *args, **kwargs):
self._meta.get_field(
'username'
).validators[0] = DomainUnicodeUsernameValidator()
super().__init__(*args, **kwargs)
This grabs the validator we set up before. It also proxys the default user and sets the validator for the username field. You can set the validator as a list to include the new validator and the max length validator (which is probably safer in case the order changes).
forms.py
from django.contrib.auth.forms import UserChangeForm
from django.utils.translation import ugettext_lazy as _
from .models import DomainUser
class DomainUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = DomainUser
help_texts = {
'username': _('Required. 150 characters or fewer. Letters, digits and \/#/./+/-/_ only.'), # NOQA
}
Here, I am extending the UserChangeForm and setting the model to the proxy model with the username validation change.
If you would like to allow for users to add user names with \, then you will also need to to change the UserAddForm in a similar way.
Lastly, in admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from .forms import DomainUserChangeForm
class DomainUserAdmin(UserAdmin):
form = DomainUserChangeForm
admin.site.unregister(User)
admin.site.register(User, DomainUserAdmin)
We set the form for our admin that will be used in the django admin pages. Then unset the User admin and replace it with our custom DomainUserAdmin.
Related
I know, this question has been already asked many times in SO, but most of the answers I read were either outdated (advising the now deprecated AUTH__PROFILE_MODULE method), or were lacking of a concrete example.
So, I read the Django documentation [1,2], but I lack a real example on how to use it properly.
In fact, my problem comes when a new user is created (or updated) through a form. The user is obviously created but, the fields from the extension are all unset. I know that the Django documentation is stating that:
These profile models are not special in any way - they are just Django models that happen to have a one-to-one link with a User model. As such, they do not get auto created when a user is created, but a django.db.models.signals.post_save could be used to create or update related models as appropriate.
But, I don't know how to do it in practice (should I add a a receiver and if 'yes', which one).
For now, I have the following (taken from the documentation for the sake of brevity):
File models.py
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User)
department = models.CharField(max_length=100)
File admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from my_user_profile_app.models import Employee
# Define an inline admin descriptor for Employee model
class EmployeeInline(admin.StackedInline):
model = Employee
can_delete = False
verbose_name_plural = 'employee'
# Define a new User admin
class UserAdmin(UserAdmin):
inlines = (EmployeeInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
File forms.py
class SignupForm(account.forms.SignupForm):
department = forms.CharField(label="Department", max_length=100)
class SettingsForm(account.forms.SignupForm):
department = forms.CharField(label="Department", max_length=100)
Then, in my code, I use it like this:
u = User.objects.get(username='fsmith')
freds_department = u.employee.department
But, Signup and Settings forms do not operates as expected and new values for the departement is not recorded.
Any hint is welcome !
I have looked at all the answers but none does really hold the solution for my problem (though some of you gave me quite good hints for looking in the right direction). I will summarize here the solution I have found to solve my problem.
First of all, I have to admit I didn't tell everything about my problem. I wanted to insert extra fields in the User model and use other apps such as the default authentication scheme of Django. So, extending the default User by inheritance and setting AUTH_USER_MODEL was a problem because the other Django applications were stopping to work properly (I believe they didn't use user = models.OneToOneField(settings.AUTH_USER_MODEL) but user = models.OneToOneField(User)).
As, it would have been too long to rewrite properly the other applications I am using, I decided to add this extra field through a One-to-One field. But, the documentation miss several points that I would like to fill in the following.
So, here is a complete example of adding an extra field to the User model with other applications using the same model.
First, write the description of the model gathering the extra fields that you want to add to your models.py file:
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
extra_field = models.CharField(max_length=100)
Then, we need to trigger the addition of an object UserProfile each time a User is created. This is done through attaching this code to the proper signal in the receiver.py file:
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from my_user_profile_app.models import UserProfile
#receiver(post_save, sender=User)
def handle_user_save(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
Now, if you want to be able to modify it through the administration interface, just stack it with the usual UserAdmin form in the admin.py file.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from my_user_profile_app.models import UserProfile
# Define an inline admin descriptor for UserProfile model
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
# Define a new User admin
class UserAdmin(UserAdmin):
inlines = (UserProfileInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
Then, it is time now to try to mix this extra field with the default Django authentication application. For this, we need to add an extra field to fill in the SignupForm and the SettingsForm through inheritance in the forms.py file:
import account.forms
from django import forms
class SignupForm(account.forms.SignupForm):
extra_field = forms.CharField(label="Extra Field", max_length=100)
class SettingsForm(account.forms.SignupForm):
extra_field = forms.CharField(label="Extra Field", max_length=100)
And, we also need to add some code to display and get properly the data that you have been added to the original User model. This is done through inheritance onto the SignupView and the SettingsView views in the views.py file:
import account.views
from my_user_profile_app.forms import Settings, SignupForm
from my_user_profile_app.models import UserProfile
class SettingsView(account.views.SettingsView):
form_class = SettingsForm
def get_initial(self):
initial = super(SettingsView, self).get_initial()
initial["extra_field"] = self.request.user.extra_field
return initial
def update_settings(self, form):
super(SettingsView, self).update_settings(form)
profile = self.request.user.userprofile
profile.extra_field = form_cleaned_data['extra_field']
profile.save()
class SignupView(account.views.SignupView):
form_class = SignupForm
def after_signup(self, form):
profile = self.created_user.userprofile
profile.extra_field = form_cleaned_data['extra_field']
profile.save()
super(SignupView, self).after_signup(form)
Once everything is in place, it should work nicely (hopefully).
I struggled with this topic for about a year off and on until I finally found a solution I was happy with, and I know exactly what you mean by "there is a lot out there, but it doesn't work". I had tried extending the User model in different ways, I had tried the UserProfile method, and some other 1-off solutions as well.
I finally figured out how to simply extend the AbstractUser class to create my custom user model which has been a great solution for many of my projects.
So, let me clarify one of your comments above, you really shouldn't be creating a link between 2 models, the generally accepted "best" solution is to have one model which is inherited from AbstractUser or AbstractBaseUser depending on your needs.
One tricky thing that got me was that "Extending the User Model" did not get me where I wanted and I needed to Substitute the User Model, which I'm sure you've seen/read multiple times, but possibly not absorbed it (at least I know I didn't).
Once you get the hang of it, there's really not that much code and it's not too complicated either.
# models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
'''
Here is your User class which is fully customizable and
based off of the AbstractUser from auth.models
'''
my_custom_field = models.CharField(max_length=20)
def my_custom_model_method(self):
# do stuff
return True
There are a couple things to look out for after this, some of which came up in django 1.7.
First of all, if you want the admin page to look like it did before, you have to use the UserAdmin
# admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
# Register your models here.
admin.site.register(get_user_model(), UserAdmin)
The other thing is that if you're wanting to import the User class in a models file, you have to import it from the settings and not with get_user_model(). If you run into this, it's easy to fix, so I just wanted to give you a heads up.
You can check out my seed project I use to start projects to get a full but simple project that uses a Custom User Model. The User stuff is in the main app.
From there all the Registration and Login stuff works the same way as with a normal Django User, so I won't go into detail on that topic. I hope this helps you as much as it has helped me!
I try to avoid to extend the user model as explained in the django docs.
I use this:
class UserExtension(models.Model):
user=models.OneToOneField(User, primary_key=True)
... your extra model fields come here
Docs of OneToOneField: https://docs.djangoproject.com/en/1.7/topics/db/examples/one_to_one/
I see these benefits:
the same pattern works for other models (e.g. Group)
If you have N apps, every app can extend the model on his own.
Creating the UserExtension should be possible without giving parameters. All fields must have sane defaults.
Then you can create a signal handler which creates UserExtension instances if a user gets created.
I prefer extend the User model. For example:
class UserProfile(User):
def __unicode__(self):
return self.last_name + self.first_name
department = models.CharField(max_length=100)
class SignupForm(forms.Form):
username = forms.CharField(max_length=30)
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
department = forms.CharField(label="Department", max_length=100)
To save the data
form = UserRegistrationForm(request.POST)
if form.is_valid():
client = UserProfile()
client.username = username
client.set_password(password)
client.first_name = first_name
client.department = department
client.save()
check how are you saving the data after validate the form
This question is a follow-up to the solution explained by Muki here:
Problem in adding custom fields to django-registration
I have installed and have been successfully using the Django-registration package. By default, when you create an account using this package, it asks for your username, email address and password. I want it to also ask for (optional) first name + last name. Muki's answer at the link above explains how to do so.
However, Muki left out what should go into the file that he creates in the custom/forms.py. I need to know what the name of the class I should create in here is and what the field definitions should look like.
Can someone please post a sample forms.py that I can use to accomplish what I'm trying to do?
If your custom backend is in the custom folder, then custom/forms.py could be something like this:
from django import forms
from registration.forms import RegistrationForm
class RegistrationFormWithName(RegistrationForm):
first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)
This adds your two optional fields to the default registration form. To tell your custom backend to use this new form instead of the default you need to change the get_form_class method in custom/__init__.py Muki's answer explains how to do that.
Of course, you'll also need to handle saving the data from the first_name and last_name fields.
Edit:
Your custom/__init__.py needs to look something like this:
from registration.backends.default import DefaultBackend
from registration.backends.custom.forms import RegistrationFormWithName
class CustomBackend(DefaultBackend):
def get_form_class(self, request):
return RegistrationFormWithName
And custom/urls.py needs a line like this:
url(r'^register/$', register, {'backend': 'registration.backends.custom.CustomBackend'}, name='registration_register'),
Change the name of the CustomBackend class in both files to whatever you're calling your new backend.
Have a look at the default backend source to get an idea of the other methods you can override. Hope that helps.
This link explains the process well and works with django-registration 1.0
here are a few extra pointers in addition to the above code.
To update the first name change this in the models.py
def user_registered_callback(sender, user, request, **kwargs):
profile = ExUserProfile(user = user)
profile.is_human = bool(request.POST["is_human"])
user.first_name = request.POST["firstname"]
user.save()
profile.save()
user_registered.connect(user_registered_callback)
and in the forms.py file
class ExRegistrationForm(RegistrationForm):
is_human = forms.BooleanField(label = "Are you human?:")
firstname = forms.CharField(max_length=30)
lastname = forms.CharField(max_length=30)
finally to see the changes on the form create an appropriate template. The profile can be seen in the admin by creating a file called admin.py in your app and write the following code
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from prof.models import ExUserProfile
admin.site.unregister(User)
class UserProfileInline(admin.StackedInline):
model = ExUserProfile
class UserProfileAdmin(UserAdmin):
inlines = [ UserProfileInline, ]
admin.site.register(User, UserProfileAdmin)
I'm building a website which contains several languages.
Therefore I need to set verbose names of all attributes in all my model classes (with the internationalizaton-helper). Unfortunately I don't find a way to change the verbose names of the user attributes...
And overwriting every single form isn't really a nice way to do it, right?
Thanks for your help!
Ron
It depends on what you need this for. Generally, verbose_name is only used within the context of the admin. If that's what you need to worry about, then you can create a proxy model and then make your user admin use that:
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class CustomUser(User):
class Meta:
proxy = True
app_label = 'auth'
verbose_name = _('My Custom User')
Then, in admin.py:
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from .models import CustomUser
admin.site.unregister(User)
admin.site.register(CustomUser, UserAdmin)
Since this is the first answer on google when searching for django verbose name I thought I'd correct Chris Pratt's answer from 2012 to be correct for django 2.0
If you only want to update the model name in the Admin panel you can simply add a Meta class to your user model. Note the slight change from Chris' answer.
class Meta:
verbose_name = 'My Custom User'
I am new in Django and even after trying thoroughly to find an answer for this question, I couldn't find any. =/
I am using UserCretionForm to create my users and I wanted to know a couple of things:
1 - How can I manage this form's properties? (e.g. I don't want to show the tips like "Required. 30 charact..." or "Enter the same password as above, for verification.")
2 - I want to make it show other customized fields. How can I do it? (please, try to be clear where I have to write the codes you'll show me as I am not an expert =D ). (e.g. Here in Brazil we have some national info I need to store. That is why I need these fields.)
Thanks in advance! (Y)
Changing the default validator messages
You can change the error messages for the default validators via the error_messages argument to a form field.
To find out which validators exist per field, check here: https://docs.djangoproject.com/en/dev/ref/forms/fields/#built-in-field-classes
class MyForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['username'].error_messages = {'invalid': 'foobar'}
self.fields['password1'].error_messages = {'required': 'required, man'}
Adding new fields to an existing form
If you want to add new fields, you'd add them via subclassing (which is just python).
If you subclass UserCreationForm and add a field to it, you end up with a new form class that simply has the original's fields and your new ones.
class MyForm(UserCreationForm):
extra_field = forms.CharField()
Overriding the admin form
If you are trying to override the UserCreationForm that the admin site uses by default, you'll have to register a new ModelAdmin for the User moder.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from foo import MyNewUserCreationForm
class NewUserAdmin(UserAdmin):
add_form = MyNewUserCreationForm
admin.site.unregister(User)
admin.site.register(User, NewUserAdmin)
I have a model that has a ForeignKey to the built-in user model in django.contrib.auth and I'm frustrated by the fact the select box in the admin always sorts by the user's primary key.
I'd much rather have it sort by username alphabetically, and while it's my instinct not to want to fiddle with the innards of Django, I can't seem to find a simpler way to reorder the users.
The most straightforward way I can think of would be to dip into my Django install and add
ordering = ('username',)
to the Meta class of the User model.
Is there some kind of monkeypatching that I could do or any other less invasive way to modify the ordering of the User model?
Alternatively, can anyone thing of anything that could break by making this change?
There is a way using ModelAdmin objects to specify your own form. By specifying your own form, you have complete control over the form's composition and validation.
Say that the model which has an FK to User is Foo.
Your myapp/models.py might look like this:
from django.db import models
from django.contrib.auth.models import User
class Foo(models.Model):
user = models.ForeignKey(User)
some_val = models.IntegerField()
You would then create a myapp/admin.py file containing something like this:
from django.contrib.auth.models import User
from django import forms
from django.contrib import admin
class FooAdminForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.order_by('username'))
class Meta:
model = Foo
class FooAdmin(admin.ModelAdmin):
form = FooAdminForm
admin.site.register(Foo, FooAdmin)
Once you've done this, the <select> dropdown will order the user objects according to username. No need to worry about to other fields on Foo... you only need to specify the overrides in your FooAdminForm class. Unfortunately, you'll need to provide this custom form definition for every model having an FK to User that you wish to present in the admin site.
Jarret's answer above should actually read:
from django.contrib.auth.models import User
from django.contrib import admin
from django import forms
from yourapp.models import Foo
class FooAdminForm(forms.ModelForm):
class Meta:
model = Foo
def __init__(self, *args, **kwds):
super(FooAdminForm, self).__init__(*args, **kwds)
self.fields['user'].queryset = User.objects.order_by(...)
class FooAdmin(admin.ModelAdmin):
# other stuff here
form = FooAdminForm
admin.site.register(Foo, FooAdmin)
so the queryset gets re-evaluated each time you create the form, as opposed to once, when the module containing the form is imported.