如何在我的帖子中上传带有CreateView的图像?

2024-06-17 13:37:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些问题,我可以上传像字段'text'和字段'video'这样的文本,其中我放置了一个URLField,问题是从管理面板上传图像没有任何问题。但是在用CreateView从一个视图来做的时候,我是不可能的。在

我被告知要将标签(enctype=“multipart/formdata”)添加到表单中,它就可以工作了,但是没有上传到/media/posts/图像.jpg它试图将其上载到(/media/image.jpg),但最后它没有上载图像。在

我真的只想把图片上传到我的帖子中,你可以在这里看到https://plxapp.herokuapp.com/,然后用头像和UserProfile的头文件进行上传。在

如果他们有任何程序或验证,他们可以告诉我在这里。在

我留下我的代码:

模板:

        <form action="" enctype="multipart/form-data" method="post">
            {% csrf_token %}
            <div class="form-group">
                <label for="{{ form.subject.id_text }}">Text</label>
                {{ form.text }}
            </div>
            <div class="form-group">
                <label for="{{ form.subject.id_image }}">Image</label>
                {{ form.image }}
            </div>
            <div class="form-group">
                <label for="{{ form.subject.video }}">Video</label>
                {{ form.video }}
            </div>
            <button type="submit" class="btn btn-success">Publish <span class="glyphicon glyphicon-edit" aria-hidden="true"></span></button>
        </form>

在视图.py公司名称:

^{pr2}$

在表单.py公司名称:

class PostForm(forms.ModelForm):
    text = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'What are you thinking?', 'maxlength': '200', 'rows': '3'})
)
    image = forms.CharField(
        widget=forms.FileInput(attrs={'class': 'form-control'}), required=False
)
    video = forms.CharField(
        widget=forms.URLInput(attrs={'class': 'form-control', 'placeholder': 'Youtube, Twitch.tv, Vimeo urls.', 'aria-describedby': 'srnm'}), required=False
)

    class Meta:
        model = Post
        fields = ('text', 'image', 'video')

在模型.py在

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.CharField(max_length=200)
    image = models.ImageField(upload_to='posts', blank=True)
    video = models.URLField(blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-date_created"]

    def __str__(self):
        return "{} {} (@{}) : {}".format(self.user.first_name,self.user.last_name, self.user.username,self.text)

Github(来源): https://github.com/cotizcesar/plaxedpy


Tags: text图像imageselfdivformtruemodels
1条回答
网友
1楼 · 发布于 2024-06-17 13:37:12

要将文件字段添加到表单中,请使用forms模块中的FileField,就像image = forms.FileField()

如果要修改表单内表单字段的小部件,只需将widgets属性添加到元类中。像这样:

class PostForm(Form):
    image = FileField()
    class Meta:
        fields = ('title', 'text')
        widgets = {
            'title': forms.TextInput(attrs={'what': 'ever'}),
             }

相关问题 更多 >