Skip to content

Completed Assignments #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file modified django_test/README.md
100644 → 100755
Empty file.
Empty file.
Empty file.
54 changes: 54 additions & 0 deletions django_test/django_test/applications/userprofile/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from django import forms
from django.contrib.auth.models import User
from django.contrib.localflavor.us.forms import USPhoneNumberField
from django.contrib.auth import authenticate

from models import Userprofile

from utils.tools import USPhoneNumberMultiWidget

class Userform(forms.ModelForm):


class Meta:
model = Userprofile
exclude = ('user',)

def __init__(self, *args, **kwargs):
super(Userform, self).__init__(*args, **kwargs)
self.fields.keyOrder = [
'username',
'firstname',
'lastname',
'email',
'telephone',
'password']

username = forms.CharField(min_length=5)
firstname = forms.CharField()
lastname = forms.CharField()
telephone = USPhoneNumberField(label="Phone", widget=USPhoneNumberMultiWidget())
email = forms.EmailField()
password = forms.CharField(max_length=32, widget=forms.PasswordInput)

def clean_username(self):
cd = self.cleaned_data
users = User.objects.filter(username__iexact=cd['username'])
if users.count() > 0:
raise forms.ValidationError("username is not unique")
return cd['username']


def save(self):
cd = self.cleaned_data
print cd['username']
user = User.objects.create_user(cd['username'], password=cd['password'], email=cd['email'])
user.save()
user = authenticate(username=cd['username'], password=cd['password'])
userprofile = Userprofile(
user=user,
telephone=cd['telephone'],
)
userprofile.save()
return userprofile

58 changes: 58 additions & 0 deletions django_test/django_test/applications/userprofile/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
try:
import simplejson as json
except:
import json

from django.db import models
from django.contrib.auth.models import User

class Userprofile(models.Model):

user = models.ForeignKey(User, related_name='profile')
telephone = models.CharField(max_length=15)



class Todo(models.Model):
user = models.ForeignKey(User, related_name="todo_list")
list = models.TextField()

def add(self, item, status='active'):
list = self.get_list()
list.append({'value':item, 'status':status})
self.list = json.dumps(list)
self.save()

def update(self, item):
list = self.get_list()
for l in list:
if l.get('value') == item:
if l['status'] == "active":
l['status'] = "complete"
else:
l['status'] = "active"
break

self.list = json.dumps(list)
self.save()
return l['status']

def remove(self, item):
list = self.get_list()
for l in list:
if l.get('value') == item:
list.pop(list.index(l))
break

self.list = json.dumps(list)
self.save()


def get_list(self):
if self.list is None or self.list == "":
todos = []
else:
print self.list
todos = json.loads(self.list)
return todos

30 changes: 18 additions & 12 deletions django_test/django_test/settings.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
# Django settings for django_test project.
import os
import sys

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append('%s/applications' % BASE_DIR)
sys.path.append('%s' % BASE_DIR)

DEBUG = True
TEMPLATE_DEBUG = DEBUG
Expand All @@ -11,15 +17,17 @@

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'test',# Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3.
#'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}

AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
Expand Down Expand Up @@ -106,6 +114,7 @@
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"%s/templates/"%BASE_DIR,
)

INSTALLED_APPS = (
Expand All @@ -115,6 +124,8 @@
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',

'userprofile',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
Expand All @@ -129,15 +140,10 @@
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},

'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
Expand Down
14 changes: 14 additions & 0 deletions django_test/django_test/templates/base.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@

<a href="/">Home</a> >>
{%if not user.is_authenticated%}
<a href="/login">login</a>
{%else%}
<a href="/todo">todo</a> >>
<a href="logout">logout</a>
{%endif%}
<br/>
<br/>

{%block content%}

{%endblock%}
10 changes: 10 additions & 0 deletions django_test/django_test/templates/home.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{%extends 'base.html'%}

{%block content%}
youre home

{%if user.is_authenticated%}
Welcome {{user.username}}
{%endif%}

{%endblock%}
31 changes: 31 additions & 0 deletions django_test/django_test/templates/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

<style>
#login{

width:250px;
height:100px;
margin:20px auto;
}
#login label{
display:inline-block;
width:85px;
}

</style>

<div id="login">
{% if errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="/login/{{parms}}">
{% csrf_token %}

<label for="username">Username</label> <input type=text id="username" name="username"/>
<label for="password">Password</label> <input type=password id="password" name="password"/>
<br/>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
</div>
8 changes: 8 additions & 0 deletions django_test/django_test/templates/register.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<form method="POST" action="/register/">
{% csrf_token %}
<table>
{{form.as_table}}
</table>

<input type="submit" value="submit"/>
</form>
113 changes: 113 additions & 0 deletions django_test/django_test/templates/todo.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
{%extends 'base.html'%}

{%block content%}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<style>
#todos{
width:300px;
margin:10px auto;


}
input[type='text']{
width:200px;
}
span.status, span.del{
line-height: 43px; /* 40 + a couple of pixels visual adjustment */
font-size: 20px;

text-shadow: 0 -1px 0 #bfbfbf;
width:40px;
height:40px;
display:inline-block;
cursor:pointer;
}
span.del{
color:red;
float:right;
display:None
}
span.status.active {
color: #d9d9d9;

}
span.status.complete {

color: green;

}

.item:hover .del{
display:inline-block;;

}

.filter{
cursor:pointer;
color:blue;
}
</style>
<script>
$(function(){
$("#newitem").focus().on('keypress',function(e){
var item = $(this).val()
if(e.which==13 && item.length > 2){
$.post("/save_todo/",{'todo':item}, function(ret){
if(ret.success){
window.location = window.location
}
})

}
})
$(".status").on('click',function(e){
var t = $(this)
var item = t.next().html()
$.post("/update_todo/",{'todo':item}, function(ret){
if(ret.success){
console.log(ret)
t.attr('class',"")
t.addClass("status")
t.addClass(ret.status)
}
})
})
$(".del").on('click',function(e){
var t = $(this)
var item = t.prev().html()
$.post("/remove_todo/",{'todo':item}, function(ret){
if(ret.success){
t.parents(".item").remove()
}
})
})
$(".filter").on('click',function(){
var t = $(this)
var status = t.attr('class').split("filter ")[1]
if(status!='all'){
$(".status:not(."+status+")").parents(".item").slideUp('fast')
$(".status."+status).parents(".item").slideDown('fast')
}else{
$(".item").slideDown('fast')
}
})
})
</script>
<div id="todos">
<input id="newitem" type="text" placeholder="What needs to be done"/>
<div id="list">
{%for item in list%}
<div class="item">
<span class="status {{item.status}}">&#10004;</span>
<span class='item_val'>{{item.value}}</span>
<span class='del'>X</span>
</div>
{%endfor%}
<span class="filter all" >all</span> |
<span class="filter active" >active</span> |
<span class="filter complete" >complete</span>
</div>
</div>

{%endblock%}
17 changes: 13 additions & 4 deletions django_test/django_test/urls.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from django.conf.urls import patterns, include, url
from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
from django.contrib import admin
# admin.autodiscover()
from views import *


urlpatterns = patterns('',
# Examples:
Expand All @@ -12,6 +14,13 @@
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^login/', login, name='login'),
url(r'^logout/', logout, name='logout'),
url(r'^register/', register, name='register'),
url(r'^todo/', todo, name='todo'),
url(r'^save_todo/', save_todo, name='save_todo'),
url(r'^update_todo/', update_todo, name='update_todo'),
url(r'^remove_todo/', remove_todo, name='remove_todo'),
#url(r'^admin/', include(admin.site.urls)),
url(r'^$', home, name='home'),
)
Empty file.
Loading