模型ImageField并保存在特定路径中

问题描述 投票:0回答:3

这是我的模特:

def group_based_upload_to(instance, filename):
    return "media/image/lavorazione/{}".format(instance.prestazione.id,)

class ImmaginiLavorazioni(models.Model):
    immagine = models.ImageField(upload_to=group_based_upload_to)
    prestazione = models.ForeignKey(Listino, on_delete=models.SET_NULL, null=True,
                                    blank=True, default=None, related_name='Listino3')

和我的形式:

class ImmagineUploadForm(forms.ModelForm):
  class Meta:
    model = ImmaginiLavorazioni
    exclude = ('preventivo', )

我需要一个视图来保存特定路径中的图像。 路径名必须是外键的pk。

我怎样才能做到这一点?

django django-models
3个回答
0
投票

我使用博客文章如何工作的模型。您可以根据需要调整示例。您应该尝试避免从视图中保存位置路径。

在你的models.py上:

# Create your models here.
def upload_location(instance, filename):
    filebase, extension = filename.split(".")
    return "%s/%s" % (instance.id, filename)

class Post(models.Model):
    title = models.CharField(max_length=120)
    slug  = models.SlugField(unique=True)
    image = models.ImageField(upload_to=upload_location,
            null=True,
            blank=True,
            height_field="height_field",
            width_field="width_field")
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    content = HTMLField()
    formfield_overrides = {
        models.TextField: {'widget': AdminPagedownWidget },
    }
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

在您的forms.py上:

from django import forms
from pagedown.widgets import PagedownWidget
from pagedown.widgets import AdminPagedownWidget
from .models import Post


class PostForm(forms.ModelForm):
    content = forms.CharField(widget=PagedownWidget(show_preview=False))
    class Meta:
        model = Post
        fields = [
            "title",
            "content",
            "image"
        ]

class PostModelForm(forms.ModelForm):
    content = forms.CharField(widget=AdminPagedownWidget())

    class Meta:
        model = Post
        fields = '__all__'

在您的settings.py上:

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn")

这是你的view.py:

# Create your views here.
def post_create(request):
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404
    form = PostForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        messages.success(request, "Succefully Created")
        return HttpResponseRedirect(instance.get_absolute_url())

    context = {
        "form": form,
    }
    return render(request, "post_form.html", context)

0
投票

下一个代码有一个没有表单的示例,但您可以根据需要进行修改。

settings.py下面

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, '../media')

Firstable,我在helpers.py中定义了图像的路径

from django.conf import settings
from datetime import datetime

def upload_to_image_post(self, filename):
    """
    Stores the image in a specific path regards to date 
    and changes the name of the image with for the name of the post
    """    
    current_date = datetime.now()

    return '%s/posts/main/{year}/{month}/{day}/%s'.format(
        year=current_date.strftime('%Y'), month=current_date.strftime('%m'), 
        day=current_date.strftime('%d')) % (settings.MEDIA_ROOT, filename)

您可以使用类似这样的代码定义图像的名称。但你必须考虑到你应该用pk来替换图像的名称

ext = filename.split('.')[-1]
name = self.pk
filename = '%s.%s' % (name, ext)

所以,我在我的models.py中调用def,特别是在图像的字段中

from django.db import models
from django.utils.text import slugify
from .helpers import upload_to_image_post

class Post(models.Model):
    """
    Store a simple Post entry. 
    """
    title = models.CharField('Title', max_length=200, help_text='Title of the post')
    body = models.TextField('Body', help_text='Enter the description of the post')   
    slug = models.SlugField('Slug', max_length=200, db_index=True, unique=True, help_text='Title in format of URL')        
    image_post = models.ImageField('Image', max_length=80, blank=True, upload_to=upload_to_image_post, help_text='Main image of the post')

    class Meta:
        verbose_name = 'Post'
        verbose_name_plural = 'Posts'

我希望这对你有所帮助


0
投票

现在这是我的模特:

def group_based_upload_to(instance,image):返回“media / quote / {pk} / {image}”。format(pk = instance.preventivo.id,image = image)

class ImmaginiLavorazioni(models.Model):immagine = models.ImageField(upload_to = group_based_upload_to)preventivo = models.ForeignKey(Preventivo,on_delete = models.SET_NULL,null = True,blank = True,default = None,related_name ='Listino3')

这是我的观点:

def upload_immagine(request,pk):

member = get_object_or_404(Preventivo, pk=pk)
if request.method == 'POST':
    form = ImmagineUploadForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        newimmagine = form.save(commit=False)
        newimmagine.preventivo_id = member.pk
        newimmagine.save()

        return redirect('preventivo_new2', pk=member.pk)

else:
    form = ImmagineUploadForm(request.POST or None, request.FILES or None)
return render(request, 'FBIsystem/upload_immagine.html', {'member': member, 'form': form})

它在db中保存文件路径和外键如:

image = average / quote / 6 / image.jpg quote_id = 6

但不能创建文件夹而不保存上传的图像...

© www.soinside.com 2019 - 2024. All rights reserved.