Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

invalid syntax Django

when I saved my view.py it threw an error of "invalid syntax" I'm not seeing an issue.

messages.add_message(request, message.SUCCESS, "Message sent!")

whole view:

from django.contrib import messages
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render

from . import forms



def clock_in_view(request):
    form = forms.ClockInForm()
    if request.method == 'POST':
        form = forms.ClockInForm(request.POST)
        if form.is_valid():
            print('continue')       
    return render(request, 'clockinform.html', {'form': form})  



def contact_form(request):
    form = forms.ContactForm()
    if request.method == 'POST':
        form = form.ContactForm(request.POST)
        if form.is_valid():
            send_mail(
                'Email from {}'.format(form.cleaned_data['name'],
                form.cleaned_data['message'],
                '{name} <{email}>'.format(**form.cleaned_data),
                ['Gerald@example.com']
            )
            messages.add_message(request, messages.SUCCESS, "Message sent!")
        return HttpResponseRedirect(reverse('contact'))
    return render(request, 'contactform.html', {'form': form})
Gavin Ralston
Gavin Ralston
28,770 Points

When you say "it threw an error" was there a more specific message? Or did python simply say "invalid syntax" and crash?

The stack trace would come in handy here, if you could post it.

3 Answers

Gavin Ralston
Gavin Ralston
28,770 Points
def contact_form(request):
    form = forms.ContactForm()
    if request.method == 'POST':
        form = form.ContactForm(request.POST)

The second asignment is assigning form.ContactForm() instead of forms.ContactForm()

So I'm guessing the syntax error is there because there is no new_message method on that item.

It simply said "invalid syntax" crashed it said the invalid syntax can from line 30 the '^' was at the 'e' of messages.

messages.add_message(request, messages.SUCCESS, "Message sent!")
           ^
SyntaxError: invalid syntax

It was there and a closing ) after ['name']