2015-10-07 228 views
0

我有2類從我的模型Django模型:自動保存

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_status」每當「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」不能爲空「)

對不起如果這是一個新手問題

回答

0

使用django信號來實現這一點。 https://docs.djangoproject.com/en/1.8/topics/signals/

或者您也可以手動保存Applicant_Status,並將fk設置爲您剛纔在視圖中收到的Application_Data。

+0

你可以添加一個簡短的例子作爲參考?我是一個初學者,我不知道謝謝 –

+0

http://stackoverflow.com/questions/10810202/django-post-save-call-from-within-sending-model。您可以使用Applicant_Status保存功能替換create_badge功能。 –

+0

所以..手動保存我只需要使用 'cde = form.save(commit = False)' 'Applicant_status.objects.create(fk = cde.id)' 我收到一個錯誤雖然 –