请帮助我。我是Django的新手,不能理解以下内容。我有CreateView的子类来创建帖子。我正在创建一个出租站点项目,人们可以在其中发布自己的内容并将文件(图像)附加到该项目。一个人应该可以将他想要添加的尽可能多的图像附加到一个表单中。我在互联网上发现一个决定,我需要使用2个模型-1个模型用于发布+ 1个单独的图像模型。是吗?
Post表单是通过CreateView子窗格在我的views.py中创建和处理的。现在如何将图像的新单独模型与我的CreateView连接?并将所有图像保存到当前的“张贴表格”中?
预先感谢
models.py
class Post(models.Model):
post_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
post_title = models.CharField(_('Title'),max_length=200, null=True, blank=False)
post_type = models.CharField(_('Type'),max_length=18, choices=post_type_list, default='appart')
post_content = models.TextField(_('Your post description'),blank=True)
post_created_date = models.DateTimeField(default=timezone.now, help_text=_('Post creation date and time.'),)
post_published_date = models.DateTimeField(null=True, blank=True, help_text=_('Post publication date and time.'),)
def get_absolute_url(self):
return reverse("posts:post_details", kwargs={'pk':self.pk,'post_type':self.post_type})
class Post_Gallery(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
current_hour = datetime.datetime.now()
images = models.ImageField(_('Upload some pictures'),upload_to='uploads/%Y/%m/%d/{}'.format(current_hour.hour), max_length=100, null=True, blank=True)
def __unicode__(self):
return self.images.url
forms.py
class NewPostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
'post_title','post_type','post_content',
]
class GalleryForm(forms.ModelForm):
class Meta:
model = Post_Gallery
fields = ['images',]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['images'].widget.attrs.update({'multiple': True, 'accept': 'image/jpg,image/jpeg,image/png,image/gif',} )
actual views.py
class NewPostView(CreateView):
form_class = NewPostForm
template_name = 'posts/submit-post.html'
model = Post
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def form_valid(self, form):
form.instance.post_author = self.request.user
return super().form_valid(form)
def get(self, request):
form_class = self.get_form_class()
form = self.get_form(form_class)
return render(self.request, 'posts/submit-post.html', {'form': form})