Django:model.save()未保存,但没有错误消息
大家好 Stackoverflow,
我正在尝试在 Django 中编写自己的联系表单,用户可以在其中向我写消息,该消息将通过电子邮件发送并保存在数据库中以供跟踪。
但不知何故, model.save() 不会保存任何内容。当我与管理员检查条目时,联系人表为空。我也没有收到任何错误消息。
消息的发送尚未完全实现。
为了测试代码,我在 if/else 分支中设置了一些状态消息,但我没有收到任何语句 - 因此代码似乎被忽略了。但我不明白为什么?有什么建议吗?
我不确定是否正确地在views.py和forms.py之间传递request变量。这可能是问题所在吗?
感谢您的建议。
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))
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))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在这里看到两件事。在视图上该方法未被调用。该方法需要调用 ()。
然后 save_and_email 方法需要一些更正。首先需要 self 参数,或者将其转换为 .
我的建议如下。
和观点:
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.
And the view: