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
最满意答案
把
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...
相关问答
更多-
文件i / o问题(file i/o problem)[2023-10-12]
其他答案解释了您的代码有什么问题。 这是一种更加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 ...
-
C文件I / O,使用TXT文件(C FILE I/O, USING TXT FILE)[2021-11-12]
您的代码存在一些问题。 其中: 您正在使用读取字符的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 ... -
记录错误:文件I / O(Error Logged : File I/O)[2022-02-15]
您也可以在包中包含程序源代码的文件夹中找到它。 在这里,因为您尚未提及文件的正确路径,因此它将存储在何处,因此它必须是默认位置的情况。 尽量写出更精确的路径。 在这种情况下,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 ...
-
结果集打印到txt文件(resultset print to txt file)[2023-05-20]
当你调用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()); ...