Z
Z
zigen2015-07-10 17:32:37
Django
zigen, 2015-07-10 17:32:37

How to transfer a form from another CBV to CBV?

Good afternoon.
There is a very simple model:

Сlass News(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    article = RichTextField()

and one more:
class Comment(models.Model):
    text = models.TextField()
    news = models.ForeignKey(News)
    author = models.ForeignKey(User)
    pub_date = models.DateTimeField('Добавлено',auto_now_add=True)

News I give as follows:
class NewsDetailView(generic.DetailView):
    model = News
    template_name = 'news/detail.html'

You also need to insert a form for adding a comment from another CBV there, for example:
class AddCommentView(AjaxableResponseMixin,CreateView):
    model = Comment
    fields = ['text']

    def get_initial(self):
        news = get_object_or_404(News, slug=self.kwargs.get('slug'))
        return {
            'news': news, 'author': self.request.user,
        }

How?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-07-10
@zigen

Create a form (now it is dynamically generated by CreateView)

def get_initial(self):
    return {'news': self.get_object(), 'author': self.request.user}

def get_context_data(self, **kwargs):
    kwargs['form'] = CommentForm(self.request.POST, initial=self.get_initial())
    return super().get_context_data(**kwargs)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question