2017-02-24 50 views
0

我目前正在用Django創建一個社交平臺。現在,我正在開發他們的儀表板,並希望最終用戶能夠發佈自己的帖子。這是我的Post模型:表單提交不生成新的Post對象

class Post(models.Model): 
    user = models.ForeignKey(User) 
    posted = models.DateTimeField(auto_now_add=True) 
    content = models.CharField(max_length=150) 
    Likes = models.IntegerField(default=0) 

def __str__(self): 
    return self.user.username 

我對Post模型形式:

class Post_form(forms.ModelForm): 

    class Meta: 
     model = Post 
     fields = (
      'content', 
      ] 

    def __init__(self, *args, **kwargs): 
     super(Post_form, self).__init__(*args, **kwargs) 
     self.fields['content'].label = "" 
     self.fields['content'].widget.attrs={ 
      'id': 'id_content', 
      'class': 'myCustomClass', 
      'name': 'name_content', 
      'placeholder': 'What are you thinking about?', 
     } 

當表單被提交,它正確地產生與內容字段的值POST請求。當我在視圖中保存表單時,不會生成新帖子。我究竟做錯了什麼?

我views.py:

def dashboard_view(request): 
    if request.POST: 
     form = Post_form(data=request.POST, instance=request.user) 
     if form.is_valid(): 
      form.save() // <- no new post gets generated after saving 
      return redirect(reverse('dashboard')) 
     else: 
      return redirect(reverse('settings')) 
    else: 
     form = Post_form 
     gebruikers = User.objects.all() 
     all_posts = Post.objects.all().order_by('-posted') 
     return render(request, 'Dashboard/index.html', {'gebruiker':gebruikers, 'posts':all_posts, 'form': form},) 

回答

1

不能在用戶通過作爲實例參數的帖子的形式。您應該省略該參數並將用戶指定從保存返回的實際Post實例。

form = Post_form(data=request.POST) 
if form.is_valid(): 
    post = form.save(commit=False) 
    post.user = request.user 
    post.save()