Skip to content

Commit

Permalink
refactor: prevent user from creating more than 5 profiles
Browse files Browse the repository at this point in the history
  • Loading branch information
moonlitgrace committed Nov 12, 2024
1 parent 1b96054 commit e852dce
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 10 deletions.
14 changes: 8 additions & 6 deletions backend/backend/apps/user/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
from django.utils.translation import gettext_lazy as _

from .models import Profile, User
from .forms import CustomUserAdminForm
from .forms import CustomUserAdminForm, ProfileAdminForm


@admin.register(User)
class CustomUserAdmin(UserAdmin):
# form = CustomUserAdminForm
add_form = CustomUserAdminForm

fieldsets = (
(None, {'fields': ('email', 'password')}),
(
Expand Down Expand Up @@ -36,13 +39,12 @@ class CustomUserAdmin(UserAdmin):
ordering = ('email',)
filter_horizontal = ()

# form = CustomUserAdminForm
add_form = CustomUserAdminForm


@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = ('username', 'user')
search_fields = ('username',)
form = ProfileAdminForm

list_display = ('username', 'user__email', 'date_created')
search_fields = ('username', 'user__email')
ordering = ('-date_created',)
readonly_fields = ('date_created',)
19 changes: 17 additions & 2 deletions backend/backend/apps/user/forms.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
from django import forms
from django.forms import ModelForm
from .models import User
from django.utils.translation import gettext_lazy as _
from .models import User, Profile


class CustomUserAdminForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput, required=False)

class Meta: # pyright: ignore [reportIncompatibleVariableOverride]
model = User
fields = ('email', 'password', 'is_active', 'is_staff', 'is_superuser')
fields = '__all__'

def save(self, commit=True):
user = super().save(commit=False)
Expand All @@ -18,3 +19,17 @@ def save(self, commit=True):
if commit:
user.save()
return user


class ProfileAdminForm(ModelForm):
class Meta: # pyright: ignore [reportIncompatibleVariableOverride]
model = Profile
fields = '__all__'

def clean(self): # pyright: ignore [reportIncompatibleVariableOverride]
user = self.cleaned_data.get('user')

if self.instance.pk is None and user and user.profiles.count() >= 5:
self.add_error(None, _('A user cannot have more than 5 profiles.'))

return self.cleaned_data
14 changes: 12 additions & 2 deletions backend/backend/apps/user/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.core.exceptions import ValidationError
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.utils.translation import gettext_lazy as _
Expand Down Expand Up @@ -33,7 +34,7 @@ class User(AbstractBaseUser, PermissionsMixin):


class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='profiles', on_delete=models.CASCADE)
username = models.CharField(_('username'), unique=True, max_length=25)
avatar = models.ImageField(
_('avatar'),
Expand All @@ -45,5 +46,14 @@ class Profile(models.Model):
last_name = models.CharField(_('last name'), max_length=255, blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)

def save(self, *args, **kwargs):
if (
self.pk is None
and self.user.profiles.count() # pyright: ignore [reportAttributeAccessIssue]
>= 5
):
raise ValidationError("A user cannot have more than 5 profiles")
super().save(*args, **kwargs)

def __str__(self):
return f"q/{self.username}"
return f"u/{self.username}"

0 comments on commit e852dce

Please sign in to comment.