JackRoster
JackRoster

Reputation: 1663

Django Form not raising error

I'm trying to create a custom send email application using the User-model.

I am able to get the application functioning by sending email but it does not raise an error on the template , If the user doesn't exist.

So I tried to test whether it will raise any error at all if the number of characters is breach and no error raise . Can someone help me

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

views.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})

forms

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

template

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

Upvotes: 0

Views: 119

Answers (1)

Jure C.
Jure C.

Reputation: 3080

Your pattern is slightly wrong:

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:
    form = NewMessageForm()

Idea is that you first check if it's a POST, ok - is it working? Great- return correct flow - otherwise fall-through and pass form with errors attached by is_valid() to context. In case it's a new one - create it as a last resort since it doesn't hold any information yet.

Also don't forget form.non_field_errors since it will contain errors that are not specific to any field.

Upvotes: 1

Related Questions