Reputation: 4316
Hi Stackoverflow people,
I am trying to write my own contact form in Django, where users can write messages to me and the message will be emailed and saved in the DB for tracking.
But somehow, the model.save() won't save anything. When I check the entries with Admin, the Contact table is empty. I also do not get any error messages.
The sending of the message hasn't been fully implemented yet.
To test the code, I set up some status messages in the if/else branch, but I do not get any of the statement - so the code seems to be neglected. But I do not understand why? Any suggestions?
I am not sure if I hand over the request variable between the views.py and forms.py correctly. Could this be the issue?
Thank you for your suggestions.
models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
import datetime, random
class Contact(models.Model):
"""
Contact class is the model for user messages.
Every message will be sent.
"""
CATEGORIES = (
('Suggestion', 'I have a suggestion'),
('Feedback', 'General feedback'),
('Complaint', 'You should improve ...'),
# ('', ''),
)
category = models.CharField(_('Message Category'),
max_length=10,
choices=CATEGORIES)
subject = models.CharField(_('Message Subject'),
max_length=255,)
sender = models.EmailField(_('Email Address'),)
message = models.TextField(_('Message Box'),)
# date and ansbwered are not visible to the user
timeOfMessage = models.DateTimeField(_('Time of sending'), blank=True, null=True)
answered = models.BooleanField(_('Answered?'),
default=False,)
def __unicode__(self):
return '%s' % self.sender
def send_and_save(self):
subject_new = ':'.join(self.category, self.subject)
send_mail(subject_new,
message,
sender,
'info@future_domain_address.com')
return True
forms.py
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from contact.models import Contact
import datetime
class ContactForm(ModelForm):
class Meta:
model = Contact
exclude = ('answered', 'timeOfMessage')
def save_and_email(request):
if request.method == 'POST':
form = self(request.POST)
if form.is_valid():
# contact.cleaned_data()
contact = form.save(commit=False)
contact.timeOfMessage = datetime.now()
contact.answered = False
contact.save()
print "was here"
return True
else:
print "Saving Failed"
else:
print "POST failed"
return False
views.py
from django.views.generic.simple import direct_to_template
from django.shortcuts import redirect, get_object_or_404, render_to_response
from django.utils.translation import ugettext as _
from django.http import HttpResponseForbidden, Http404, HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.core.mail import BadHeaderError
from contact.forms import ContactForm
def contact(request):
if request.method == 'POST':
try:
contactform = ContactForm()
contactform.save_and_email
except BadHeaderError:
return HttpResponse(_('Invalid header found.'))
return HttpResponseRedirect('/contact/thankyou/')
return render_to_response('contact/contact.html', {'form': ContactForm()},
RequestContext(request))
Upvotes: 1
Views: 9296
Reputation: 15003
I see two things here. On the view the method is not called. The method needs the () to be called.
Then the save_and_email method needs some corrections. First of all needs the self argument, or convert it to a . My suggestion is as follows.
def save_and_email(self):
if self.is_valid():
contact = self.save(commit=False)
contact.timeOfMessage = datetime.now()
contact.answered = False
contact.save()
return True
else:
return False
And the view:
def contact(request):
if request.method == 'POST':
contactform = ContactForm(request.POST)
if contactform.save_and_email():
return HttpResponseRedirect('/contact/thankyou/')
return render_to_response('contact/contact.html', {'form': ContactForm()},
RequestContext(request))
Upvotes: 4