我有两个模型和两个不同的形式。拖曳形式组合在单个视图功能中。这两种形式组合在一个HTML形式中。当我提交HTML表单时,除未保存图像外,其他一切都正常。 这是拖车模型:
class Posts(models.Model):
user = models.ForeignKey(MyUser, on_delete=models.CASCADE)
post_category = models.ForeignKey(Post_Category,
on_delete=models.CASCADE)
post_title = models.CharField(max_length=256)
post_detail = models.TextField(max_length=65536)
def __str__(self):
return "%s %s %s %s " % (
self.user, self.post_category, self.post_title,
self.post_detail)
class Meta:
verbose_name_plural = "Posts"
class Images(models.Model):
post = models.ForeignKey(Posts, on_delete=models.CASCADE)
images = models.ImageField(upload_to='images', blank=True, null=True )
def __str__(self):
return "%s %s" % (self.post, self.images)
class Meta:
verbose_name_plural = "images"
这些形式是:
class PostsForm(forms.ModelForm):
class Meta:
model = Posts
fields = [
'post_category',
'post_title', 'post_detail',
]
class ImagesForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
kwargs.setdefault('label_suffix', '')
super(ImagesForm , self).__init__(*args, **kwargs)
self.fields['car_images'].widget.attrs.update({'class' : 'image',
'style':'display:none','id':'input-image-hidden',
'onchange':"document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" ,
'type':'file', "name":"images", 'accept':'image/*'})
class Meta:
model = Images
fields = [
'images',
]
widgets = {
'images': forms.ClearableFileInput(attrs={'multiple': True}),
}
这是查看功能:
from django.forms import inlineformset_factory
from django.utils.translation import ugettext_lazy as _
def post(request):
form = PostsForm()
imagesForm = ImagesForm()
template_name = 'path/to/template.html'
success_url = 'user_profile.html'
form = PostsForm(request.POST or None)
imagesForm = ImagesForm(request.POST or None,
request.FILES or None)
if form.is_valid() and imagesForm.is_valid():
new_post = form.save(commit=False)
new_post.user = request.user
new_post = form.save()
imagesForm.save(commit=False)
for file in request.FILES.getlist('images'):
instance = Images(
post= Posts.objects.get("images"),
images=file
)
instance.save()
return redirect('index')
else:
imagesForm = ImagesForm(request.POST or None, request.FILES or
None)
return render(request, template_name, {'imagesForm': imagesForm,
'form': form})
提交HTML表单时,将保存除图像外的所有数据(不会出现错误)。将再次显示HTML表单,而不是重定向到用户个人资料页面。 您能告诉我发生了什么以及可能的错误在哪里吗?您能帮我保存多张图片吗
注意:如果必须设置额外的参数,则无法使用内联表单集工厂。我不想限制用户上传数量有限的图像。