ユーザーモデルを使用してカスタムのメール送信アプリケーションを作成しようとしています。
メールを送信してアプリケーションを機能させることはできますが、ユーザーが存在しない場合、テンプレートでエラーは発生しません。
そこで、文字数が違反でエラーなしの場合にエラーが発生するかどうかをテストしてみました raise 。誰か助けてくれませんか
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
ビュー.py
@login_required
def Create(request):
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'))
else:
return HttpResponseRedirect(reverse('world:Create'))
return render(request,'create.html',{'messages':messages,'form':form})
フォーム
class NewMessageForm(forms.Form):
recipient = forms.CharField(required=True,max_length=1)
subject = forms.CharField(required=True,max_length=1)
message = forms.CharField(widget=forms.Textarea,required=True,max_length=1)
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
テンプレート
<form method="POST" >{% csrf_token %}
{{form.recipient}}
{{form.subject}}
{{form.message}}
<input type = "submit" value= "send" class="save" id="send"/>
</form>
{{form.recipient.errors}}
{{form.subject.errors}}
{{form.message.errors}}