Django上传多个图像

时间:2017-04-13 18:13:40

标签: django file-upload

我一直想把它做两天。我创建了一个能够上传一个图像文件的网站,但我希望能够上传更多连接到同一主模型的网站。 这是我上传一张图片的原因: forms.py: 来自django进口表格

from .models import Exam

class ExamForm(forms.ModelForm):
    class Meta:
        model = Exam
        fields = ['exam_number', 'exam_file']
        widgets = {
        'exam_number': forms.NumberInput(
            attrs={'id': 'exam_number', 'required': True,})
        }

Models.py:

from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from datetime import datetime
from django.core.validators import MaxValueValidator, MinValueValidator

class Exam(models.Model):
    exam_number = models.PositiveIntegerField(validators=[MaxValueValidator(6),MinValueValidator(1)])
    exam_path = models.CharField(max_length=255)
    exam_file = models.ImageField() #i want to be able to upload more of these
    exam_date = models.DateTimeField(auto_now_add=True)
    exam_user = models.ForeignKey(User, null=True)

    def __str__(self):
        return self.exam_path

    def __int__(self):
        return self.exam_number

views.py:

def create_exam(request, letnik_id, classes_id, subject_id):
    response_data = {}
    if subject_id in SUBJECTS:
        path = letnik_id + '/' + classes_id + '/' + subject_id
        form = ExamForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            exam = form.save(commit=False)
            exam.exam_user = request.user
            exam.exam_path = path
            exam.exam_file = request.FILES['exam_file']
            file_type = exam.exam_file.url.split('.')[-1]
            file_type = file_type.lower()
            if file_type not in IMAGE_FILE_TYPES:
                context = {
                'error_message': 'error',
                }
                return Http404("Napaka")
            if Exam.objects.filter(exam_path=path, exam_number=exam.exam_number):
                context = {
                'form': form,
                'error_message': 'error',
                }
                return render(request, 'tests.html', context)
            exam.save()
            return redirect('subject_id', letnik_id=letnik_id, classes_id=classes_id, subject_id=subject_id)
        context = {
        "form": form
        }
        raise Http404("error")
    raise Http404("error")

我听说最好为文件制作单独的模型,但我不知道如何制作连接到父(考试)模型的视图。 感谢帮助!

1 个答案:

答案 0 :(得分:0)

您需要创建一个看起来像这样的单独模型

class ExamFile(models.Model):
      file = models.ImageField()
      exam = models.ForeignKey(Exam, null=False)

然后在您的视图中,您将使用它来创建此新模型,而不是将exam_file添加到考试中。这看起来像这样

from .models import Exam, ExamFile
...
exam_file = ExamFile.objects.create(
                    file = request.FILES['exam_file'],
                    exam=exam
            )

有关修复表单的详细信息,请查看找到的文档here