Skip to content

Commit

Permalink
Finally built REST architecture. Changed a few names in models so tha…
Browse files Browse the repository at this point in the history
…t models on server and client had same set of fields. RIGHT NOW IMAGES ARE DELETED BY CLICKING ON THEM. IT SHOULD BE CHANGED.
  • Loading branch information
Vladimir-Kozlov committed Mar 8, 2014
1 parent 10f7742 commit 987f191
Show file tree
Hide file tree
Showing 14 changed files with 113 additions and 27 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.DS_Store
*~

bower_components
*.db
Expand Down
5 changes: 4 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@

Django==1.5.1
beautifulsoup4==4.3.2
pillow
pillow
python-mimeparse
python-dateutil
django-tastypie
1 change: 1 addition & 0 deletions textum/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'tastypie',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
Expand Down
39 changes: 39 additions & 0 deletions textum/textedit/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# myapp/api.py
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from tastypie import fields

from textum.textedit.models import TImage


# https://stackoverflow.com/questions/15263964/django-tasypie-image-upload-example-with-jquery


class MultipartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.META.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultipartResource, self).deserialize(request, data, format)


class TImageResource(MultipartResource, ModelResource):

file = fields.FileField(attribute="file", null=True, blank=True)
class Meta:
always_return_data=True
queryset = TImage.objects.all()
authorization = Authorization()

def obj_create(self, bundle, **kwargs):
print "create"
bundle.data["page_num"] = 0
return super(TImageResource, self).obj_create(bundle, **kwargs)

def alter_list_data_to_serialize(self, request, data):
return data["objects"]
1 change: 0 additions & 1 deletion textum/textedit/core/serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,5 @@ def serialize(instance, file_attr='file'):
'url': obj.url,
'name': order_name(obj.name),
'type': mimetypes.guess_type(obj.path)[0] or 'application/rtf',
'thumbnailUrl': obj.url,
'size': obj.size,
}
8 changes: 5 additions & 3 deletions textum/textedit/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ def delete(self, *args, **kwargs):


class TImage(models.Model):
file = models.ImageField(upload_to="TImages")
slug = models.SlugField(max_length=50, blank=True)
file = models.ImageField(blank = True, null=True, upload_to="TImages")
title = models.SlugField(max_length=50, blank=True)
page_num = models.IntegerField()

def __unicode__(self):
return self.file.name
Expand All @@ -38,10 +39,11 @@ def get_absolute_url(self):
return ('upload-new', )

def save(self, *args, **kwargs):
print "save"
self.slug = self.file.name
super(TImage, self).save(*args, **kwargs)

def delete(self, *args, **kwargs):
"""delete -- Remove to leave file."""
self.file.delete(False)
#self.file.delete(False)
super(TImage, self).delete(*args, **kwargs)
8 changes: 5 additions & 3 deletions textum/textedit/static/textedit/js/app/collections/timages.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@
define([
'underscore',
'backbone',
'backboneLocalstorage',
//'backboneLocalstorage',
'models/timage'
], function (_, Backbone, Store, TImage) {
], function (_, Backbone, TImage) {
'use strict';

var TodosCollection = Backbone.Collection.extend({
// Reference to this collection's model.
model: TImage,

url: '/api/images/timage/',

// Save all of the todo items under the `"todos"` namespace.
localStorage: new Store('timages-backbone'),
//localStorage: new Store('timages-backbone'),

// TImage are sorted by their original insertion order.
comparator: function (timage) {
Expand Down
4 changes: 2 additions & 2 deletions textum/textedit/static/textedit/js/app/models/timage.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ define([
var TImage = Backbone.Model.extend({
defaults: {
title: '',
url: '',
page_num: ''
file: '',
page_num: '',
}
});

Expand Down
28 changes: 18 additions & 10 deletions textum/textedit/static/textedit/js/app/views/gallery.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@ define(['backbone',
this.imageCollection = new TImages();
this.viewsArray = [];
this.listenTo(Backbone, 'uploadImage', function (data) {
this.updateGallery(data);
this.addToGallery(data);
});
},

addTImage: function() {
console.log("New TImage!");
if (this.popup == undefined) {
Expand All @@ -37,24 +38,31 @@ define(['backbone',
this.popup.show('UploadImg');
}
},
updateGallery: function(data) {

addToGallery: function(data) {
console.log(data);
/*this.imageCollection.create({
id: data.id,
img_url: data.files[0].url
});*/
this.imageCollection.create({
//title: data.name,
url: data.url
id: data.id,
file: data.file,
page_num: data.page_num,
});
var just_added = this.imageCollection.last();
console.log(just_added);
this.viewsArray[this.viewsArray.length] = new TImageView({
model: just_added,
id: 'image' + just_added.attributes.id
});
this.viewsArray[this.viewsArray.length - 1]
.$el.appendTo('.photoGrid');
just_added.set('title', data.name); // I do it after view is inserted on the page so that "change" event would happen
/*$('<li><span>' + just_added.attributes.page_num +
'</span><img src="' + just_added.attributes.url +
'" alt="' + just_added.attributes.name +'" /></li>')
.appendTo('.photoGrid');*/
}
just_added.set('title', data.title); // I do it after view is inserted on page so that "change" event would happen
//this.viewsArray[this.viewsArray.length - 1]
//.listenTo(this.viewsArray[this.viewsArray.length - 1].$el, 'click', function(data){console.log('click');});
},

});

return Gallery;
Expand Down
11 changes: 9 additions & 2 deletions textum/textedit/static/textedit/js/app/views/imgview.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,23 @@ define(['backbone',
], function(Backbone, TImage) {
var TImageView = Backbone.View.extend({
tagName: 'li',
className: 'image',
template: _.template('<span><%= page_num %></span>\
<img src="<%= url %>" alt="<%= name %>" />'),
<img src="<%= file %>" alt="<%= title %>" />'),
events: {
'click': 'deleteImg',
},
initialize: function() {
this.listenTo(this.model, "change", this.render);
},
render: function () {
console.log(this.model.attributes);
this.$el.html(this.template(this.model.attributes));
return this;
},
deleteImg: function () {
this.model.destroy();
this.remove();
},
});

return TImageView;
Expand Down
17 changes: 14 additions & 3 deletions textum/textedit/static/textedit/js/app/views/popup-img.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ define(['backbone',
var self = this;
var index = 0;
$('#uploadImg').fileupload({
url: '/api/images/timage/',
dataType: 'json',
context: $('#uploadImg'),

Expand Down Expand Up @@ -110,14 +111,15 @@ define(['backbone',
$('#cancelbutton' + data.files[0].uploadID).click(function (e) {
jqXHR.abort();
});
jqXHR.success(function(result, textStatus, jqXHR) {
/*jqXHR.success(function(result, textStatus, jqXHR) {
Backbone.trigger('uploadImage', result.files[0]);
//console.log(result.files[0]);
console.log(result.files[0]);
console.log(result.id);
$('<p>Загрузка завершена.</p>').replaceAll('#cancelbutton' + data.files[0].uploadID);
setTimeout(function() {
$('#progressbarext' + data.files[0].uploadID).remove();
}, 1000);
});
});*/
});
},

Expand All @@ -127,6 +129,15 @@ define(['backbone',
},

done: function(e, data) {
var result = data.result;
var textStatus = data.textStatus;
var jqXHR = data.jqXHR;
console.log(data);
Backbone.trigger('uploadImage', result);
$('<p>Загрузка завершена.</p>').replaceAll('#cancelbutton' + data.files[0].uploadID);
setTimeout(function() {
$('#progressbarext' + data.files[0].uploadID).remove();
}, 1000);
console.log("File uploaded.");
}
});
Expand Down
8 changes: 8 additions & 0 deletions textum/textedit/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@

from textum.textedit import views

from tastypie.api import Api
from textum.textedit.api import TImageResource

images_api = Api(api_name='images') # Create new api version urlconf
images_api.register(TImageResource())


urlpatterns = patterns('',

Expand All @@ -14,4 +20,6 @@

# ToDo: For tmp purposes. Change url names for more readability
url(r'^upload_image$', views.TImageCreateView.as_view(), name='upload_image'),
#url(r'^api/', include(images_api.urls)),
#url(r'^images/(?P<id>\d+)/$', 'textum.textedit.views.manage'),
)
2 changes: 1 addition & 1 deletion textum/textedit/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class TImageCreateView(CreateView):
def form_valid(self, form):
self.object = form.save()
files = [serialize(self.object)]
data = {'files': files}
data = {'files': files, 'id': self.object.id}
response = JSONResponse(data, mimetype=response_mimetype(self.request))
response['Content-Disposition'] = 'inline; filename=files.json'
return response
Expand Down
7 changes: 6 additions & 1 deletion textum/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
from django.conf.urls.static import static
from django.conf.urls import patterns, url, include

from tastypie.api import Api
from textum.textedit.api import TImageResource

images_api = Api(api_name='images') # Create new api version urlconf
images_api.register(TImageResource())

urlpatterns = patterns('',

Expand All @@ -15,7 +20,7 @@

# textedit(Text Editor) app urls:
url(r'^textedit/', include('textum.textedit.urls', namespace="textedit")),

url(r'^api/', include(images_api.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


Expand Down

0 comments on commit 987f191

Please sign in to comment.