[Answer]-Add optional fields to django's built-in comments app

1👍

you should set field optional in model like this:

class MyComment(Comment):
    thumbs_up = models.IntegerField(default=0)
    thumbs_down = models.IntegerField(default=0)

take a look at Field options for more information.
And change your form like this:

class MyCommentForm(CommentForm):
    thumbs_up = forms.IntegerField(required=False)
    thumbs_down = forms.IntegerField(required=False)

and change get_comment_create_data like this:

def get_comment_create_data(self):
    data = super(MyCommentForm, self).get_comment_create_data()
    data['thumbs_up'] = self.cleaned_data.get('thumbs_up', 0)
    data['thumbs_down'] = self.cleaned_data.get('thumbs_down', 0)
    return data

0👍

You can tell field to be optional by setting “required”:

class MyCommentForm(CommentForm):
    thumbs_up = forms.IntegerField(required=False)
    thumbs_down = forms.IntegerField(required=False)

0👍

Modify your Model… it’s work.

class MyComment(Comment):
    thumbs_up = models.IntegerField(default=0, blank=True)
    thumbs_down = models.IntegerField(default=0, blank=True)

blank attribute let you to be set null in admin panel, and null attribute let you set null in database (null=True). i think in your case you just need to set blank=True, because you set default for your fields in model.

Leave a comment