【问题标题】:django - How to change existing code to ModelForm instancedjango - 如何将现有代码更改为 ModelForm 实例
【发布时间】:2016-09-03 22:58:55
【问题描述】:

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的sn-p:

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的表单部分的sn-p:

<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>

【问题讨论】:

    标签: python django modelform


    【解决方案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) - CreateView 将与您现有的视图一样使用更少的代码,使用隐式 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/

    【讨论】:

      【解决方案2】:

      按照@John Carter 所说创建 CustomerDetailForm 后,您可能希望将 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)
      

      【讨论】:

      • 保存数据我应该把form.save()?
      • 是,但不在表格上。它应该与您的旧 view.py 相同
      猜你喜欢
      • 2015-04-24
      • 1970-01-01
      • 2012-03-31
      • 2013-08-28
      • 1970-01-01
      • 2023-03-03
      • 2014-12-01
      • 2010-12-14
      • 1970-01-01
      相关资源
      最近更新 更多