我有一个模型,我正在使用vanilla视图来创建Create,Update,Detail和Delete视图。
class Person( models.Model ):
username = models.CharField( max_length=30, unique=True )
first_name = models.CharField( max_length=30 )
middle_initial = models.CharField( max_length=3, null=True, blank=True )
last_name = models.CharField( max_length=30 )
last_four_ssn = models.CharField( max_length="5" )
ssn = models.CharField( max_length="13", verbose_name='SSN', blank=False )
我想要做的是创建一个没有'last_four_ssn'的表单,然后在提交(并验证)表单时,我想将last_four_ssn设置为ssn中的最后四个数字。
class PersonCreate(PersonCRUDView, CreateView):
fields = ['username', 'first_name', 'middle_initial', 'last_name',
'ssn', 'email', 'years_of_service', 'birth_date',
'address', 'city', 'state', 'zip_code']
def form_valid(self, form):
form.cleaned_data['ssn_last_four'] = form.cleaned_data['ssn'][-4:]
return super(PersonCreate, self).form_valid(form)
但它似乎没有起作用。
如何保存ssn_last_four?
答案 0 :(得分:0)
我通常使用post方法,如下所示:
forms.py
from .models import Person
PersonForm(forms.ModelForm):
model = Person
fields = ['username', 'first_name', 'middle_initial', 'last_name',
'ssn', 'email', 'years_of_service', 'birth_date',
'address', 'city', 'state', 'zip_code']
视图 来自django.http import HttpResponse
from .forms import PersonForm
class PersonCreate(PersonCRUDView, CreateView):
form_class = PersonForm
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
submited_form = form.save(commit=False)
submited_form.ssn_last_four = form.cleaned_data['ssn'][-4:]
submited_form.save()
# return an HTTPResponse here, example:
return HttpResponse("Saved!")
如果您想使用form_valid方法:
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.ssn_last_four = form.cleaned_data['ssn'][-4:]
self.object.save()
return super(ModelFormMixin, self).form_valid(form)