Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model in Django 1.9. TypeError: __init__() got multiple values for argument 'verbose_name'

Tags:

python

django

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

like image 505
Donotyou Avatar asked Oct 03 '16 07:10

Donotyou


2 Answers

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 and OneToOneField, 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.

like image 181
vishes_shell Avatar answered Oct 17 '22 22:10

vishes_shell


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

like image 1
Igor Pomaranskiy Avatar answered Oct 17 '22 23:10

Igor Pomaranskiy