我一直在尝试实现一种上传多个图像的方法,但是我一直遇到管理表单错误。我上传多张图片的方式是让图片拥有自己的表格。然后只需对页面中的每个帖子使用外键。每当我转到创建帖子页面时,就会发生问题
这些是我的代码。
Models.py
// A Divide and Conquer based Java solution
// To find a subarray with the maximum sum
import java.util.Arrays;
import java.util.Scanner;
class MaxSubArray {
private static Result maxCrossingSum(int arr[], int l, int m, int h) {
int sum = 0;
int maxLeft = 0;
int leftSum = Integer.MIN_VALUE;
for (int i = m; i >= l; i--) {
sum = sum + arr[i];
if (sum > leftSum) {
leftSum = sum;
maxLeft = i;
}
}
sum = 0;
int rightSum = Integer.MIN_VALUE;
int maxRight = arr.length - 1;
for (int i = m + 1; i <= h; i++) {
sum = sum + arr[i];
if (sum > rightSum) {
rightSum = sum;
maxRight = i;
}
}
return new Result(maxLeft, maxRight, leftSum + rightSum);
}
private static Result maxSubArray(int[] A, int low, int high) {
if (low == high) {
return new Result(low, high, A[low]);
}
int mid = (low + high) / 2;
Result leftSubArray = maxSubArray(A, low, mid);
Result rightSubArray = maxSubArray(A, mid + 1, high);
Result maxCrossingSubArray = maxCrossingSum(A, low, mid, high);
int leftSum = leftSubArray.sum;
int rightSum = rightSubArray.sum;
int crossSum = maxCrossingSubArray.sum;
if (leftSum > rightSum && leftSum > crossSum) {
return new Result(leftSubArray.low, leftSubArray.high, leftSubArray.sum);
} else if (rightSum > leftSum && rightSum > crossSum) {
return new Result(rightSubArray.low, rightSubArray.high, rightSubArray.sum);
} else {
return new Result(maxCrossingSubArray.low, maxCrossingSubArray.high,
maxCrossingSubArray.sum);
}
}
public static class Result {
public int low;
public int high;
public int sum;
public Result(int low, int high, int sum) {
this.low = low;
this.high = high;
this.sum = sum;
}
}
/* Driver program to test maxSubArray */
public static Result maxSubArray(int[] arr) {
return maxSubArray(arr, 0, arr.length - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] arrString = sc.nextLine().split(" ");
int n = arrString.length;
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(arrString[i]);
}
Result result = maxSubArray(arr);
int[] subArray = new int[result.high - result.low + 1];
int j = 0;
for (int i = result.low; i <= result.high; i++) {
subArray[j++] = arr[i];
}
System.out.println(Arrays.toString(subArray));
System.out.println("Sum : " + result.sum);
}
}
Views.py
from django.db import models
from django.utils import timezone
from django.forms import ModelForm
from django.utils.text import slugify
from django.utils.crypto import get_random_string
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from PIL import Image
import os
# Create your models here.
class Projects(models.Model):
title = models.CharField(max_length=30)
description = models.TextField(max_length=150)
publish_date = models.DateTimeField(auto_now=False, auto_now_add=True)
update_date = models.DateTimeField(auto_now=True, auto_now_add=False)
slug = models.SlugField(unique=True)
files = models.FileField(upload_to='files/', blank=True)
images = models.ImageField(upload_to='images/', height_field =
'img_height', width_field = 'img_width',blank=True)
img_height = models.PositiveIntegerField(default=600)
img_width = models.PositiveIntegerField(default=300)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
# Generates a random string
unique_string = get_random_string(length=32)
# Combines title and unique string to slugify
slugtext = self.title + "-" + "unique_id=-" + unique_string
self.slug = slugify(slugtext)
return super(Projects, self).save(*args, **kwargs)
def get_p_image_filename(instance, filename):
title = instance.p_post.title
slug_title = slugify(title)
return "post_images/%s-%s" % (slug_slug, filename)
class P_Images(models.Model):
p_post = models.ForeignKey(Projects, default=None,
on_delete=models.PROTECT)
p_image = models.ImageField(upload_to=get_p_image_filename,
verbose_name='Image')
forms.py
def create_projects(request):
P_ImageFormSet = modelformset_factory(P_Images,form=P_ImageForm,
extra=3)
# Special case if the request method is not POST
if request.method != "POST":
project_form = ProjectsForm()
p_formset = P_ImageFormSet(queryset=P_Images.objects.none())
# No more special case ^ from here
project_form = ProjectsForm(request.POST, request.FILES)
p_formset = P_ImageFormSet(request.POST, request.FILES,
queryset=P_Images.objects.all())
# Checks if the form is valid before save
if project_form.is_valid() and p_formset.is_valid():
instance = project_form.save(commit=False)
#if instance.images:
ContentFile(thumb_io.getvalue()))
instance.save()
for p_form in p_formset.cleaned_data:
p_image = p_form['p_image']
photo = Images(p_post=project_form, p_image=p_image)
photo.save()
return render(request, 'projects/forms.html', context)
#else:
# print(project_form.errors, p_formset.errors)
# Return to the main page
context = {
'project_form': project_form,
'p_formset': p_formset,
}
return render(request, 'projects/forms.html', context)
forms.html
from django import forms
from .models import Projects, P_Images
class ProjectsForm(forms.ModelForm):
class Meta:
model = Projects
fields = ('images','title', 'description', 'files')
class P_ImageForm(forms.ModelForm):
class Meta:
model = P_Images
fields = ('p_image',)
这是我的完整回溯
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<!--{{ project_form.as_p }}-->
{% for hidden in project_form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in project_form %}
{{ field }} <br />
{% endfor %}
{{ p_formset.management_form }}
{% for p_form in p_formset %}
{{ p_form }}
{% endfor %}
<input type="submit" value="OK">
</form>