How to add image to message in django

I am creating a blog system that allows a user to add an image to their blog.

when a user adds an image, the image is loaded automatically, this happened before the blog was published, so how should I process the downloaded image, this image is like a temporary image, because if the user publishes a blog, these images will have a foreign key for this blog and are stored in some folder, but if the user cancels the blog, these temporary images should be deleted.

the problem is how to get the images uploaded for the first time when the blog is really posted? Where should I store these temporary images? and how can I find out if a user discards a blog?

+4
source share
2 answers

I would suggest the following:

  • Modify the Post model to add a published datetime field that allows NULL.
  • Use the published field to determine if the message is published or not. A message will be considered as a draft if the published field is NULL, otherwise published.
  • Create a message as soon as you click the create message button. This will give you a Post object with an identifier that you can bind to ModelForm and show the user for editing. Therefore, when they add an image, you can upload it and bind it to the message id as you want.
  • datetime.now() .
  • , .

, .

+5

django.contrib.auth ? , User request Ajax. , . . :

views.py:

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.utils import simplejson
from django.contrib.auth.decorators import login_required
from filetransfers.api import prepare_upload, serve_file
from blog.models import BlogEntry
from blog.forms import BlogEntryForm

@login_required
def createBlogEntry(request):
    return render_to_response('blogEdit.html', { 'form' : BlogEntryForm() })

@login_required
def uploadImage(request):
  if request.method == 'POST':
     form = BlogEntryForm(request.POST, request.FILES)
     if form.is_valid():
        newEntry = BlogEntry()
        newEntry = request.FILES['blogImage']
        newEntry.image = request.FILES['file'].name
        newEntry.user = request.user

        # delete unsaved previous blog post
        try:
            oldEntry = BlogEntry.objects.get(user=request.user,completed=False)
            oldEntry.delete()
        except:
            pass

        newEntry.save()
        return HttpResponse(simplejson.dumps({'imageLocation' : '/static/media/blogImgs/%s' % request.FILES['image'].name }), mimetype='application/javascript')
  return HttpResponse(simplejson.dumps({"error" : 101, "message" : "Big error!"}}), mimetype="application/json")

@login_required
def uploadText(request):
if request.method == 'POST':
    if form.is_valid():
        newEntry = BlogEntry()
        try:
            newEntry = BlogEntry.objects.get(user=request.user,completed=False)
        except:
            pass

        newEntry.blogText = request.POST['blogText']
                    newEntry.completed = True
        newEntry.save()
        return HttpResponse(simplejson.dumps({'result' : 'success'});
  return HttpResponse(simplejson.dumps({"error" : 102, "message" : "other Big error!"}}), mimetype="application/json")

, 2 ajax . BlogEntry , , . , .

( - , ), , . django.auth.contrib , - .

:
< > models.py:

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

class blogEntry(models.Model):
    user = models.ForeignKey(User)
    created = models.DateField(auto_now_add = True)
    completed = models.BooleanField(default = False)

    blogText = models.TextField()
    image = models.ImageField(upload_to = 'blogImgs/')

    def delete(self, *args, **kwargs):
        # Delete image file also
        storage, path = self.image.storage, self.image.path
        super(ImageModel, self).delete(*args, **kwargs)
        storage.delete(path)

.

template: blogEdit.html

<html><head><title>New Blog Entry</title></head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.fileupload/8.9.0/js/jquery.fileupload.js"></script>
<style type="text/css">
form { float: left; }
#textForm {
width: 320px;
padding: 8px;
}
#textForm textarea {
width: 320px;
height: 150px;
margin-bottom: 8px;
}
#imageForm {
width: 100px;
padding-top: 8px;
}
#blogImage {
width: 120px;
height: 120px;
}
#imageForm input[type=file] {
margin: 8px 0 8px 0;
}
</style>
</head>
<body>
<form id="textForm">{% csrf_token %}
<textarea id="blogText" name="blogText"></textarea>
<input type="button" value="upload text" id="textUpload"/>
<img id="blogImage" src="/static/imgs/holdingImage.png" />
    <input id="fileupload" type="file" name="blogImage">
</form>
<script>
$(function () {
  $('#fileupload').fileupload({
    url: '/ajax/uploadImage/',
    dataType: 'json',
    done: function (e, data) {
        blogImage.attr('src', data.result.imageLocation)
    }
  });
});

$('#textUpload').click(function() {
    $.ajax({
      url: '/ajax/uploadText/',
      dataType: 'json',
      data: $('#blogText').val(),
      done: function(e, data) {
        if(data.result == 'success') {
            // display message / redraw edit area with complete blog, etc..
        } else if(data.error) {
            // error handing code
        }
      }
    });
 });
</script>
</body>
</html>

jquery-file .

Ajax Django csrf, . . csrf ajax, . . Ajax jquery , .

forms.py

from django import forms

class BlogEntryForm(forms.Form):
  blogImage = forms.FileField()
  blogText = forms.TextField()

urls.py

from django.conf.urls import patterns, include, url
import blog.views

urlpatterns = patterns('',
  url(r'^createEntry/$', 'blog.views.createBlogEntry', name='createBlogEntry'),
  url(r'^ajax/uploadImage/', 'blog.views.uploadImage'),
  url(r'^ajax/uploadText/', 'blog.views.uploadText'),
  ...additional urls for django.contrib.auth
);
+3

All Articles