django - 无法在django管理页面上查看数据

时间:2016-09-04 19:53:42

标签: python django django-forms modelform

以下是我正在使用的模型:

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

的摘录
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()方法有关?请帮忙。谢谢!

1 个答案:

答案 0 :(得分:0)

在您的情况下,您不需要覆盖cleaned_data。因为您已经使用ModelFormCustomerDetail方法之后创建了save个实例 视图可能如下所示:

def create_profile(request):
    if request.method == 'POST':
        form = CustomerDetailForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'newuser/profile_created.html', {'form': form})
    else:
        form = CustomerDetailForm()
    return render(request, 'path_to_create_profile.html', {'form': form})

check the docs about forms