O
O
Oleg Vedernikov2015-12-25 14:05:22
Django
Oleg Vedernikov, 2015-12-25 14:05:22

How to add a default value?

Can you please tell me how to correctly define the initial attribute? When I try to create a comment, I get the error IntegrityError ... null value in column "comment_article_id" violates not-null constraint. The comment is linked to the article via the comment_article field.
views.py

class Comment(CreateView):
    model = Comment
    form_class = CommentForm
    http_method_names = ['post']
    template_name = 'article_detail.html'
    success_url = '/blog'
    initial = {'comment_article': self.object.pk}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nerevar_soul, 2015-12-25
@Nerevar_soul

If you need to edit an object, then it is better to use UpdateView. CreateView is intended to create new objects, though.
If you need default values ​​when creating all new objects, then in the model you can write default for the required fields.

A
Andrey K, 2015-12-25
@mututunus

Something like this:

class CommentView(CreateView):
    def get_initial(self):
        initial = super(CommentView, self).get_initial():
        initial['comment_article'] = Article.objects.get(id=self.kwargs['article_id'])

        return initial

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question