Re: Django Custom User Admin Login
So I solved the problem. Even I don't know how. :/
I used this as a template and added my own models and requirements on top of it.
Slightly off topic but I needed this setup because I want to grant users object level permissions. django-guardian looked like a match but I'm having trouble making it work with custom user models. The developer of guardian has a warning for custom users.
Since the template I used to create my custom user had admin.site.unregister(Group) included in the admin.py file, guardian throws:
|--- customauth
|--- management
|--- migrations
|--- admin.py // same as used in the initial post, slight additions
|--- models.py // same as used in the initial post, slight additions
|--- views.py
|--- customuser
|--- setting.py
|--- urls.py
|--- client001
|--- admin.py // posted below
|--- models.py // posted below
|--- views.py
So, I have a separate app for each client (customer) that registers for my app. Each client can have multiple users with each user having permission to 'view' a 'stream' or not. The main app stores a list of all users and all clients.
customauth/models.py
customauth/admin.py
client001/models.py
-- I used this as a template and added my own models and requirements on top of it.
Slightly off topic but I needed this setup because I want to grant users object level permissions. django-guardian looked like a match but I'm having trouble making it work with custom user models. The developer of guardian has a warning for custom users.
Since the template I used to create my custom user had admin.site.unregister(Group) included in the admin.py file, guardian throws:
'MyUser' has no attribute 'groups' error. Allowing groups to register shows the same error. Do we need to implement custom groups when we use custom users? As of now, I don't need the group functionality - so it'd be great if there is a work around.
Here is my architecture:
|--- customuser|--- customauth
|--- management
|--- migrations
|--- admin.py // same as used in the initial post, slight additions
|--- models.py // same as used in the initial post, slight additions
|--- views.py
|--- customuser
|--- setting.py
|--- urls.py
|--- client001
|--- admin.py // posted below
|--- models.py // posted below
|--- views.py
So, I have a separate app for each client (customer) that registers for my app. Each client can have multiple users with each user having permission to 'view' a 'stream' or not. The main app stores a list of all users and all clients.
customauth/models.py
class Address(models.Model):
country = models.CharField(_('Country'), max_length=100, blank=True)
*** ommited ***
street_line3 = models.CharField(_('Address Line 3'), max_length=100, blank=True)
class Client(models.Model):
cID = models.IntegerField(primary_key=True, blank=False)
*** ommited ***
address = models.ForeignKey(Address, related_name='located_at')
class MyUserManager(BaseUserManager):
def create_user(self, email, username, password=None):
*** ommited ***
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
*** ommited ***
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
db_index=True,
)
username = models.CharField(max_length=254, unique=True, blank=False, db_index=True)
*** ommited ***
corp = models.ForeignKey(Client, related_name="employee_of", null=True)
objects = MyUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
customauth/admin.py
admin.site.register(Address)
admin.site.register(Client)
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = ZenatixUser
fields = ('email', 'username')
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = ZenatixUser
fields = ['username', 'corp', 'first_name', 'last_name', 'email', 'password', 'date_of_birth', 'is_active',
'is_admin']
def clean_password(self):
return self.initial["password"]
class MyUserAdmin(UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
list_display = ('username', 'corp', 'email', 'is_admin')
list_filter = ('corp',)
fieldsets = (
(None, {'fields': ('username', 'email', 'corp', 'password')}),
('Personal info', {'fields': ('date_of_birth', 'first_name', 'last_name')}),
('Permissions', {'fields': ('is_admin', 'is_active')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2', 'corp')}
),
)
search_fields = ('username',)
ordering = ('username',)
filter_horizontal = ()
admin.site.register(ZenatixUser, MyUserAdmin)
#admin.site.unregister(Group)
client001/models.py
class Stream(models.Model):
id = models.AutoField(primary_key=True)
uuid = models.CharField(unique=True, max_length=36, db_index=True)
metadata = hstore.DictionaryField(db_index=False, default={'key':'value'})
objects = hstore.HStoreManager()
class Meta:
permissions = (
('read_stream', 'Read Stream'),
)
class ClientInfo(models.Model):
corp = models.ForeignKey(Client, blank=False, db_index=True, related_name='+')
def save(self, *args, **kwargs):
if ClientInfo.objects.all().count()>0:
print ClientInfo.objects.all()
raise ValueError("Only one corp can be registered per client")
else:
super(ClientInfo, self).save(*args, **kwargs)
client001/admin.py
admin.site.register(ClientInfo)
class StreamAdmin(GuardedModelAdmin):
prepopulated_fields = {"uuid": ("metadata",)}
list_display = ('uuid', 'metadata')
search_fields = ('uuid', 'metadata')
#ordering = ('-created_at',)
#date_hierarchy = 'created_at'
admin.site.register(Stream, StreamAdmin)
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a0d8127a-413f-4445-8ddd-2dfc0a39b97c%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home