代码之家  ›  专栏  ›  技术社区  ›  peter

Django表单在尝试从数据库更新现有行时未验证

  •  1
  • peter  · 技术社区  · 7 年前

    我正在做我的第一个Django项目。 但我发现以下错误:

    编辑\u文件模板

                    <form method="POST" action="{% url 'edit_file' file.id %}">
                    {% csrf_token %}
    
                    {{ form.errors }}
                    {{ form.non_field_errors }}
    
                    {% for hidden_field in form.hidden_fields %}
                        {{ hidden_field.errors }}
                        {{ hidden_field }}
                    {% endfor %}
    
                    <div class="form-group row">
                        <label for="id_name" class="col-sm-3 col-form-label"> File Name </label>
                        <div class="col-sm-4">
                            {% render_field form.name|add_class:"form-control" %}
                        </div>
                    </div>
    
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label">File Path</label>
                        <div class="col-sm-4">
                            {% render_field form.directory_path|add_class:"form-control" %}
                        </div>
                    </div>
    
                    <div class="form-group">
                        {% render_field form.script_code|add_class:"form-control" %}
                        <pre id="id_script_code" style="height: 40pc;">{{ form.script_code }}</pre>
                    </div>
    
                    <button type="submit" class="btn btn-success mr-2">Save Changes</button>
                    <a href="{% url 'list_files_from_version' file.version_id %}" class="btn btn-light">Back</a>
    
                </form>
    

    视图。py公司

    def edit_file(request, id):
        instance = get_object_or_404(File, id=id)
        if request.method == "POST":
            form = EditFileForm(request.POST, instance=instance)  
            if form.is_valid():
                print('Form validation => True')
                form.save()
                return HttpResponse('<h1> database updated! </h1>')
            else:
                print('Form validation => False')
            file = File.objects.latest('id')
            context = {'file': file, "form": form}
            return render(request, 'edit_file.html', context)
        else:
            instance = get_object_or_404(File, id=id)
            form = EditFileForm(request.POST or None, instance=instance)
            file = File.objects.latest('id')
            context = {'file': file, "form": form}
            return render(request, 'edit_file.html', context)
    

    表格。py公司

    class EditFileForm(ModelForm):
        # field_order = ['field_1', 'field_2']
    
        class Meta:
            print("forms.py 1")
            model = File
            fields = ('name', 'script_code', 'directory_path','version')
    
        def clean(self):
            print("forms.py 2")
            cleaned_data = super(EditFileForm, self).clean()
            name = cleaned_data.get('name')
            print("cleaned data: ", cleaned_data)
    

    型号:

    版本id指向包含多个文件的版本。

      class File(models.Model):
        # Incrementing ID (created automatically)
        name = models.CharField(max_length=40)
        script_code = models.TextField()  # max juiste manier?
        directory_path = models.CharField(max_length=200)
        version = models.ForeignKey('Version', on_delete=models.CASCADE)
    
        class Meta(object):
            db_table = 'file'  # table name
    
    
    class Version(models.Model):
        # Incrementing ID (created automatically)
        version_number = models.CharField(max_length=20)
        pending_update = models.BooleanField(default=False)
        creation_date = models.DateTimeField(auto_now_add=True, null=True, editable=False)
        modification_date = models.DateTimeField(auto_now_add=True, null=True)
        connecthor = models.ForeignKey('ConnecThor', on_delete=models.CASCADE)
    
        def __str__(self):
            return self.connecthor_id
    

    问题是:

    类型is\u valid()不断失败。我的视图返回一个错误。 *版本:此字段为必填字段。 但我不知道怎么解决这个问题。用户应该只能更新5个数据字段中的3个。因此,没有理由在模板中显示PK或FK。

    2 回复  |  直到 7 年前
        1
  •  3
  •   Daniel Roseman    7 年前

    您已经在表单的字段列表中包含了版本,但您没有在模板中输出它,因此无法提供它。由于模型字段未指定blank=True,因此它是必填字段,因此会出现错误。

    如果您不希望用户能够修改此字段,则应将其从Meta下的字段列表中删除。

        2
  •  0
  •   Vishnu Kiran    7 年前

    模板中没有版本。版本的模型字段没有说明它可以有空值。因此,表单验证失败。将其包含在模板中,或从表单中EditFileForm类的元类中删除该字段。py公司