尝试设置上传位置时,Django instance.id始终='无'

时间:2017-02-10 11:53:59

标签: python django django-models python-3.6

我一直试图让我的帖子表单允许用户上传图片,然后将其保存在相对于帖子ID的文件夹中。但是帖子ID总是==无。

我的models.py:

from django.db import models
from django.core.urlresolvers import reverse
# Create your models here.

def upload_location(instance, filename):
    return "{}/{}".format(form.id, filename)

class Post(models.Model):
    post_title = models.CharField(max_length = 120)
    post_content = models.TextField()
    last_updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    post_date = models.DateTimeField(auto_now=False, auto_now_add=True)
    post_image = models.FileField(upload_to=upload_location, null=True, blank=True)

    def __unicode__(self):
        return self.post_title

    def __str__(self):
        return self.post_title

    def get_absolute_url(self):
        return reverse("posts:post_display", kwargs= {'post_id': self.id})

我的views.py:

from django.shortcuts import render, get_object_or_404, redirect
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# Create your views here.
from .forms import PostForm
from .models import Post

#create
def post_create(request):
    if not request.user.is_authenticated:
        return(redirect("posts:post_timeline"))

    form = PostForm(request.POST or None, request.FILES or None)
    if form.is_valid() and request.POST:
        instance = form.save(commit=False)
        instance.save()
        return(HttpResponseRedirect(instance.get_absolute_url()))


    context = {
        "form": form,
    }

    return render(request, "post_form.html", context)


def post_edit(request, post_id = None):

    instance = get_object_or_404(Post, id = post_id)

    form = PostForm(request.POST or None, request.FILES or None, instance = instance)
    if form.is_valid and request.POST and request.user.is_authenticated:
        instance = form.save(commit=False)
        instance.save()
        #messages.success(request, "Post successfully Edited")
        return(HttpResponseRedirect(instance.get_absolute_url()))
    context = {
        "title": instance.post_title,
        "instance": instance,
        "form": form,
    }

    return render(request, "post_edit.html", context)

如果您需要任何其他代码,请与我们联系,

感谢您提供任何帮助!

1 个答案:

答案 0 :(得分:0)

我敢肯定,只有在保存表单时才分配ID,以便您可以在保存后上传文件。

但是这样做可能会很烦人,我建议您这样做

def upload_location(instance, filename):
    return os.path.join('postFiles', str(instance.post_title), filename)

它将创建一个名为postFiles的文件,以更好地组织

您可以使用instance.post_title代替form.id,因为django会自动重命名文件,并且在尝试访问文件名时文件名实际上并没有关系。要访问它们,只需通过

Post.objects.get(pk= the id of the post you're trying to access)

在您的视图中(称其为Post或其他名称) 并在您的模板中完成

{{ Post.post_image.url }}