1

我正在编写一个项目,您可以在其中将照片从磁盘或其他站点添加到网站。在 jquery 中,我写了一个 book marklet,我可以在其中添加来自其他站点的图片。但我在从光盘上传图像时遇到问题。我编写了模型、模型表单、视图和 html 文件。当我在表单中选择一个 img 文件时,一切看起来都很好。我已移至图像列表网页,但没有我要上传的文件。图像文件未保存。我不知道我做错了什么。下面是我的代码:

模型.py

class Image(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
                         related_name='images_created')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200,
                        blank=True)
url = models.URLField(blank=True)
image = models.ImageField(upload_to='images/%Y/%m/%d')
description = models.TextField(blank=True)
created = models.DateField(auto_now_add=True,
                           db_index=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                related_name='images_liked',
                                blank=True)

total_likes = models.PositiveIntegerField(db_index=True, default=0)


def __str__(self):
    return self.title

def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = slugify(self.title)
    super(Image, self).save(*args, **kwargs)

def get_absolute_url(self):
    return reverse('images:detail', args=[self.id, self.slug])

class Meta:
    ordering = ["-image"]

表格.py

class ImageCreateForm(forms.ModelForm):
class Meta:
    model = Image
    fields = ('title', 'url', 'description')
    widgets = {
        'url': forms.HiddenInput,
    }

def clean_url(self):
    url = self.cleaned_data['url']
    valid_extensions = ['jpg', 'jpeg']
    extension = url.rsplit('.', 1)[1].lower()
    if extension not in valid_extensions:
        raise forms.ValidationError('Podany adres URL nie zawiera ' \
                                    'obrazów w obsługiwanym formacie.')
    return url

def save(self, force_insert=False,
               force_update=False,
               commit=True):
    image = super(ImageCreateForm, self).save(commit=False)
    image_url = self.cleaned_data['url']
    image_name = '{}.{}'.format(slugify(image.title),
                                image_url.rsplit('.', 1)[1].lower())

    # Pobranie pliku obrazu z podanego adresu URL.
    response = request.urlopen(image_url)
    image.image.save(image_name,
                     ContentFile(response.read()),
                     save=False)
    if commit:
        image.save()
    return image

从网页上传

class UploadImageForm(forms.ModelForm):
class Meta:
    model = Image
    fields = ('image', 'title', 'description')

def save(self, commit=True):

    image = super(UploadImageForm, self).save(commit)
    image_name = '{}.{}'.format(slugify(image.title),
                                image_url.rsplit('.', 1)[1].lower())

    # Pobranie pliku obrazu z podanego adresu URL.
    response = request.urlopen(image_title)
    image.image.save(image_name,
                     ContentFile(response.read()),
                     save=False)
    if commit:
        image.save()
    return image

从 dics 上传

视图.py

   @login_required
def image_create(request):
    if request.method == 'POST':
        form = ImageCreateForm(data=request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            new_item = form.save(commit=False)
            new_item.user = request.user
            new_item.save()
            create_action(request.user, 'Added Image', new_item)
            messages.success(request, 'Obraz został dodany.')
            return redirect(new_item.get_absolute_url())
    else:

        form = ImageCreateForm(data=request.GET)

    return render(request,
                  'images/image/create.html',
                  {'section': 'images',
                   'form': form})

从网页上传

@login_required
def image_upload(request):
    if request.method == 'POST':
        upload_form = UploadImageForm(request.POST, request.FILES)
        if ulpoad_form.is_valid():
            new_item=upload_form.save(commit=False)
            new_item.image=request.FILES['image']
            new_item.save()
            messages.success(request, 'Obraz został dodany.')
            return redirect('new_item.get_absolute_url()')
    else:
        upload_form=UploadImageForm()
    return render(request, 'images/image/upload_image.html',
                  {'upload_form': upload_form, 'section': 'images' })

从 dics 上传

并上传.html

{% block content %}
    <h1>upload img</h1>
    <form action="." method="post" enctype="multipart/form-data">
        {{ upload_form.as_p }}
        {% csrf_token %}
        <input type="submit" value="Upload!!">
    </form>
{% endblock %}

我将不胜感激

4

0 回答 0