首页 \ 问答 \ Django上传多张图片(Django uploading multiple images)

Django上传多张图片(Django uploading multiple images)

我现在一直在试着做这个两天。 我创建的网站能够上传一个图像文件,但我希望能够上传更多的图像文件,这些图像文件都连接到相同的主要模型。 这是我有一个图片上传: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")

我听说最好为文件制作分离的模型,但我不知道如何制作可以连接到父级(考试)模型的视图。 帮助表示赞赏!


Ive been trying to make this for two days now. I have created website that is capable of uploading one image file, but i would like to be able to upload more of them, that are connected to the same main model. This is what i have for one picture upload: forms.py: from django import forms

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")

ive heard that it would be best to make separated model for files, but i dont know how to make views that would connect to parent(exam) model. Help is appreciated!


原文:https://stackoverflow.com/questions/43399099
更新时间:2022-07-15 14:07

最满意答案

int num = 1放在循环的旁边...

int num = 1;
while(sc.hasNext())
{
    System.out.print(num);
    System.out.print(" "); // Separate the line number from the text
    System.out.println(sc.nextLine());
    num++;
}

这样,每次循环重新启动时都不会重置...


Take int num = 1 and place it out side of the loop...

int num = 1;
while(sc.hasNext())
{
    System.out.print(num);
    System.out.print(" "); // Separate the line number from the text
    System.out.println(sc.nextLine());
    num++;
}

This way it won't be reset every time the loop restarts...

相关问答

更多
  • 其他答案解释了您的代码有什么问题。 这是一种更加pythonic的方式来做你想做的事情: with open('seq.txt', mode='r', encoding='utf-8') as infile: with open('seqpar.txt', mode='w', encoding='utf-8') as outfile: for line in infile: outfile.write(line.strip("\n")) # O ...
  • File.AppendText和TextWriter.Write是可能的方法: using(var output = new File.AppendText("highscore.txt")) { output.Write("Moves Taken: {0}", MoveCounter); } File.AppendText and TextWriter.Write is possible approach: using(var output = new File.AppendText("high ...
  • 这一行: while (fscanf(corolla, "%c", &eof) != EOF) 从文件中读取一个字符。 文件中的第一个字符是1因此它将1读入eof 。 你的下一行是: fscanf(corolla, "%lf %lf", &age, &avgprice); 它按顺序读取文件中的下两个条目,即13990和2 。 所以第一个年龄是13990,第一个年龄是2 。 之后,文件指针现在指向2之后的空白区域。 当你去: fscanf(corolla, "%c", &eof) 它将空间读入eof ...
  • 把int num = 1放在循环的旁边... int num = 1; while(sc.hasNext()) { System.out.print(num); System.out.print(" "); // Separate the line number from the text System.out.println(sc.nextLine()); num++; } 这样,每次循环重新启动时都不会重置... Take int num = 1 and place i ...
  • 您的代码存在一些问题。 其中: 您正在使用读取字符的fgetc ,每次只能读取一个字符。 如果您想一次读取一个分数,这将不适用于“50分”的分数。 您直接将“fgetc”的结果用作数字。 这是错误的: fgetc将返回字符代码,而不是数字。 所以如果你有ASCII,当fgetc读取1时,它将返回49。 我建议你尝试使用fscanf("%d", ..)代替。 There a are a few problems with your code. Among them: You are using fgetc w ...
  • 您也可以在包中包含程序源代码的文件夹中找到它。 在这里,因为您尚未提及文件的正确路径,因此它将存储在何处,因此它必须是默认位置的情况。 尽量写出更精确的路径。 在这种情况下,abc.txt文件也可以被ABC.txt文件的内容覆盖,如果存在任何名为abc.txt的文件,那么ypu也应该查看它。 You can also find it in the folder consisting the source code of your program inside that package. Here as yo ...
  • 声明行变量 int n, line = 0; std::string value; 适当的加载数据: getline (myfile,value); PA[line] = atof(value.c_str()); cout << PA[line]<< endl; line++; declare line variable int n, line = 0; std::string value; proper load data: getline (myfile,value); PA[line] = at ...
  • 当你调用rs1.toString()你得到了Object的默认toString()实现,它打印了类名和onstance哈希(在你的例子中是com.mysql.jdbc.JDBC4ResultSet@81c868 )。 您要做的是从ResultSet中提取查询的结果,然后打印它。 使用rs1.getInt(1)获取查询提取的计数。 请参阅此处的参考 编辑(在问题中编辑后): 首先,我将第一个查询更改为: String query = "select count(kelompok),kelompok from ...
  • 在Windows上: 关于打开控制台来完成工作的想法,因为这是平台的东西,似乎是合理的。 但是,如果你有USB打印机,那就太难了。 相反,我建议你安装Powershell(在Windows 7上你默认使用它)。 在Powershell中打印的方法是获取文件的内容并将其拍摄到Out-Printer(别名'lp')cmdlet。 然后你的公开电话是: String psPrint = "C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -Comm ...
  • 我无法解决变量。 while ((line = br.readLine()) != null) { String[] numbers = line.split("\\W+"); for ( int i = 0 ; i < 25 ; i++){ matrix[lineCount][i] = Double.parseDouble(numbers[i].trim()); ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)