我正在尝试创建一个简单的收件箱应用程序,允许用户使用 UserModel 相互发送消息。
如何在表单集的隐藏字段中填充查询集中所有对象的 ID?因为当我尝试
File "C:\mysite\pet\views.py" in message
913. initial.update({'hidden_field': messages.id})
异常类型:/message/ 处的 AttributeError 异常值:'function' 对象没有属性 'id'
class Message(models.Model):
user = models.ForeignKey(User, related_name='sender')
recipient = models.ForeignKey(User, related_name='recipient')
created = models.DateTimeField(auto_now_add=True)
body = models.CharField(max_length=1000)
read = models.BooleanField(default=False)
trash = models.BooleanField(default=False)
sentmessage = models.BooleanField(default=False)
thread = models.ForeignKey(Thread,blank=True,null=True)
draft = models.BooleanField(default=False)
def __unicode__(self):
return self.body
意见
@login_required
def message(request):
person = Person.objects.get(user=request.user)
messages = Message.objects.filter(recipient=request.user.id).order_by("-created").values
initial = {}
initial.update({'hidden_field': messages.id})
form = formset_factory(CheckBoxForm)
formset = form(initial=initial)
return render(request,'messages.html',{'messages':messages,'form':form,'person':person})
形式
class CheckBoxForm(forms.Form):
checkbox = forms.BooleanField(required=False)
hidden_field = forms.CharField(widget=forms.HiddenInput())
模板
{% for m in messages %}
{{m.body}}
{% endfor %}
@新代码
@login_required
def message(request):
messages = Message.objects.filter(recipient=request.user).order_by("-created")
form = CheckBoxForm()
if request.method =='POST':
form = ReplyForm(request.POST)
if form.is_valid():
id = request.POST.get('hidden_field', False)
Message.objects.filter(pk=id).delete()
return render(request,'messages.html', {'messages':messages,'form':form,'person':person})