I have Python 3.5 and Django 1.9 try to do the next
class Question(models.Model):
def __init__(self, *args, question_text=None, pub_date=None, **kwargs):
self.question_text = question_text
self.pub_date = pub_date
question_text = models.CharField(max_length=200, verbose_name="Question")
pub_date = models.DateTimeField('date_published', verbose_name="Date")
def __str__(self):
return self.question_text
def __unicode__(self):
return self.question_text
class Meta:
verbose_name = "Question"
But got an error
File "/home/donotyou/PycharmProjects/djangobook/polls/models.py", line 15, in Question pub_date = models.DateTimeField('date_published', verbose_name="Date") TypeError: init() got multiple values for argument 'verbose_name'
Please help
You don't need to override __init__
in Django. Django is doing everything for you, you just need to define your models and you are fine.
But the error you are getting because pub_date = models.DateTimeField('date_published', verbose_name="Date")
here you are setting verbose_name
twice, because the first argument of django Field
is verbose_name
and after that you setting the same verbose_name
making two same arguments passing to class.
So basically you need to do is:
class Question(models.Model):
question_text = models.CharField(max_length=200, verbose_name="Question")
pub_date = models.DateTimeField('date_published') # or pub_date = models.DateTimeField("Date")
def __str__(self):
return self.question_text
def __unicode__(self):
return self.question_text
class Meta:
verbose_name = "Question"
NOTE: In most cases it's more readable to passing verbose_name
as a first argument without any verbose_name=
except relational fields.
From docs:
Each field type, except for
ForeignKey
,ManyToManyField
andOneToOneField
, takes an optional first positional argument – a verbose name. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
I believe you should not override __init__()
here (as @vishes_shell supposed too). Instead of this, if you want to made some customization of instances initialization, you can add classmethod create
to the model. Here is documentation: https://docs.djangoproject.com/en/1.10/ref/models/instances/#creating-objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With