file upload and edit in django
===================== Example 1 (default)
--------------- in models.py
class Mockup(models.Model):
def get_path(self, image_name):
upload_path = ('%s/%s/mockups/%s/%s') %(settings.UPLOAD_PATH, self.mockupset.project.id, self.mockupset.mockupset_number, image_name)
return upload_path
mockupset = models.ForeignKey(MockupSet)
caption = models.CharField(max_length=200, blank=True)
image = models.ImageField(upload_to=get_path, null=False, blank=False)
created_on = models.DateTimeField()
created_by = models.ForeignKey(ProjectMember, related_name='mockup_created_by')
------------- in forms.py
class MockupForm(ModelForm):
class Meta:
model = Mockup
exclude = ('mockupset', 'created_by', 'created_on')
def __init__(self, current_user, mockupset, *args, **kwargs):
super(MockupForm, self).__init__(*args, **kwargs)
self._current_user = current_user
self._mockupset_id = mockupset
def save(self, commit=True):
m = super(MockupForm, self).save(commit=False)
m.mockupset = self._mockupset_id
m.created_by = self._current_user
m.created_on = datetime.datetime.now()
if commit:
m.save()
return m
------------- in template
{% block content %}
<div class="title-block">
<h1>Add New Image</h1>
<div class="header_links">
<a href="{% url mockupset_detail project.id mockupset.mockupset_number %}">Back</a>
</div>
</div>
<div class="form-wrapper">
{% if form.errors %}
<p class="error">
Please correct the error below.
</p>
{% endif %}
<form enctype="multipart/form-data" action="{% if mockup %} {% url mockup_edit project.id mockupset.mockupset_number mockup.id %} {% else %} {% url mockup_add project.id mockupset.mockupset_number %} {% endif %}" method="post">
<div class="row">
{{form.caption.label_tag }}
{{ form.caption }}
{{ form.caption.errors}}
</div>
<div class="row">
{{ form.image.label_tag }}
{{ form.image }}
{{ form.image.errors}}
</div>
<div class="row">
<label> </label>
{% if mockup %}
<button type="submit">Save Chanages</button>
{% else %}
<button type="submit">Create Mockup</button>
{% endif %}
</div>
</form>
</div>
{% endblock %}
-------------in views.py (Add, Edit)
def mockup_add(request, project_id, mockupset_number):
project = get_object_or_404(Project, pk=project_id)
mockupset = get_object_or_404(MockupSet, project=project, mockupset_number=mockupset_number)
projectmember = get_object_or_404(ProjectMember, user=request.user, project=project)
if request.method == 'POST':
form = MockupForm(projectmember, mockupset, request.POST, request.FILES)
if form.is_valid():
m = form.save()
return HttpResponseRedirect(reverse('mockupset_list', kwargs={'project_id':project.id}))
elif request.method == 'GET':
form = MockupForm(projectmember, mockupset)
return render_to_response('siren/mockup/mockup_add.html', {
'form':form,
'project':project,
'mockupset':mockupset
}, context_instance=RequestContext(request))
def mockup_edit(request, project_id, mockupset_number, mockup_id):
project = get_object_or_404(Project, pk=project_id)
mockup = get_object_or_404(Mockup, pk=mockup_id)
mockupset = get_object_or_404(MockupSet, project=project, mockupset_number=mockupset_number)
projectmember = get_object_or_404(ProjectMember, user=request.user, project=project)
if request.method == 'POST':
form = MockupForm(projectmember, mockupset, request.POST, request.FILES, instance=mockup)
if form.is_valid():
m = form.save()
return HttpResponseRedirect(reverse('mockupset_list', kwargs={'project_id':project.id}))
elif request.method == 'GET':
form = MockupForm(projectmember, mockupset, instance=mockup)
return render_to_response('siren/mockup/mockup_add.html', {
'form':form,
'mockup': mockup,
'mockupset':mockupset,
'project':project
}, context_instance=RequestContext(request))
========================== Example 2 (upload to image field in the another model)
--------------- in models.py
class MockupSet(fts.SearchableModel):
project = models.ForeignKey(Project)
mockupset_number = models.IntegerField(default=0)
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
created_on = models.DateTimeField()
created_by = models.ForeignKey(ProjectMember, related_name='mockupset_created_by')
class Mockup(models.Model):
def get_path(self, image_name):
upload_path = ('%s/%s/mockups/%s/%s') %(settings.UPLOAD_PATH, self.mockupset.project.id, self.mockupset.mockupset_number, image_name)
return upload_path
mockupset = models.ForeignKey(MockupSet)
caption = models.CharField(max_length=200, blank=True)
image = models.ImageField(upload_to=get_path, null=False, blank=False)
created_on = models.DateTimeField()
created_by = models.ForeignKey(ProjectMember, related_name='mockup_created_by')
-------------- in forms.py
class MockupSetForm(ModelForm):
image_one = forms.ImageField(required=False)
image_two = forms.ImageField(required=False)
image_three = forms.ImageField(required=False)
class Meta:
model = MockupSet
exclude = ('project', 'mockupset_number', 'created_by', 'created_on')
def __init__(self, current_user, project, *args, **kwargs):
super(MockupSetForm, self).__init__(*args, **kwargs)
self._current_user = current_user
self._project_id = project
def save(self, commit=True):
ms = super(MockupSetForm, self).save(commit=False)
ms.project = self._project_id
ms.created_by = self._current_user
ms.created_on = datetime.datetime.now()
if commit:
ms.save()
print "oo"
if self.cleaned_data['image_one']:
img = self.cleaned_data['image_one']
ms.mockup_set.create(caption=str(img), image=img, created_on=datetime.datetime.today(), created_by=self._current_user)
if self.cleaned_data['image_two']:
img = self.cleaned_data['image_two']
ms.mockup_set.create(caption=str(img), image=img, created_on=datetime.datetime.today(), created_by=self._current_user)
if self.cleaned_data['image_three']:
img = self.cleaned_data['image_three']
ms.mockup_set.create(caption=str(img), image=img, created_on=datetime.datetime.today(), created_by=self._current_user)
return ms
--------------- in template
{% block content %}
<div class="title-block">
<h1>Add New Mockupset</h1>
<div class="header_links">
<a href="{% url mockupset_list project.id %}">List Mockupset</a>
</div>
</div>
<div class="form-wrapper">
{% if form.errors %}
<p class="error">
Please correct the error below.
</p>
{% endif %}
<form enctype="multipart/form-data" action="{% if mockupset %} {% url mockupset_edit project.id mockupset.mockupset_number %} {% else %} {% url mockupset_add project.id %} {% endif %}" method="post">
<div class="row">
{{form.title.label_tag }}
{{ form.title }}
{{ form.title.errors}}
</div>
<div class="row">
{{ form.description.label_tag }}
{{ form.description }}
{{ form.description.errors}}
</div>
<div class="row">
{{ form.image_one.label_tag }}
{{ form.image_one }}
{{ form.image_one.errors}}
</div>
<div class="row">
{{ form.image_two.label_tag }}
{{ form.image_two }}
{{ form.image_two.errors}}
</div>
<div class="row">
{{ form.image_three.label_tag }}
{{ form.image_three }}
{{ form.image_three.errors}}
</div>
<div class="row">
<label> </label>
{% if mockupset %}
<button type="submit">Save Chanages</button>
{% else %}
<button type="submit">Create Mockupset</button>
{% endif %}
</div>
</form>
</div>
{% endblock %}
--------------- in views.py (Add)
# For Add
def mockupset_add(request, project_id):
project = get_object_or_404(Project, pk=project_id)
projectmember = get_object_or_404(ProjectMember, user=request.user, project=project)
if request.method == 'POST':
form = MockupSetForm(projectmember, project, request.POST, request.FILES)
if form.is_valid():
ms = form.save()
return HttpResponseRedirect(reverse('mockupset_list', kwargs={'project_id':project.id}))
elif request.method == 'GET':
form = MockupSetForm(projectmember, project)
return render_to_response('siren/mockupset/mockupset_add.html', {
'form':form,
'project':project
}, context_instance=RequestContext(request))
========================== Example 3
No comments:
Post a Comment