我当前的问题是没有表单显示,并且如果我将{{form.as_p}}添加到create.html页面,则仅显示TradeForm而不显示任何图像。
我已将此问题用作参考: how to upload multiple images to a blog post in django
views.py
class TradeCreateView(CreateView):
template_name = "tj/cp/trade/create.html"
form_class = TradeForm
form_class_image = ImageForm
queryset = Trade.objects.all()
def post(self, request, *args, **kwargs):
ImageFormSet = modelformset_factory(Image, form=ImageForm, extra=3)
formset = ImageFormSet(request.POST, request.FILES, queryset=Image.objects.none())
if TradeForm.is_valid() and formset.is_valid():
trade_form = TradeForm.save(commit=False)
trade_form.user = request.user
trade_form.save()
for form in formset.cleaned_data:
image = form['address']
photo = Image(trade=trade_form, image=image)
photo.save()
def form_valid(self, form):
print(form.cleaned_data)
return super().form_valid(form)
forms.py
class TradeForm(forms.ModelForm):
class Meta:
model = Trade
fields = [
'user',
'target_size',
'target_entry',
...
]
# exclude = ['user',]
class ImageForm(forms.ModelForm):
address = forms.ImageField(label='Image')
class Meta:
model = Image
fields = ('address',)
models.py
class Trade(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
comments = models.TextField(max_length=10000, blank=True, null=True)
def get_image_filename(instance, filename):
title = instance.post.title
slug = slugify(title)
return "uploads/%s-%s" % (slug, filename)
class Image(models.Model):
trade = models.ForeignKey(Trade, blank=True, null=True, default=None, on_delete=models.CASCADE)
address = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name='Image')
title = models.CharField(max_length=100, null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
def __unicode__(self):
return self.title
create.html
<form id="TradeCreateView" method="post" action="." enctype="multipart/form-data">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{ form.as_p }}
{% endfor %}
<input type="submit" name="submit" value="Submit" />
</form>