2017-07-15 73 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'}), 
      }