Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Comparing changes

Choose two branches to see what's changed or to start a new pull request. If you need to, you can also compare across forks.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also compare across forks.
...
head fork: andreysobol/42test
Checking mergeability… Don't worry, you can still create the pull request.
  • 19 commits
  • 15 files changed
  • 0 commit comments
  • 1 contributor
Commits on Mar 11, 2012
@andreysobol many fixes b3899d7
@andreysobol Merge branch 't1_show_bio' into t2_request_middleware
Conflicts:
	testsobol/mainapp/tests.py
	testsobol/mainapp/views.py
	testsobol/urls.py
c980321
@andreysobol ticket3: pep8, named url, 10 first, test <10 request c52e8b2
@andreysobol Merge branch 't2_request_middleware' into t4_settings_in_context
Conflicts:
	testsobol/mainapp/tests.py
bfa1afd
@andreysobol ticket4: pep8, fix test context 512e72f
@andreysobol Merge branch 't4_settings_in_context' into t5_forms_and_auth
Conflicts:
	testsobol/mainapp/models.py
	testsobol/mainapp/tests.py
	testsobol/mainapp/views.py
	testsobol/templates/index.html
	testsobol/urls.py
3a44bf4
@andreysobol ticket5: pep8, test all edit, req 14b87f4
@andreysobol Merge branch 't5_forms_and_auth' into t6_ajax
Conflicts:
	testsobol/mainapp/tests.py
	testsobol/mainapp/views.py
31b9007
@andreysobol ticket6: pep8, input readonly fef71af
@andreysobol Merge branch 't6_ajax' into t7_reversed
Conflicts:
	testsobol/mainapp/tests.py
	testsobol/mainapp/utils.py
79d764d
@andreysobol ticket7: pep8, remove render in model 79e15c8
@andreysobol Merge branch 't7_reversed' into t8_tag
Conflicts:
	testsobol/mainapp/tests.py
aa75af9
@andreysobol ticket9: pep8 be9dde8
@andreysobol Merge branch 't8_tag' into t9_command
Conflicts:
	testsobol/mainapp/tests.py
b9a2ef6
@andreysobol ticket9: pep8 097ed64
@andreysobol Merge branch 't9_command' into t10_signal
Conflicts:
	testsobol/mainapp/tests.py
92a6ef5
@andreysobol ticket10: pep8 996fb38
@andreysobol Merge branch 't10_signal' into t13_customer
Conflicts:
	testsobol/mainapp/models.py
	testsobol/mainapp/tests.py
	testsobol/mainapp/views.py
49c52bd
@andreysobol ticket13: pep8 a72df5c
View
1  requirements.txt
@@ -1,2 +1,3 @@
Django==1.3
+pil
wsgiref==0.1.2
View
2  testsobol/Makefile
@@ -0,0 +1,2 @@
+test:
+ python manage.py test mainapp
View
3  testsobol/mainapp/context_processor.py
@@ -1,4 +1,5 @@
from django.conf import settings
+
def settings_context_processor(request):
- return {'settings':settings}
+ return {'settings': settings}
View
12 testsobol/mainapp/forms.py
@@ -5,15 +5,18 @@
from models import Bio
from utils import Render
+
class ImgWidget(ClearableFileInput):
def render(self, name, value, attrs=None):
substitutions = {}
template = u'%(input)s'
- substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)
+ substitutions['input'] = super(ClearableFileInput, self)\
+ .render(name, value, attrs)
if value and hasattr(value, "url"):
template = u'%(initial)s<br />%(input)s'
- substitutions['initial'] = (u'<img src="%s"/>' % (escape(value.url)))
+ substitutions['initial'] = (u'<img src="%s"/>' %\
+ (escape(value.url)))
return mark_safe(template % substitutions)
@@ -25,7 +28,10 @@ class Meta:
}
def render(self):
- form_field = dict([(field.name, {'label':field.label,'value':field.as_widget(),'errors':field.errors}) for field in self])
+ form_field = dict([(field.name,
+ {'label':field.label,
+ 'value':field.as_widget(),
+ 'errors':field.errors}) for field in self])
get = lambda item: form_field[item]
View
4 testsobol/mainapp/management/commands/printmodels.py
@@ -2,9 +2,11 @@
from django.db import models
import sys
+
class Command(NoArgsCommand):
def handle(self, *args, **options):
- p = unicode([(cls.__name__,cls.objects.count()) for cls in models.get_models()])
+ p = unicode([(cls.__name__, cls.objects.count())
+ for cls in models.get_models()])
print p
print >> sys.stderr, 'error: ' + p,
View
3  testsobol/mainapp/middleware.py
@@ -2,8 +2,9 @@
from models import Request
+
class RequestMiddleware(object):
-
+
def process_request(self, request):
r = Request()
r.date = datetime.now()
View
22 testsobol/mainapp/models.py
@@ -1,9 +1,8 @@
from django.db import models
from django.db.models.signals import post_save, post_delete
-from utils import Render
-class Bio(models.Model, Render):
+class Bio(models.Model):
name = models.CharField(max_length=250, verbose_name='Name')
surname = models.CharField(max_length=250, verbose_name='Last name')
birth = models.DateField(verbose_name='Date of birth')
@@ -14,18 +13,13 @@ class Bio(models.Model, Render):
bio = models.TextField(verbose_name='Bio')
img = models.ImageField(verbose_name='Photo', upload_to='img/')
- def render(self):
- field_types = dict([(field.name, field.verbose_name) for field in self._meta.fields])
-
- get = lambda item: {'value':unicode(getattr(self,item)) if item!='img' else '<img src="%s" />' % getattr(self,item).url,'label':field_types[item]}
-
- return self.get_struct(get, False)
class Request(models.Model):
date = models.DateTimeField()
url = models.CharField(max_length=250)
ip = models.CharField(max_length=250)
+
class RequestPriority(models.Model):
url = models.CharField(max_length=250)
priority = models.IntegerField()
@@ -33,24 +27,28 @@ class RequestPriority(models.Model):
def __unicode__(self):
return 'url="' + self.url + '" prioryty=' + str(self.priority)
+
class Log(models.Model):
date = models.DateTimeField(auto_now_add=True)
model = models.CharField(max_length=250)
signal = models.CharField(max_length=250)
+
def save(sender, **kwargs):
if sender != Log:
if kwargs['created']:
- signal='create'
+ signal = 'create'
else:
- signal='update'
+ signal = 'update'
- log = Log(model = sender.__name__, signal = signal)
+ log = Log(model=sender.__name__, signal=signal)
log.save()
+
def delete(sender, **kwargs):
- log = Log(model = sender.__name__, signal = 'delete')
+ log = Log(model=sender.__name__, signal='delete')
log.save()
+
post_save.connect(save)
post_delete.connect(delete)
View
6 testsobol/mainapp/templatetags/my_tags.py
@@ -1,8 +1,10 @@
from django.template import Library, Node, Variable
from django.core.urlresolvers import reverse
+
register = Library()
+
class EditAdmin(Node):
def __init__(self, edit):
@@ -10,7 +12,9 @@ def __init__(self, edit):
def render(self, context):
e = self.edit.resolve(context)
- return u'<a href="%s">Edit</a>' % reverse('admin:%s_%s_change' % (e._meta.app_label, e._meta.module_name), args=(e.id,))
+ return u'<a href="%s">Edit</a>' %\
+ reverse('admin:%s_%s_change' %\
+ (e._meta.app_label, e._meta.module_name), args=(e.id,))
def ed(parser, token):
View
137 testsobol/mainapp/tests.py
@@ -17,14 +17,12 @@
class IndexViewTest(TestCase):
def test(self):
- fixtures = ['initial_data.json']
-
page = self.client.get('')
self.assertEqual(page.status_code, 200)
-
- for key,value in model_to_dict(Bio.objects.get(pk = 1)).items():
- if key!='id':
+
+ for key, value in model_to_dict(Bio.objects.get(pk=1)).items():
+ if key != 'id':
self.assertTrue(page.content.find(unicode(value)) != -1)
@@ -32,7 +30,11 @@ class RequestTest(TestCase):
def test(self):
page = self.client.get('')
- self.assertTrue(bool(Request.objects.filter(date__gte = (datetime.now() - timedelta(minutes=1)))))
+
+ self.assertEqual(page.status_code, 200)
+
+ self.assertTrue(bool(Request.objects.filter(
+ date__gte=(datetime.now() - timedelta(minutes=1)))))
class RequestViewTest(TestCase):
@@ -42,28 +44,42 @@ def test(self):
self.assertEqual(page.status_code, 200)
self.assertTrue(bool(page.context['custom_request']))
+
class SettingsContextTest(TestCase):
-
+
def test(self):
page = self.client.get('')
self.assertEqual(page.status_code, 200)
self.assertTrue(page.context['settings'])
+ self.assertEqual(page.context['settings'].STATIC_URL, '/static/')
class Edit(TestCase):
-
- def test(self):
- fixtures = ['initial_data.json']
- page = self.client.post('/accounts/login/', {'username': 'admin', 'password': 'admin'})
+ def test(self):
+ page = self.client.post('/accounts/login/',
+ {'username': 'admin', 'password': 'admin'})
self.assertEqual(page.status_code, 302)
-
- page = self.client.post('/edit/', {"bio": "Noooooooooooooo", "surname": "Sobol", "name": "Andrey", "other": "pigeon post - white pigeon only", "birth": "1990-09-18", "skype": "andreysobol", "jabber": "pisecs@gmail.com", "email": "asobol@mail.ua"})
+
+ s = {"bio": "Noooooooooooooo",
+ "surname": "Sobol",
+ "name": "Andrey",
+ "other": "pigeon post - white pigeon only",
+ "birth": "1990-09-18",
+ "skype": "andreysobol",
+ "jabber": "pisecs@gmail.com",
+ "email": "asobol@mail.ua"}
+ page = self.client.post('/edit/', s)
self.assertEqual(page.status_code, 200)
self.assertTrue(page.content == 'Okay')
- self.assertTrue(Bio.objects.get(pk = 1).bio == "Noooooooooooooo")
-
- page = self.client.post('/edit/', {"bio": "Noooooooooooooo", "surname": "Sobol", "name": "Andrey", "other": "pigeon post - white pigeon only"})
+ for t in s:
+ self.assertEqual(unicode(getattr(Bio.objects.get(pk=1), t)), s[t])
+
+ page = self.client.post('/edit/',
+ {"bio": "Noooooooooooooo",
+ "surname": "Sobol",
+ "name": "Andrey",
+ "other": "pigeon post - white pigeon only"})
self.assertEqual(page.status_code, 200)
self.assertTrue(page.content.find("error") != -1)
@@ -71,14 +87,13 @@ def test(self):
class AjaxEdit(TestCase):
def test(self):
- fixtures = ['initial_data.json']
-
- page = self.client.post('/accounts/login/', {'username': 'admin', 'password': 'admin'})
+ page = self.client.post('/accounts/login/',
+ {'username': 'admin', 'password': 'admin'})
self.assertEqual(page.status_code, 302)
page = self.client.post('/edit/')
self.assertTrue(page.content.find('<body>') == -1)
-
+
page = self.client.get('/edit/')
self.assertTrue(page.content.find('<body>') != -1)
self.assertTrue(page.content.find('<script') != -1)
@@ -90,70 +105,98 @@ def test(self):
class EditReverse(TestCase):
def test(self):
- fixtures = ['initial_data.json']
-
page = self.client.get('/')
- self.assertTrue(page.content.find('>Name:') < page.content.find('Last name:'))
- self.assertTrue(page.content.find('Bio:') > page.content.find('Other'))
+ self.assertTrue(page.content.find('>Name:')
+ < page.content.find('Last name:'))
+ self.assertTrue(page.content.find('Bio:')
+ > page.content.find('Other'))
- page = self.client.post('/accounts/login/', {'username': 'admin', 'password': 'admin'})
+ page = self.client.post('/accounts/login/',
+ {'username': 'admin', 'password': 'admin'})
page = self.client.get('/edit/')
- self.assertTrue(page.content.find('>Name:') > page.content.find('Last name:'))
- self.assertTrue(page.content.find('Bio:') < page.content.find('Other'))
+ self.assertTrue(page.content.find('>Name:')
+ > page.content.find('Last name:'))
+ self.assertTrue(page.content.find('Bio:')
+ < page.content.find('Other'))
class Tag(TestCase):
def test(self):
- fixtures = ['initial_data.json']
+ page = self.client.post('/accounts/login/',
+ {'username': 'admin', 'password': 'admin'})
+
+ page = self.client.get('/')
+ self.assertTrue(page.content.find(
+ '<a href="/admin/auth/user/1/"') != -1)
- page = self.client.post('/accounts/login/', {'username': 'admin', 'password': 'admin'})
+class NameUrlTest(TestCase):
+
+ def test(self):
page = self.client.get('/')
- self.assertTrue(page.content.find('<a href="/admin/auth/user/1/"') != -1 )
+ self.assertEqual(page.status_code, 200)
+ self.assertTrue(page.content.find('a href="/http/"') != -1)
+ self.assertTrue(page.content.find('a href="/edit/"') != -1)
class Command(TestCase):
def test(self):
- p = Popen("python manage.py printmodels", stdout=PIPE, stderr=PIPE, shell=True).stdout.read()
- self.assertTrue(p.find('Bio')!=-1)
+ p = Popen("python manage.py printmodels",
+ stdout=PIPE, stderr=PIPE, shell=True).stdout.read()
+ self.assertTrue(p.find('Bio') != -1)
Popen("bash save.bash", stdout=PIPE, stderr=PIPE, shell=True)
l = os.listdir(".")
for d in l:
- if d.find('.dat')!=-1:
- f = open(d,'r')
+ if d.find('.dat') != -1:
+ f = open(d, 'r')
self.assertTrue((f.read()).find('error') != -1)
f.close()
Popen("rm " + d, stdout=PIPE, stderr=PIPE, shell=True)
class Signal(TestCase):
-
+
def test(self):
- b = Bio(bio="Noooooooooooooo", surname="Sobol", name="Andrey", other="pigeon post - white pigeon only", birth="1990-09-18", skype="andreysobol", jabber="pisecs@gmail.com", email="asobol@mail.ua", img="img/1.jpg")
+ b = Bio(bio="Noooooooooooooo", surname="Sobol",
+ name="Andrey", other="pigeon post - white pigeon only",
+ birth="1990-09-18", skype="andreysobol",
+ jabber="pisecs@gmail.com", email="asobol@mail.ua",
+ img="img/1.jpg")
b.save()
- self.assertEqual(Log.objects.order_by('-id')[0].model,'Bio')
- self.assertEqual(Log.objects.order_by('-id')[0].signal,'create')
-
- b.bio="sfsf"
+ self.assertEqual(Log.objects.order_by('-id')[0].model, 'Bio')
+ self.assertEqual(Log.objects.order_by('-id')[0].signal, 'create')
+
+ b.bio = "sfsf"
b.save()
- self.assertEqual(Log.objects.order_by('-id')[0].model,'Bio')
- self.assertEqual(Log.objects.order_by('-id')[0].signal,'update')
+ self.assertEqual(Log.objects.order_by('-id')[0].model, 'Bio')
+ self.assertEqual(Log.objects.order_by('-id')[0].signal, 'update')
b.delete()
- self.assertEqual(Log.objects.order_by('-id')[0].model,'Bio')
- self.assertEqual(Log.objects.order_by('-id')[0].signal,'delete')
+ self.assertEqual(Log.objects.order_by('-id')[0].model, 'Bio')
+ self.assertEqual(Log.objects.order_by('-id')[0].signal, 'delete')
+
class RequestPriority(TestCase):
def test(self):
- fixtures = ['initial_data.json']
page = self.client.get('/http/')
self.assertEqual(page.status_code, 200)
- b = False;
+ b = False
for r in page.context['custom_request']:
- if r['url']=='/http/' and r['priority']==2:
+ if r['url'] == '/http/' and r['priority'] == 2:
b = True
self.assertTrue(b)
+
+
+class ManyRequestTest(TestCase):
+
+ def test(self):
+ for t in range(11):
+ page = self.client.get('/')
+ self.assertEqual(page.status_code, 200)
+
+ page = self.client.get('/http/')
+ self.assertTrue(len(page.context['custom_request']) == 10)
View
32 testsobol/mainapp/utils.py
@@ -1,15 +1,35 @@
-structs = (
- ('name','surname','birth','img'),
- ('email','jabber','skype','other', 'bio'),
+structs = (
+ ('name', 'surname', 'birth', 'img'),
+ ('email', 'jabber', 'skype', 'other', 'bio'),
)
-multiline = ('bio','other', 'img')
+multiline = ('bio', 'other', 'img')
+
class Render(object):
-
+
def get_struct(self, get, reverse):
if reverse:
local_structs = [struct[::-1] for struct in structs]
else:
local_structs = structs
- return [[dict(get(item).items() + [('multiline',(item in multiline))]) for item in struct] for struct in local_structs]
+ return [[dict(get(item).items() + [('multiline', (item in multiline))])
+ for item in struct]
+ for struct in local_structs]
+
+
+class DataRender(Render):
+
+ def __init__(self, model):
+ self.model = model
+
+ def render(self):
+ field_types = dict([(field.name, field.verbose_name) \
+ for field in self.model._meta.fields])
+
+ get = lambda item: {'value':\
+ unicode(getattr(self.model, item)) if item != 'img'\
+ else '<img src="%s" />' % getattr(self.model, item).url,
+ 'label': field_types[item]}
+
+ return self.get_struct(get, False)
View
54 testsobol/mainapp/views.py
@@ -1,6 +1,6 @@
-from django.views.generic import View, TemplateView, ListView
+from django.views.generic import View, TemplateView
from django.forms.models import model_to_dict
-from django.shortcuts import redirect, render_to_response
+from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
@@ -8,33 +8,37 @@
from models import Bio, Request, RequestPriority
from forms import BioForm
+from utils import DataRender
+
class Index(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
- context = super(Index, self).get_context_data(**kwargs)
- return {'renders':Bio.objects.get(pk = 1).render()}
+ super(Index, self).get_context_data(**kwargs)
+ d = DataRender(Bio.objects.get(pk=1))
+ return {'renders': d.render()}
class Edit(View):
-
- def render(self,request,form,temp):
- return render_to_response(temp,RequestContext(request,{'renders':form.render(), 'form':True}))
+
+ def render(self, request, form, temp):
+ return render_to_response(temp,
+ RequestContext(request, {'renders': form.render(), 'form': True}))
@method_decorator(login_required())
def dispatch(self, request, *args, **kwargs):
return super(Edit, self).dispatch(request, *args, **kwargs)
def get(self, request):
- form = BioForm(model_to_dict(Bio.objects.get(pk = 1)),{'img':Bio.objects.get(pk = 1).img})
- render=form.render()
- return self.render(request,form,'index.html')
+ form = BioForm(model_to_dict(Bio.objects.get(pk=1)),
+ {'img': Bio.objects.get(pk=1).img})
+ return self.render(request, form, 'index.html')
def post(self, request):
if not request.FILES:
- form = BioForm(request.POST, {'img':Bio.objects.get(pk = 1).img})
+ form = BioForm(request.POST, {'img': Bio.objects.get(pk=1).img})
else:
form = BioForm(request.POST, request.FILES)
if form.is_valid():
@@ -43,7 +47,7 @@ def post(self, request):
model.save()
return HttpResponse("Okay")
else:
- return self.render(request,form,'content.html')
+ return self.render(request, form, 'content.html')
class Http(TemplateView):
@@ -53,16 +57,18 @@ class Http(TemplateView):
def get_context_data(self, **kwargs):
def add(filter):
-
- req = Request.objects.exclude(url__in = exlude_list)
+
+ req = Request.objects.exclude(url__in=exlude_list)
if filter:
- req = req.filter(url = p.url)
+ req = req.filter(url=p.url)
+
+ req = req.order_by('date')
+
+ return [dict(model_to_dict(r).items() +
+ ([('priority', p.priority)] if filter else [('priority', 0)]))
+ for r in req]
- req = req.order_by('-date')
-
- return [dict(model_to_dict(r).items() + ([('priority', p.priority)] if filter else [('priority', 0)])) for r in req]
-
paginate_by = 10
exlude_list = []
@@ -71,12 +77,16 @@ def add(filter):
for p in RequestPriority.objects.order_by('-priority'):
result += add(True)
-
+
if len(result) > paginate_by:
- return {'custom_request':result[0:paginate_by]}
+ return {'custom_request': result[0:paginate_by]}
else:
exlude_list.append(p.url)
result += add(False)
- return {'custom_request':(result if len(result) < paginate_by else result[0:paginate_by])}
+ return {'custom_request': (result if len(result) < paginate_by
+ else result[0:paginate_by])}
+
+ def get_queryset(self):
+ return Request.objects.order_by('date')
View
12 testsobol/settings.py
@@ -13,12 +13,12 @@
DATABASES = {
'default': {
- 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
- 'NAME': 'db.sqlite3', # Or path to database file if using sqlite3.
- 'USER': '', # 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.
+ 'ENGINE': 'django.db.backends.sqlite3',
+ 'NAME': 'db.sqlite3',
+ 'USER': '',
+ 'PASSWORD': '',
+ 'HOST': '',
+ 'PORT': '',
}
}
View
4 testsobol/static/custom.js
@@ -20,6 +20,8 @@ $(function(){
url:'/edit/',
type: 'post',
success: function(response){
+ $('input').removeAttr('readonly');
+ $('textarea').removeAttr('readonly');
if(response=="Okay"){
$('.mess').html('Bio update. <a href="/">View.</a>');
$('.error').css('display','none');
@@ -33,6 +35,8 @@ $(function(){
},
beforeSubmit: function(){
$('input[type="submit"]').css('display','none');
+ $('input').attr('readonly','readonly');
+ $('textarea').attr('readonly','readonly');
$('.mess').html('<img src="/static/ajax-loader.gif" style="width:32px;"/>');
}
}
View
6 testsobol/templates/index.html
@@ -36,11 +36,11 @@
{% else %}
<div class="but">
{% if user.is_authenticated %}
- <a href="/edit/">edit</a>
+ <a href="{% url edit %}">edit</a>
{% else %}
- <a href="/edit/">login and edit</a>
+ <a href="{% url edit %}">login and edit</a>
{% endif %}
- <a href="/http/">request</a>
+ <a href="{% url http %}">request</a>
</div>
{% endif %}
{% endblock %}
View
10 testsobol/urls.py
@@ -9,10 +9,12 @@
urlpatterns = patterns('',
# Examples:
url(r'^$', Index.as_view()),
- url(r'^edit/$', Edit.as_view()),
- url(r'^http/$', Http.as_view()),
- (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
- (r'^accounts/login/$', 'django.contrib.auth.views.login', { "template_name": "admin/login.html" } ),
+ url(r'^edit/$', Edit.as_view(), name="edit"),
+ url(r'^http/$', Http.as_view(), name="http"),
+ (r'^media/(?P<path>.*)$', 'django.views.static.serve',
+ {'document_root': settings.MEDIA_ROOT}),
+ (r'^accounts/login/$', 'django.contrib.auth.views.login',
+ {"template_name": "admin/login.html"}),
# url(r'^testsobol/', include('testsobol.foo.urls')),

No commit comments for this range

Something went wrong with that request. Please try again.