Захват нескольких изображений из шаблона [закрыто]
Этот код связан с запросом на реферальный товар, в котором пользователь может загрузить столько фотографий, сколько захочет для своего реферального запроса. Есть две формы, одна для фотографий, а другая для описания и номера запрашиваемого продукта. Когда я хочу иметь несколько изображений, что я должен сделать, потому что таким образом сохраняется только изображение, и это связано с последней формой, которая загружается с помощью Ajax.
модели
class Reject(models.Model):
product = models.ForeignKey(Product, related_name='rejects', on_delete=models.CASCADE)
quantity = models.IntegerField()
rejecter = models.ForeignKey(ShopUser, related_name='rejects', on_delete=models.CASCADE)
description = models.TextField(max_length=1000)
verify = models.BooleanField(default=False)
created = jmodels.jDateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
indexes = [
models.Index(fields=['-created'])
]
def __str__(self):
return f'{self.product} مرجوع شد توسط {self.rejecter}'
def get_total_cost(self):
return self.product.discount_price * self.quantity
def image_sorter(instance, filename):
return f"rejected_product_images/{instance.created.year}/{instance.created.month}/{instance.created.day}/{filename}"
class Image(models.Model):
rejected_product = models.ForeignKey(Reject, related_name='images', on_delete=models.CASCADE)
created = jmodels.jDateTimeField(auto_now_add=True)
file = ResizedImageField(upload_to=image_sorter)
class Meta:
ordering = ['-created']
indexes = [
models.Index(fields=['-created']),
Формы
class RejectForm(forms.ModelForm):
class Meta:
model = Reject
fields = ['quantity', 'description']
widgets = {
'quantity': forms.NumberInput(attrs={'class': 'quantity-of-reject-input'}),
'description': forms.Textarea(attrs={'class': 'description-of-reject-input'})
}
labels = {
'quantity': "تعداد کالاهای ارجاعی",
'description': "توضیحات دلیل ارضاع"
}
class RejectImageForm(forms.Form):
image = forms.FileField(widget=forms.FileInput(attrs={'class': 'reject-image-input'}),label=None)
шаблон
{% extends 'parents/base_template.html' %}
{% block title %} Reject product{% endblock %}
{% block body %}
<form class="user-form" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="images">
{{ image_form.as_p }}
</div>
<p id="add-another-image">اضافه کردن تصویر</p>
{{ texts_form.as_p }}
<input type="submit" class="user-submit" value="ثبت درخواست">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
$(document).ready(function(){
$('#add-another-image').click(function (){
$.ajax({
type: 'GET',
url: '{% url 'ordering:add_image' %}',
datatype: 'html',
success: function(data){
$('.images').append(data);
}
});
});
});
</script>
{% endblock %}
Шаблон дляajax
{{ image_form.as_p }}
view
@login_required
def reject_product(request, product_id=None):
if request.headers.get('x-requested-with') == "XMLHttpRequest":
image_form = RejectImageForm()
return render(request, 'ajax/ajax_reject_image_form.html', {'image_form': image_form})
user = request.user
product = Product.objects.get(id=product_id)
if request.method == 'POST':
texts_form = RejectForm(data=request.POST)
image_form = RejectImageForm(data=request.POST, files=request.FILES)
if texts_form.is_valid() and image_form.is_valid():
rejected_product = texts_form.save(commit=False)
rejected_product.rejecter = user
rejected_product.product = product
rejected_product.save()
Image.objects.create(rejected_product=rejected_product, file=image_form.cleaned_data['image'])
rejected_product.save()
return redirect('account:orders_status', 'rejected')
else:
texts_form = RejectForm()
image_form = RejectImageForm()
context = {
'texts_form': texts_form,
'image_form': image_form,
}
return render(request, 'forms/reject.html', context)
Я пробую это
Image.objects.create(rejected_product=rejected_product, file=request.FILES['image'])
и это
for image in request.FILES:
Image.objects.create(rejected_product=rejected_product, file=image)