我尝试使用Filepond上传多张图片,并且它可以从前端运行,但不能从后端运行。
并且也没有从后端获取数据来编辑表单。
仅显示空白的表格。
我在下面添加了我的代码,分别是models.py,forms.py,views.py和HTML代码。我尝试了多种方法上传多张图片,但每次都只会出错。
models.py
class UserDetail(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
image = models.ImageField(null=True)
firm_name = models.CharField(max_length=75, null=True)
slug = models.SlugField(max_length=75, null=True, blank=True)
person_name = models.CharField(max_length=40, null=True)
designation = models.CharField(max_length=20, null=True)
def slug_generator(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(slug_generator, sender=UserDetail)
class UploadImages(models.Model):
userdetail = models.ForeignKey(UserDetail, default=None, on_delete=models.CASCADE)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.userdetail.firm_name
class Meta:
verbose_name_plural = "Upload Extra Images"
forms.py
from django import forms
from customer.models import UserDetail
from django.contrib.auth.forms import UserChangeForm
class EditForm(UserChangeForm):
person_name = forms.CharField(label='Full Name')
image = forms.ImageField(label='Logo Image')
def __init__(self, *args, **kwargs):
super(EditForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'input'
class Meta:
model = UserDetail
fields = ('image', 'firm_name', 'person_name', 'designation')
admin.py
class UploadImagesAdmin(admin.StackedInline):
model=UploadImages
@admin.register(UserDetail)
class UserDetailAdmin(admin.ModelAdmin):
inlines = [UploadImagesAdmin]
class Meta:
model = UserDetail
admin.site.register(UploadImages)
views.py
def template(request, slug_text, template_name='customer/template.html'):
update = UserDetail.objects.get(slug=slug_text)
photos = UploadImages.objects.filter()
length = request.POST.get('length')
for file_num in range(0, int(length)):
UploadImages.objects.create(
update=update,
images=request.FILES.get(f'images{file_num}')
)
form = EditForm(request.POST or None, request.FILES, instance=update)
if form.is_valid():
form.save()
return redirect('dashboard')
return render(request, 'customer/template.html', {'form':form, 'photos':photos})
template.html
{% extends 'base.html' %}
{% load static %}
{% block body %}
{% if user.is_authenticated %}
<section id="form">
<div class="container">
<div class="wrapper">
<div class="title">EDIT Template</div>
<div class="title">Template 1</div>
<form method="POST" action="/customer/designs/1/{{user.userdetail.slug}}" enctype="multipart/form-data">{% csrf_token %}
<div class="form">
<div class="title">HOME</div>
<div class="inputfield">
{{ form.image.label_tag }}
{{ form.image}}
</div>
<div class="inputfield">
{{ form.person_name.label_tag }}
{{ form.person_name}}
</div>
<div class="inputfield">
{{ form.designation.label_tag }}
{{ form.designation }}
</div>
<div class="inputfield">
{{ form.firm_name.label_tag }}
{{ form.firm_name }}
</div>
<div class="inputfield">
<input type="submit" id="saveBtn" value="Update" class="btn">
</div>
</div>
</form>
</div>
</div>
</section>
{% else %}
<div>
<h1> 404 - Page Not Found </h1>
<h3> You Must Login First </h3>
<p><a href="{% url 'login' %}">Login</a> to Continue</p>
</div>
{% endif %}
<script>
document.addEventListener('DOMContentLoaded', function(){
var files = []
FilePond.registerPlugin(
FilePondPluginFileEncode,
FilePondPluginFileValidateSize,
FilePondPluginImageExifOrientation,
FilePondPluginImagePreview
);
const inputElement = document.querySelector('input[type="file"]');
const pond = FilePond.create(inputElement,{
onaddfile: (err, fileItem) => {
files.push(fileItem.file)
console.log(files)
},
onremovefile: (err, fileItem) => {
const index = files.indexOf(fileItem.file)
if (index > -1) {
files.splice(index, 1)
}
console.log(files)
}
});
var formData = new FormData();
$(document).on('click', '#saveBtn', function(e) {
formData.append('length', files.length)
for (var i = 0; i < files.length; i++) {
formData.append('images' + i, files[i])
}
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}')
$.ajax({
type: 'POST',
url: '/customer/designs/1/{{user.userdetail.slug}}',
data: formData,
cache: false,
processData: false,
contentType: false,
enctype: 'multipart/form-data',
success: function (){
alert('The post has been created!')
},
error: function(xhr, errmsg, err) {
console.log(xhr.status + ":" + xhr.responseText)
}
})
})
})
</script>
{% endblock body %}