Django模型:自动保存

时间:2015-10-07 11:12:06

标签: django python-2.7 django-models

我的模特有2个课

class APPLICANT_DATA(models.Model): 
    FIRST_NAME= models.CharField(max_length=20)
    LAST_NAME= models.CharField(max_length=20)
    MIDDLE_NAME= models.CharField(max_length=20)

class Applicant_status(models.Model):
    fkey = models.ForeignKey(APPLICANT_DATA)
    COMMENTS = models.CharField(max_length=100, null=True)
    date_of_app = models.DateTimeField(auto_now_add=True, blank=True)

如何制作我的“申请人”状态'每当“APPLICANT_DATA”中的数据填充时插入?

这是我的views.py

def save_page(request):
form = application_form(request.POST)
if request.method == 'POST':

    if form.is_valid():  

            emails = form.cleaned_data['EMAIL']
            mail = EmailMessage("Your activation and application code is: asdasd, do not show this to anyone", to=[emails])

            mail.send()
            cde = form.save(commit=False)
            applicant_status.objects.create(fk=cde.id)
            cde.save()



            return HttpResponseRedirect('verify')

else:
    form = application_form()

return render(request, 'frontend/apply.html', {'form': form})`

编辑:我的forms.py

from django.forms import ModelForm
from django import forms
from .models import APPLICANT_DATA
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

class application_form(ModelForm):

FIRST_NAME = forms.CharField( max_length=20, label = ("First Name"),
. . .
class Meta:
    model = APPLICANT_DATA
    fields = ('FIRST_NAME', 'LAST_NAME', 'MIDDLE_NAME', )

错误是(1048,"列' fkey'不能为空")

对不起,如果这是一个新手问题

1 个答案:

答案 0 :(得分:0)

使用django信号来实现这一目标。 https://docs.djangoproject.com/en/1.8/topics/signals/

或者您可以手动保存Applicant_Status,并将fk设置为您在视图中收到的Application_Data。