python – Django:对象没有attibute’id’

保存对象时,它显示如下错误:

'feed' object has no attribute 'id'

这是我的代码:

form.py

from django import forms
from .models import feed

class feed_form(forms.ModelForm):
    class Meta:
        model = feed
        fields = ('feed_text',  )

models.py

class feed(models.Model):
    user = models.ForeignKey(User,null=True,blank=True)
    feed_text = models.CharField(max_length=2000)
    date =0 
    upvote = 0
    downvote = 0

    def __str__(self):
        return feed.content

    def __init__(self):
        date = timezone.now()

views.py

def upload(request):
    feed_cont = feed_form(data=request.POST)
    feed_cont.save(commit=False)
    feed_cont.user = User.objects.get(pk =1)
    feed_cont.upvote = 0
    feed_cont.downvote = 0
    feed_cont.save()
    return render(request,'feeds/feeds.html')

我在哪里弄错了?我是否以正确的方式使用外键方法?
提前致谢

最佳答案 你需要在超类上调用__init __()让django正确初始化你的模型:

class feed(models.Model):
    ...
    def __init__(self, *args, **kwargs):
        super(feed, self).__init__(*args, **kwargs)

        date = timezone.now()
点赞