2016-03-27 11 views
0

私は機能を作って、ユーザーが投稿を追加したときにメインビューでそれを呼び出しました。投稿ごとにpost_countを更新するにはどうすればよいですか?

`type object 'Post' has no attribute 'post_count' 

私が間違っているのは何:しかしPOST_COUNTは私が新しい記事を追加していると私はこのエラーを取得していたときに更新されていませんか?

これは

class Post(models.Model): 
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) 
    title = models.CharField(max_length=100) 
    body = models.TextField() 
    date = models.DateField(auto_now_add=True) 
    likes = models.IntegerField(default=0) 
    post_count = models.PositiveIntegerField(default=0) 

    def __str__(self): 
     return self.title 

私model.pyですこれは私のview.pyです:

def create_post(request): 
    context = RequestContext(request) 
    if request.method == 'POST': 
     pform = PostForm(data=request.POST, prefix='PostForm') 
     if pform.is_valid(): 

      new_post = pform.save(commit=False) 
      new_post.user = request.user 
      post_count(request, new_post.user) 
      new_post.save() 
      return HttpResponseRedirect('/forum/all') 
    else: 
     pform = PostForm() 

    return render_to_response('forum/createpost.html', 
           {'pform': pform}, 
           context) 

これは、ユーザーごとの投稿数を更新カウントする私の関数です。

def post_count(request, user, **kwargs): 
     if user: 
      Post.post_count += 1 
      Post.save() 
+0

モデルの編集後に移行しましたか? –

+0

あなたはクラス変数で作業したいと思いますか? – flaschbier

+0

@JesseBakkerこんにちは、はい、移行は正常に行った。 1人のユーザーあたりのログイン回数をカウントするには、うまくいきました。 – Selena

答えて

0
def post_count(request, user, **kwargs): 
    if user: 
     user.post_count += 1 
     user.save() 

クラスの代わりに、オブジェクトのPOST_COUNTを変更、関数にあなたのポストのオブジェクトを渡します。

投稿の投稿数はあまり意味がありません。あなたはそれをユーザーにするつもりはありませんか?

+0

はい、ユーザーが投稿を追加すると、すべてのユーザーの数を更新する必要があります。 post_countをUserモデルに移動する必要がありますか? – Selena

+0

@Selena次に、Userモデルを変更する必要があります。 authモデルを使用しているときは、フィールドを追加できるように、まず1対1の関係でユーザーを拡張する必要があります。 –

+0

はいいいえ。私はそれを試み、それが動作するかどうかを見てみましょう。あなたの時間をありがとう。 – Selena

関連する問題