2016-04-05 15 views
2

ブログエントリがあり、URLが/blog/1であると仮定して、ブログの投稿にコメントしてURL /comment/1をクリックするとします。ジャンゴでは、urls.pyUpdateViewを使用してブログ投稿にコメントを追加する

urlpatterns = (
    url(r'^blog/(?P<pk>[0-9])',BlogView.as_view()) 
    url(r'^comment/(?P<pk>[0-9])',CommentView.as_view() 
) 

models.pyのようになります。だから今、私はforms.py

class CommentForm(forms.ModelForm): 
    for_blog = forms.IntegerField(required=True) 
    def __init__(self, blog, *args, **kwargs): 
    . 
    . 
    class Meta: 
    model=Comment 

でCommentFormを持って

class Blog(models.Model): 
    text = models.TextField() 

class Comment(models.Model): 
    comment_text = models.TextField() 
    for_blog = models.ForeignKey(Blog) 

のようなものです質問は、どのように私は実装しない、ありますこれはDjangoのUpdateViewでですか?特に、CommentFormのfor_blogにはBlogIDがあらかじめ入力されていますので、より簡単に使用できます。

答えて

0

(あなたが何かを必要としない)、あなたの実際の質問に答えるためにCommentFormを使用するように、メタクラスのフィールドを定義します。

class CommentForm(forms.ModelForm): 

    class Meta: 

    model=Comment 
    fields = ['for_blog'] 

その後、あなたのビューでは、のようなものを実行します。

class ClassView(UpdateView): 

    def get(self, request, pk, ...): 

    blog = get_object_or_404(Blog, pk) 
    forms = [CommentForm(instance=comment) for comment in blog.comment_set.all()] 
    return render(request, 'template.html', {'forms': forms}) 
0

私はフォームセット(https://docs.djangoproject.com/en/dev/topics/forms/formsets/)を使用します。次に、pkを使用してブログオブジェクトを読み込み、フォームセットのinstance kwargとして渡すことができます。テンプレートにformsetをレンダリングするだけで、関連するブログコメントが表示されます。

また、コメントの追加/削除や簡単なフォーム管理も簡単に追加/削除できます。

関連する問題