0

我正在尝试创建一个简单的收件箱应用程序,允许用户使用 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})
4

1 回答 1

1

老实说,我会用 javascript 来做这件事。也许这不是最好的方式,或者实际上是最好的方式,但它仍然是一种方式。

模板:

<head> 
<script>
checkbox=getelementbyId('#container');
var itemlist= [];
function togglelist(newitem){
    field=getelementbyId('#'+newitem);
if (!field.value){
        itemlist.push(newitem)
}
else{
   itemlist.remove(itemlist.indexOf(newitem))
};
checkbox.innerHTML="<input type='hidden' id='checkbox' label='hidden_field' value='"+String(itemlist)+"'>";

}
</script>
</head>
<body>
<div id="container"> </div>
{% for m in messages %}
<input type="checkbox" id="{{m.id}}" onchange="togglelist({{m.id}})">
{{m.body}}
{% endfor %}

您的 models.py 可以去掉布尔值,而只有一个字符字段 hidden_​​field。然后在你的views.py中,使用ast库从字符串中解析列表:

import ast
form = CheckBoxForm()
 if request.method =='POST' and form.is_valid():
         deletelist = request.POST.get('hidden_field', False)
         ids=ast.literal_eval(deletelist)
         for id in ids:
             Message.objects.filter(pk=id).delete()

抱歉,我无法对此进行测试,但希望对您有所帮助。

于 2013-07-06T14:56:42.110 回答