Django在视图上拆分保存功能

时间:2013-07-02 11:13:37

标签: python django

我正在尝试创建一个简单的消息传递应用程序,用户可以相互发送邮件。

enter image description here

我可以创建一条消息并发送它,但如果我想将其另存为草稿呢?

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

</form>

<input type = "submit" value= "draft" class="save"/>

我的表单有一个提交按钮,这是用于发送邮件的发送按钮。 如果我要实现一个保存功能,它是草稿功能。我还必须在表单中添加一个保存按钮。如果我这样做的话。如何在我的views.py中唯一标识用户选择了哪个选项?

@login_required
def Create(request):
    person = Person.objects.get(user=request.user)
    form = NewMessageForm()
    if request.method =='POST':
        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'))



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

形式

class NewMessageForm(forms.ModelForm):
    recipient = forms.CharField(required=True,max_length=1)
    message = forms.CharField(widget=forms.Textarea,required=True,max_length=1)


    class Meta:
       model = Thread 
       fields = ('subject',)  

模型

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)

1 个答案:

答案 0 :(得分:3)

只需设置每个提交输入的名称:

<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>

在视图中,检查哪个被点击:

if request.POST.get('_save', False):
    # save
elif request.POST.get('_send', False):
    # send
else:
    return HttpResponseBadRequest()

注意:我不清楚为什么你没有使用many django messaging apps之一。