如何从联系表单到Django SQLITe DB正确实现save()输入数据方法?

时间:2017-10-08 18:53:43

标签: python django sqlite

从联系表单输入中获取数据时,如何正确实现对Django SQLITe DB方法的save()?最后一个方法尝试保存输入,但它不起作用。我使用了Django联系表格发送电子邮件的教程代码。需要添加保存到数据库功能。

视图

from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
from .models import SendEmail

def email(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']

            try:
                send_mail(
                    subject, message, from_email,
                    ['bioinformatics_bel@yahoo.com']
                )
                return redirect('success')
            except BadHeaderError:
                return HttpResponse('Invalid header found.')

            return render(request, "email.html", {'form': form})

def success(request):
    return HttpResponse('All right! Thank you for your message.')

def savedata(request):  # want to save data input into the SQLIte  database!! here is something wrong
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            message_object = SendEmail(
                from_email=from_email, subject=subject, message=message)

            message_object.save()

            return HttpResponseRedirect('success')  # else: form = ContactForm() # unbound form
    return render(request, "email.html", {'form': form})

模板

<h1>Submit identifier for the  data processing</h1>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <div class="form-actions">
    <button type="submit">Send</button>
  </div>
</form>

形式

from django import forms

class ContactForm(forms.Form):
    from_email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea, required=True)

模型

from django.db import models

class SendEmail(models.Model):
    from_email = models.EmailField()
    subject = models.TextField()
    mesage = models.TextField()

1 个答案:

答案 0 :(得分:0)

如果您更喜欢使用简单的Form,那么您的方法也不错。如果您希望将保存逻辑从views.py迁移到forms.py/models.py,则应使用ModelForm,而@ hansTheFranz发表评论时可以使用.save() method你实例化的表格。