如何在Django中使用存储在数据库中的值自动填充表单模板?

时间:2014-10-31 11:10:17

标签: python django django-forms

我想用edit_post.html填充已经存储在数据库中的值。 我的修改网址为http://hostname/edit_Post/960。 " 960"对应于我的数据库中的项ID。我请求使用该ID更新其内容。

我想把内容显示在这里: -

edit_Post.html

<form id="category_form" method="post" action="/edit_Post/">

    {% csrf_token %}

    {% for field in form.visible_fields %}            
        {{ field.errors }}
        <input type="text" placeholder='{{ field.help_text }}'>
    {% endfor %}

    <input type="submit" name="submit" value="Create Post" />
</form>

urls.py

url(r'^edit_Post/(?P<id>\d+)', 'blog.views.edit_Post'),

forms.py

class addPostForm(forms.ModelForm):
    title = forms.CharField(max_length=128, help_text="Please enter the title ")
    author = forms.CharField(max_length=128, help_text="Please enter the Author ")
    bodytext = forms.CharField(max_length=128,
                               help_text="Please enter the Body",
                               required=False)

    # An inline class to provide additional information on the form.
    class Meta:
        # Provide an association between the ModelForm and a model
        model=posts
        fields = ('title', 'author','bodytext')

最后 views.py

def edit_Post(request, id):
    context = RequestContext(request)
    instance=posts.objects.get(id=id)
    form = addPostForm(instance=instance)
    if request.method == "POST":
        form = addPostForm(request.POST,instance=instance)
        if form.is_valid():
            form.save(commit=True)
            confirmation_message = "Post information updated successfully!"
            return HttpResponseRedirect('/home')
        else:
            print form.errors
    else:
        form=addPostForm(instance=instance)
    return render_to_response('edit_Post.html', {'form': form}, context)

我的 model.py

class posts(models.Model):
    author = models.CharField(max_length = 30)
    title = models.CharField(max_length = 100)
    bodytext = models.TextField()
    timestamp = models.DateTimeField(default=datetime.now, blank=True)

2 个答案:

答案 0 :(得分:1)

如果你没有绕过输出字段的机制,那么Django就已经这样做了。在您的模板中,您应该这样做:

{% for field in form.visible_fields %}
    {{ field.errors }}
    {{ field }}
{% endfor %}

如果要保留占位符功能,请在表单类本身中添加:

class addPostForm(forms.ModelForm):
    title = forms.CharField(max_length=128, widget=forms.TextInput(attrs={'placeholder': 'Please enter the title'}))

答案 1 :(得分:0)

Django提供 CRUD (创建 - &gt; CreateView,删除 - &gt;删除视图,更新 - &gt; UpdateView,详细信息 - &gt; DetailView)视图。如果可以,请使用它们。
您可以在类中的views.py中更改方法。

class PostDetail(DetailView):
    model = posts
    form_class = addPostForm
    template = "edit_post.html"

然后你可以在那里添加方法:)。