Skip to content

Commit

Permalink
deleted messages app, Implemented users
Browse files Browse the repository at this point in the history
  • Loading branch information
Jpadilla1 committed Jul 12, 2014
1 parent b0e962b commit da1b0ee
Show file tree
Hide file tree
Showing 18 changed files with 174 additions and 84 deletions.
Empty file removed chatrooms/messages/__init__.py
Empty file.
6 changes: 0 additions & 6 deletions chatrooms/messages/admin.py

This file was deleted.

1 change: 0 additions & 1 deletion chatrooms/messages/models.py

This file was deleted.

Empty file removed chatrooms/messages/tests.py
Empty file.
Empty file removed chatrooms/messages/urls.py
Empty file.
Empty file removed chatrooms/messages/views.py
Empty file.
18 changes: 18 additions & 0 deletions chatrooms/router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from django.conf.urls import patterns, include
from django.utils.module_loading import import_by_path


def get_api_urlpatterns(apps):
urls = []

for app in apps:
dotted_path = 'chatrooms.{}.urls.api_urlpatterns'.format(app)
urls.append((r'', include(import_by_path(dotted_path))))

return patterns('', *urls)


urlpatterns = get_api_urlpatterns([
'users',
# 'rooms',
])
21 changes: 9 additions & 12 deletions chatrooms/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ class Common(Configuration):
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',

# Third Party
'debug_toolbar',
Expand All @@ -34,12 +33,10 @@ class Common(Configuration):

# Apps
'chatrooms.users',
'chatrooms.messages',
'chatrooms.rooms',
)

MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
Expand All @@ -53,24 +50,26 @@ class Common(Configuration):
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',

# 'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.IsAuthenticated',
# ),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
'rest_framework.permissions.IsAuthenticated',
),
'PAGINATE_BY': 25,

'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.UnicodeJSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)
),
'DEFAULT_FILTER_BACKENDS': (
'rest_framework.filters.DjangoFilterBackend',
'rest_framework.filters.SearchFilter',
'rest_framework.filters.OrderingFilter',
),
}

# Swagger Rest Framework Doc Settings
SWAGGER_SETTINGS = {
"exclude_namespaces": [],
"api_version": '0.1',
"api_version": '1.0',
"api_path": "/",
"enabled_methods": [
'get',
Expand Down Expand Up @@ -107,7 +106,7 @@ class Common(Configuration):

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_ROOT = 'static'
# STATIC_ROOT = 'static'

STATIC_URL = '/static/'

Expand All @@ -119,8 +118,6 @@ class Common(Configuration):
os.path.join(BASE_DIR, 'templates'),
)

SITE_ID = 1

AUTH_USER_MODEL = 'users.User'


Expand Down
3 changes: 2 additions & 1 deletion chatrooms/urls.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
# from django.views.generic import TemplateView

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^api-v1/', include('chatrooms.router'))
)
26 changes: 25 additions & 1 deletion chatrooms/users/admin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,30 @@
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin

from .models import User
from .forms import UserChangeForm, UserCreationForm


admin.site.register(User)
class MyUserAdmin(UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
list_display = ('username', 'first_name', 'last_name', 'email', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
('Personal info', {'fields': ('email', 'first_name', 'last_name')}),
('Permissions', {'fields': ('is_admin',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'first_name',
'last_name', 'password1', 'password2')}),
)
search_fields = ('username', 'first_name', 'last_name', 'email',)
ordering = ('username', 'email', 'first_name', 'last_name')
filter_horizontal = ()

admin.site.register(User, MyUserAdmin)
admin.site.unregister(Group)
41 changes: 41 additions & 0 deletions chatrooms/users/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from .models import User


class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(
label='Password confirmation',
widget=forms.PasswordInput)

class Meta:
model = User
fields = ('email', 'first_name', 'last_name')

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 = User
fields = ('email', 'password', 'first_name',
'last_name', 'is_active', 'is_admin')

def clean_password(self):
return self.initial["password"]
41 changes: 23 additions & 18 deletions chatrooms/users/managers.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,32 @@
from django.utils import timezone
from django.contrib.auth.models import BaseUserManager


class UserManager(BaseUserManager):
def create_user(self, username, first_name, last_name,
email, password=None):
if not email:
raise ValueError('Users must have an email address')

user = self.model(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
)

def _create_user(self, username, email, password,
is_staff, is_superuser, **extra_fields):
now = timezone.now()
if not username:
raise ValueError('The given username must be set')
email = self.normalize_email(email)
user = self.model(username=username, email=email,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user

def create_user(self, username, email=None, password=None, **extra_fields):
return self._create_user(username, email, password, False, False,
**extra_fields)

def create_superuser(self, username, email, password, **extra_fields):
return self._create_user(username, email, password, True, True,
**extra_fields)
def create_superuser(self, username, first_name, last_name,
email, password):
user = self.create_user(
username=username,
email=email,
password=password,
first_name=first_name,
last_name=last_name,
)
user.is_admin = True
user.save(using=self._db)
return user
62 changes: 24 additions & 38 deletions chatrooms/users/models.py
Original file line number Diff line number Diff line change
@@ -1,56 +1,36 @@
from django.db import models
from django.utils import timezone
from django.core import validators
from django.contrib.auth.models import AbstractBaseUser

from .managers import UserManager
from .utils import get_gravatar_url
from .managers import UserManager


class User(AbstractBaseUser):
class Meta:
ordering = ['username', ]

username = models.CharField(
'username', max_length=30, unique=True,
help_text='Required. 30 characters or fewer. Letters, digits and '
'@/./+/-/_ only.',
validators=[
validators.RegexValidator(
r'^[\w.@+-]+$',
'Enter a valid username. '
'This value may contain only letters, numbers '
'and @/./+/-/_ characters.', 'invalid'),
],
error_messages={
'unique': "A user with that username already exists.",
})

username = models.CharField(max_length=15, unique=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
gravatar_url = models.URLField(blank=True)
email = models.EmailField('email address', blank=True, unique=True)
is_staff = models.BooleanField(
'staff status', default=False,
help_text='Designates whether the user can log into this admin '
'site.')
is_active = models.BooleanField(
'active', default=True,
help_text='Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.')
date_joined = models.DateTimeField('date joined', default=timezone.now)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)

objects = UserManager()

USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
REQUIRED_FIELDS = ['email', 'first_name', 'last_name']

def __str__(self):
return self.username
def get_full_name(self):
return "%s %s" % (self.first_name, self.last_name)

def save(self, *args, **kwargs):
if not self.pk or self.has_field_changed('email'):
self.gravatar_url = get_gravatar_url(self.email)
def get_short_name(self):
return self.first_name

return super(User, self).save(*args, **kwargs)
def __str__(self):
return self.email

def has_perm(self, perm, obj=None):
return True
Expand All @@ -61,3 +41,9 @@ def has_module_perms(self, app_label):
@property
def is_staff(self):
return self.is_admin

def save(self, *args, **kwargs):
if not self.pk:
self.gravatar_url = get_gravatar_url(self.email)

return super(User, self).save(*args, **kwargs)
10 changes: 10 additions & 0 deletions chatrooms/users/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from .models import User

from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'first_name',
'last_name', 'gravatar_url')
3 changes: 0 additions & 3 deletions chatrooms/users/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +0,0 @@
from django.test import TestCase

# Create your tests here.
11 changes: 7 additions & 4 deletions chatrooms/users/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from django.conf.urls import patterns, url
from rest_framework import routers

from .views import UserViewSet

urlpatterns = patterns(
'',
)

router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

api_urlpatterns = router.urls
14 changes: 14 additions & 0 deletions chatrooms/users/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from .models import User

from rest_framework import viewsets

from .serializers import UserSerializer


class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_fields = ('username', 'email', 'first_name', 'last_name')
search_fields = ('username', 'email', 'first_name', 'last_name')
ordering = ('username',)
ordering_fields = ('username', 'email', 'first_name', 'last_name')
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ django-configurations==0.8
django-debug-toolbar==1.2.1
django-dotenv==1.2
django-extensions==1.3.8
django-filter==0.7
django-rest-swagger==0.1.14
djangorestframework==2.3.14
gunicorn==19.0.0
Expand Down

0 comments on commit da1b0ee

Please sign in to comment.