Skip to main content
 首页 » 编程设计

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

2024年10月17日34itcoder

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

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

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

对于编辑部分,我是否使用 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> 

请您参考如下方法:

实现一个基本的 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

但我建议您也切换到使用基于类的 View (CBV) - CreateView 将使用更少的代码执行与现有 View 相同的操作,并带有隐式 ModelForm(您可以通过提供自己的 ModelForm 类来自定义它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/