1

我正在尝试在使用自定义 UserModel 的简单消息应用程序上实现草稿功能

草稿功能是当用户不立即发送邮件而是保存它时。

我无法弄清楚如何使用我的模型实现草稿功能。

我能够弄清楚如何发送邮件。

@login_required
def Create(request):
    person = Person.objects.get(user=request.user)
    form = NewMessageForm()
    if request.POST.get('send', False):
        form = NewMessageForm(request.POST)
        if form.is_valid():
            recipient = form.cleaned_data['recipient']
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            thread = Thread.objects.create(subject=subject,user=request.user)
            recipient = User.objects.get(username=recipient)
        message =    Message.objects.create(user=request.user,recipient=recipient,body=message,thread=thread)
            return HttpResponseRedirect(reverse('world:message'))

    elif request.POST.get('save', False):
        #How can I save it as a draft?

    return render(request,'create.html',{'messages':messages,'form':form,'person':person})

楷模

class Thread(models.Model):
    subject = models.CharField(max_length=100, blank=True)
    user = models.ForeignKey(User)


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)


    def __unicode__(self):
        return self.body

形式

class NewMessageForm(forms.ModelForm):
    recipient = forms.CharField(required=True,max_length=1)
    message = forms.CharField(widget=forms.Textarea,required=True,max_length=1)
    checkbox = forms.BooleanField(required=False)
    def clean_recipient(self):
        recipient = self.cleaned_data['recipient']
            try:
                recipient = User.objects.get(username=recipient)
            except User.DoesNotExist:
                raise forms.ValidationError("This username does not exist")
            return recipient
class Meta:
    model = Thread 
    fields = ('subject',)  

模板

<form method="POST" >
    {% csrf_token %}
    {{form.recipient}}
    {{form.subject}}
    {{form.message}}
    <input type="submit" value="send" name="_send" />
    <input type="submit" value="save" name="_save" />
</form>
4

1 回答 1

1

您可以在 Message 中添加一个 BooleanField “draft”,以确定当前消息是否为草稿,并通过排除每条带有状态草稿和 where 的消息来过滤邮箱recipient = current_user

这需要通过在发送消息时将草稿设置为 0 来修改您的逻辑,在保存消息时设置为 1。

编辑:我没有看到你的messagesent属性。您可以将它用于该行为,我认为它是合适的:)

于 2013-07-02T11:55:07.763 回答