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