Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge branch 't8_tag' into t9_command

Conflicts:
	testsobol/mainapp/tests.py
  • Loading branch information...
commit b9a2ef69b964c00280e3f3198ba7df3d8eb8e3ad 2 parents 49921e4 + be9dde8
@andreysobol authored
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
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
9 testsobol/mainapp/models.py
@@ -1,8 +1,7 @@
from django.db import models
-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')
@@ -13,12 +12,6 @@ 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()
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
98 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,28 +105,40 @@ 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.post('/accounts/login/', {'username': 'admin', 'password': 'admin'})
+ page = self.client.get('/')
+ self.assertTrue(page.content.find(
+ '<a href="/admin/auth/user/1/"') != -1)
+
+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):
@@ -127,3 +154,14 @@ def test(self):
self.assertTrue((f.read()).find('error') != -1)
f.close()
Popen("rm " + d, stdout=PIPE, stderr=PIPE, shell=True)
+
+
+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(page.context['custom_request'].count() == 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
28 testsobol/mainapp/views.py
@@ -1,6 +1,6 @@
from django.views.generic import View, TemplateView, ListView
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
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(ListView):
@@ -53,4 +57,4 @@ class Http(ListView):
paginate_by = 10
def get_queryset(self):
- return Request.objects.order_by('-date')
+ 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')),
Please sign in to comment.
Something went wrong with that request. Please try again.