我需要在我的Django表单集id
字段中添加image
,我知道如何向模型表单添加ID。下面是我的帖子模型。
下面是我的表单模板
<h2> Create/Update a post</h2>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% bootstrap_form form %}
#More images
{% bootstrap_formset formset %}
<br/><br/><input type="submit" class="btn btn-primary" value="Post"/>
</form>
下面是我的模特,以防万一
class Post(models.Model):
user = models.ForeignKey(User, related_name='posts')
title = models.CharField(max_length=250, unique=True)
message = models.TextField()
post_image = models.ImageField(upload_to='post_images/')
下面的模型添加剩余的图像
class Prep (models.Model): #(Images)
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_prep')
image = models.ImageField(upload_to='post_prep_images/', blank=True, null=True)
image_title = models.CharField(max_length=100)
image_description = models.CharField(max_length=250)
下面是我的观点
@login_required
def post_create(request):
ImageFormSet = modelformset_factory(Prep, fields=('image',), extra=7, max_num=7,
min_num=2)
if request.method == "POST":
form = PostForm(request.POST or None, request.FILES or None)
formset = ImageFormSet(request.POST or None, request.FILES or None)
if form.is_valid() and formset.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
post_user = request.user
for f in formset.cleaned_data:
try:
photo = Prep(post=instance, image=f['image'], image_title=f['image_title'], image_description=f['image_description'])
photo.save()
except Exception as e:
break
return redirect('posts:single', username=instance.user.username, slug=instance.slug)
else:
form = PostForm()
formset = ImageFormSet(queryset=Prep.objects.none())
context = {
'form': form,
'formset': formset,
}
return render(request, 'posts/post_form.html', context)
现在如何在Django表单集中的字段图像中添加
id
。您可以在视图中看到的forms.py只有一个PostForm