【发布时间】:2016-09-04 19:53:42
【问题描述】:
以下是我正在使用的模型:
class Customer(models.Model):
customer_id = models.AutoField(primary_key=True, unique=True)
full_name = models.CharField(max_length=50)
user_email = models.EmailField(max_length=50)
user_pass = models.CharField(max_length=30)
def __str__(self):
return "%s" % self.full_name
class CustomerDetail(models.Model):
phone_regex = RegexValidator(regex = r'^\d{10}$', message = "Invalid format! E.g. 4088385778")
date_regex = RegexValidator(regex = r'^(\d{2})[/.-](\d{2})[/.-](\d{2})$', message = "Invalid format! E.g. 05/16/91")
customer = models.OneToOneField(
Customer,
on_delete=models.CASCADE,
primary_key=True,
)
address = models.CharField(max_length=100)
date_of_birth = models.CharField(validators = [date_regex], max_length = 10, blank = True)
company = models.CharField(max_length=30)
home_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
work_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
def __str__(self):
return "%s" % self.customer.full_name
这里是forms.py:
from django.forms import ModelForm
from .models import CustomerDetail
class CustomerDetailForm(ModelForm):
class Meta:
model = CustomerDetail
fields = ['address', 'date_of_birth', 'company', 'home_phone', 'work_phone',]
我的应用程序中有一个视图(用户登录后),名为create_profile,它要求用户提供更多详细信息,我使用 ModelForm 实例来实现它。这是来自views.py的sn-p:
def create_profile(request):
if request.POST:
form = CustomerDetailForm(request.POST)
if form.is_valid():
address = form.cleaned_data['address']
date_of_birth = form.cleaned_data['date_of_birth']
company = form.cleaned_data['company']
home_phone = form.cleaned_data['home_phone']
work_phone = form.cleaned_data['work_phone']
profdata = CustomerDetail(address = address, date_of_birth = date_of_birth, company = company, home_phone = home_phone, work_phone = work_phone)
profdata.save()
return render(request, 'newuser/profile_created.html', {form: form})
else:
return redirect(create_profile)
当我在相应的模板 html 上填写表格并点击提交时,它会显示后续页面,但是当我检查管理页面上的 CustomerDetail 条目时,我看到一个“-”代替了实际记录。我在哪里错了?它与覆盖 clean() 方法有关吗?请帮忙。谢谢!
【问题讨论】:
标签: python django django-forms modelform