Reputation: 194
I wanna add a thumb-up and thumb-down counter as comments' fields. And I added two IntegerFields to a class called 'MyComment' in models.py. And I also use a forms.py like this:
from django import forms
from django.contrib.comments.forms import CommentForm
from blog.models import MyComment
class MyCommentForm(CommentForm):
thumbs_up = forms.IntegerField()
thumbs_down = forms.IntegerField()
def get_comment_model(self):
return MyComment
def get_comment_create_data(self):
data = super(MyCommentForm, self).get_comment_create_data()
data['thumbs_up'] = self.cleaned_data['thumbs_up']
data['thumbs_down'] = self.cleaned_data['thumbs_down']
return data
After that, when I submit a comment, it says that: thumbs_up and thumbs_down are required. How do I make them optional, just like the default field "Users' URL"? Any help will be appreciated.
OK, here's my MyComment model:
from django.contrib.comments.models import Comment
class MyComment(Comment):
thumbs_up = models.IntegerField(default=0)
thumbs_down = models.IntegerField(default=0)
Upvotes: 0
Views: 105
Reputation: 5194
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
Upvotes: 1
Reputation: 1046
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.
Upvotes: 0
Reputation: 10827
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)
Upvotes: 0