Django发送邮件,草稿功能问题

时间:2013-07-02 11:52:40

标签: django

我正在尝试使用自定义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>

1 个答案:

答案 0 :(得分:1)

您可以在Message中添加一个BooleanField“draft”,用于确定当前邮件是否为草稿,并通过排除包含州草稿的所有邮件以及recipient = current_user的位置来过滤邮箱。

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

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