2017-07-15 71 views
0

我有一些问题,我可以上传文本字段'文本'和字段'视频',我在其中放置一个URLField,问题是,从管理面板我可以上传图像没有任何问题。但从CreateView的角度来看,我是不可能的。如何在我的帖子上用CreateView上传图片?

我被告知需要在窗体中添加标签(enctype =“multipart/form-data”),它可以工作,但不是将其上传到/media/posts/image.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> 

views.py:

class PostCreateView(generic.CreateView): 
    form_class = PostForm 
    success_url = reverse_lazy('timeline') 
    template_name = 'posts/post_new.html' 

    def form_valid(self, form): 
     obj = form.save(commit=False) 
     obj.user = self.request.user 
     obj.date_created = timezone.now() 
     obj.save() 
     return redirect('timeline') 

forms.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') 

models.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

+0

为什么你再次在模型表单中声明字段? –

回答

1

要将文件字段添加到您的形式如果要修改表单域的小部件,你从forms模块像image = forms.FileField()

使用FileField在表单中,只需将widgets属性添加到Meta类。像这样:

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