我已经定义并创建了以下模型:
class Links(models.Model):
id = models.AutoField(primary_key=True, unique=True),
longlink = models.CharField(max_length=100),
shortlink = models.CharField(max_length=15),
createdate = models.DateField(default=timezone.now)
def __str__(self):
return self.longlink
我的代码:
from appointments.models import Links
def shortlinkgen():
import secrets
return secrets.token_urlsafe(4)
def DateToday():
from datetime import datetime, date, time
now = datetime.now()
return now.strftime("%Y-%m-%d")
link = Links(longlink='https://mail.google.com/mail/u/0/#inbox/FMfcgxvzKQmmrZMGFJVWvsLlFPxQKhJG', shortlink=shortlinkgen(), createdate=DateToday())
link.save()
print(link)
我遇到了错误:
TypeError Traceback (most recent call last)
<ipython-input-2-66d347994058> in <module>()
9 return now.strftime("%Y-%m-%d")
10
---> 11 link = Links(longlink='https://mail.google.com/mail/u/0/#inbox/FMfcgxvzKQmmrZMGFJVWvsLlFPxQKhJG', shortlink=shortlinkgen(), createdate=DateToday())
12 link.save()
13 print(link)
~/.local/lib/python3.6/site-packages/django/db/models/base.py in __init__(self, *args, **kwargs)
482 pass
483 for kwarg in kwargs:
--> 484 raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg)
485 super().__init__()
486 post_init.send(sender=cls, instance=self)
TypeError: 'longlink' is an invalid keyword argument for this function
怎么了?
答案 0 :(得分:3)
class Links(models.Model):
id = models.AutoField(primary_key=True, unique=True),
longlink = models.CharField(max_length=100),
shortlink = models.CharField(max_length=15),
createdate = models.DateField(default=timezone.now)
def __str__(self):
return self.longlink
问题在于每行末尾的“,”。您正在将字段定义为它们的类引用,而不是这些类的实例。应该是
class Links(models.Model):
id = models.AutoField(primary_key=True, unique=True)
longlink = models.CharField(max_length=100,default="") #or null=True incase!
shortlink = models.CharField(max_length=15,default="")
createdate = models.DateField(default=timezone.now)