django - 如何将现有代码更改为ModelForm实例

时间:2016-09-03 22:58:55

标签: python django modelform

Django的新手,这是我的第一个Web应用程序。

我在使用django的ModelForm功能时遇到了麻烦,我想知道:

如何修改我的代码以便创建ModelForm的实例,具体来说,如何提取表单数据以上传到后端?我需要稍后引用此实例以在update_profile视图中重新填充相同的数据,但更新只能在用户登录后进行(在注册和创建配置文件之后)。

对于编辑部分,我是否使用pk=some_record.pk?很困惑,任何帮助都表示赞赏。

我使用CustomerDetail的模型有一个引用customer模型的外键字段Customer

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 str(self.customer)

以下是views.py

的摘录
def create_profile(request):
if request.POST:
    address = request.POST['address']
    date_of_birth = request.POST['date_of_birth']
    company = request.POST['company']
    home_phone = request.POST['home_phone']
    work_phone = request.POST['work_phone']

    custprofdata = CustomerDetail(address = address, date_of_birth = date_of_birth, company = company, home_phone = home_phone, work_phone = work_phone)
    custprofdata.save()

    output = {'address': address, 'dateofbirth': date_of_birth, 'company': company, 'homephone': home_phone, 'workphone': work_phone}

    return render(request, 'newuser/profile_created.html', output)
else:
    return redirect(create_profile)

以下是相应create_profile.html

的表单部分的片段
<form action = "{% url 'create_profile' %}" class="create_profile" role="form" method = "post">
    {% csrf_token %} 
    <div class="form-group">
    <label for="address" class="col-md-3 control-label">Address</label>
    <div class="col-md-9">
        <input type="text" class="form-control" name="address" placeholder="777 Park St" />
    </div>
    </div>
    <div class="form-group">
    <label for="date-of-birth" class="col-md-3 control-label">Date Of Birth</label>
    <div class="col-md-9">
        <input type="text" class="form-control" name="date_of_birth" placeholder="09/12/82" />
    </div>
    </div>
    <div class="form-group">
    <label for="company" class="col-md-3 control-label">Company</label>
    <div class="col-md-9">
        <input type="text" class="form-control" name="company" placeholder="Oracle">
    </div>
    </div>
    <div class="form-group">
    <label for="home-phone" class="col-md-3 control-label">Home Phone</label>
    <div class="col-md-9">
        <input type="text" class="form-control" name="home_phone" placeholder="4082992788">
    </div>
    </div>
    <div class="form-group">
    <label for="work-phone" class="col-md-3 control-label">Work Phone</label>
    <div class="col-md-9">
        <input type="text" class="form-control" name="work_phone" placeholder="6690039955">
    </div>
    </div>
    <div class="form-group">
    <div class="col-md-offset-3 col-md-9">
        <button type = "create" class="btn btn-success" form = "create_profile"> Submit </button>
    </div>
    </div>              
 </form>

2 个答案:

答案 0 :(得分:1)

实现基本的ModelForm只是以下问题:

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',]

https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#a-full-example

但我建议你也转而使用基于类的视图(CBV) - 使用隐式ModelForm(可以通过提供自己的ModelForm类来自定义),CreateView将使用更少的代码执行与现有视图相同的操作。如果你愿意,可以form_class = YourFormClass

https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-editing/#createview

https://ccbv.co.uk/projects/Django/1.10/django.views.generic.edit/CreateView/

答案 1 :(得分:1)

创建CustomerDetailForm后@John Carter说,您可能想将view.py更改为以下


def create_profile(request):
    if request.POST:
        form = CustomerDetailForm(request.POST)
        if form.is_valid():
            ## save data in database ##
            return render(request, 'newuser/profile_created.html', {form:form})
    else:
        return redirect(create_profile)