Django ImageField не проверяет изображение - PullRequest
0 голосов
/ 12 июля 2020

Я могу загрузить код, но это очень простая форма c, которая имеет ImageField и Model with ImageField, однако я могу загрузить любой тип файла. Я установил PIL и успешно записываю загруженные файлы в каталог мультимедиа, но, как я уже сказал, они могут быть такими, какие мне нравятся, поскольку проверки не происходит.

Добавлено обновление, извините, я этого не сделал ' Сделайте это раньше.

Просмотры.

from django.shortcuts import render
from .forms import QuoteForm, ImageForm
from django.http import HttpResponse
from django.core.mail import EmailMessage
from django.shortcuts import redirect
from django.template.loader import get_template
from .models import Quote, Image, Job
from django.forms import modelformset_factory
from django.contrib import messages
from django.http import HttpResponseRedirect


def job_index(request):
    jobs = Job.objects.all()
    context = {
        'jobs':jobs
    }
    return render (request, 'about.html', context)

def quote(request):

    if request.method == 'POST':
        form = QuoteForm(request.POST)
        files = request.FILES.getlist('image')

        if form.is_valid():
            quote_form = form.save(commit=False)
            quote_form.save()
            messages.success(request, 'Form submission successful')
            HttpResponse('image upload success')
            form=QuoteForm()

            for f in files:
                Image.objects.create(quote=quote_form, image = f)



        else:
            print("Oh Know")

    else:
        form = QuoteForm()

    context ={
        'form': form,


    }
    
    return render (request, 'quote.html', context)

Форма


from django import forms
from .models import Quote, Image
from django.core.exceptions import ValidationError
from django.core import validators
from django.utils.translation import gettext_lazy as _
import csv
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, ButtonHolder, Submit



SERVICES = [
    ('lawn', 'Lawn Mowing'),
    ('hedge', 'Hedge Triming'),
    
]


# def check_size(value):
#     if len(value)<6:
#         raise ValidationError("You fucked it")


class QuoteForm(forms.ModelForm):
    title = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Post Code to check if we service your area"}))
    message = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Title"}))
    date_call = forms.CharField(widget=forms.TextInput(attrs={"id":"datetimes"}))
    service = forms.ChoiceField(choices=SERVICES)
    class Meta:
        model = Quote
        fields = ('title', 'message', 'email', 'date_call', 'service')


    def clean_title(self):
        with open("/Users/Mitch/Desktop/Work/Website/db_landscaping/db_landscaping/static/postcodes.csv", mode = "r") as csvDataFile:
            csvReader = csv.reader(csvDataFile)
            title = self.cleaned_data.get("title")
            for row in csvReader:
                if title not in row:
                    raise ValidationError('Postcode invalid or we do not service your area') 
            return title






class ImageForm(forms.ModelForm):
    image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
    class Meta (QuoteForm.Meta):
        fields = QuoteForm.Meta.fields + ('image',)

Модели


from django.db import models
from django.db.models.signals import pre_save
from db_landscaping import settings
import os
from django.template.defaultfilters import slugify





class Quote (models.Model):
    title = models.CharField(null=True, max_length=100)
    message = models.TextField(null=True,blank=True)
    email = models.EmailField( null=True)
    slug = models.SlugField(null=True ,unique=True )
    service = models.CharField(max_length=100, null=True)
    date_call = models.TextField(null=True)
    created_date = models.DateTimeField(null=True, auto_now_add=True)
    last_modified = models.DateTimeField(null=True, auto_now=True)

class Job (models.Model):
    title = models.CharField(null=True, max_length=100)
    message = models.TextField(null=True,blank=True)
    image = models.ImageField(upload_to="images/job",null=True,blank=True)




class Image (models.Model):
    quote = models.ForeignKey(Quote, default=None, on_delete=models.CASCADE)
    image = models.ImageField(upload_to="images/",null=True,blank=True)

    def __str__(self):
        return self.quote.title + "Image"
...