【问题标题】:Modelforms : not able to view the editable content while updatingModelforms:更新时无法查看可编辑内容
【发布时间】:2018-07-19 15:13:51
【问题描述】:

可能是一个新手问题,所以请多多包涵。

我有一个编辑模型的某个实例的 Django 表单。我正在使用模型表单。我可以编辑实例,但看不到要编辑的实例内容。

我现在正在使用视频教程学习 django,并在教程中将 instance=instance 添加到 ModelForm 实例,然后使用 form.as_p 将值填充到输入框中。

在我要编辑 url 的情况下,我的输入字段是空白的。但是,我以新的空白形式写的任何内容都会更新为该对象。这里可能出了什么问题?我在这一点上被困了 4 天,所以这个问题非常绝望 :)

我的表单类:

from django import forms
from .models import Entry
class EntryForm(forms.ModelForm):
    class Meta:
        model = Entry
        fields = ['name','type', 'date', 'description']

我的模特:

from django.db import models

class Entry(models.Model):
    name = models.CharField(max_length=200)
    type = models.CharField(max_length= 200)
    date = models.DateTimeField()
    description = models.TextField()

我的观点是这样的:

def update(request,pk):
    instance = get_object_or_404(Entry,pk=pk)
    if request.method == 'POST':
        form = EntryForm(request.POST or None,instance=instance )
        if form.is_valid():
            instance =form.save(commit=False)
            instance.save()
            return HttpResponseRedirect('/')      
    else:
        form = EntryForm()

    return render(request, "form.html", {"name":instance.name,'instance':instance,'form': form})

表单模板:

<form method="POST">
    {% csrf_token %}
    {{form.as_p}}

        <button class="btn btn-success" type='submit'>Submit</button>   
    </form>

【问题讨论】:

    标签: django django-models django-forms django-views


    【解决方案1】:

    您没有传递第二种情况的实例。将您的 views.py 更新为此。

    def update(request,pk):
        instance = get_object_or_404(Entry,pk=pk)
        if request.method == 'POST':
            form = EntryForm(request.POST or None,instance=instance )
            if form.is_valid():
                instance =form.save(commit=False)
                instance.save()
                return HttpResponseRedirect('/')
        else:
            form = EntryForm(instance=instance)
    
        return render(request, "form.html", {"name":instance.name,'instance':instance,'form': form})
    

    【讨论】:

    • 这太尴尬了 :) 哈哈。非常感谢
    猜你喜欢
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多