我收到了错误:
/ feeds / upload
上的IntegrityError
我尝试使用'外键关键方法连接用户模型和Feed模型。
这是我的model.py:
class feed(models.Model):
user = models.ForeignKey(User,null=True,blank=True)
feed_text = models.CharField(max_length=2000)
date = models.DateField()
upvote = 0
downvote = 0
def __str__(self):
return feed.content
class comments(models.Model):
feed = models.ForeignKey(feed,null=True,blank=True)
comment_text = models.CharField(max_length=600)
user = models.ForeignKey(User)
def __str__(self):
return comments.comment_text
在form.py中:
from django import forms
from .models import *
class feed_form(forms.ModelForm):
class Meta:
model = feed
fields = ('feed_text', )
在views.py中:
def upload(request):
feed_cont = feed_form(data=request.POST)
feed_cont.user = User.objects.get(id =1)
print(feed_cont.user.id)
feed_cont.upvote = 0
feed_cont.downvote =0
feed_cont.save()
return render(request,'feeds/feeds.html')
但是当我试图打印uesr.id时,它起作用..我不知道我在哪里弄错了.. 请帮我解决这个问题.. 提前谢谢..
答案 0 :(得分:1)
您应该将属性设置为不是表单,而是设置为模型实例:
form = feed_form(request.POST)
feed_cont = form.save(commit=False)
feed_cont.user = User.objects.get(id=1)
feed_cont.upvote = 0
feed_cont.downvote = 0
feed_cont.save()