编程语言
首页 > 编程语言> > python-ModelForm的Django编辑模板未填充值

python-ModelForm的Django编辑模板未填充值

作者:互联网

我有一个ModelForm,我已经创建了一个视图和模板,用于将实例添加到数据库.我现在尝试将其扩展为在用户单击按钮时可编辑-但是当他们这样做时,将显示表单/模板页面,并且我收到“此字段为必填消息”,但所有字段均为空,而不是预先填充我传入的实例,但是当我将值编辑为不同于原始实例的值时,则在数据库中更新了正确的实例.因此它正在传递主键,但是没有显示任何值.如果有人能告诉我我在做错什么,我将不胜感激,哦,我以这篇帖子Django edit form based on add form?为基础,所以请不要仅仅将我发送到那里.

这是我的档案

型号表格

class CreditCardForm(forms.ModelForm):
class Meta:
    model = CreditCard
    fields = ('name_on_card','card_number','contact_number_on_card')

视图

def edit(request, id=None, template_name='article_edit_template.html'):
if id:
    print "Edit Mode"
    card = get_object_or_404(CreditCard, pk=id)
    if card.card_owner != request.user:
        raise HttpResponseForbidden()
else:
    print "Create Mode"
    card = CreditCard(card_owner=request.user)

if request.POST:
    print "request.POST"
    form = CreditCardForm(request.POST, instance=card)
    if form.is_valid():
        print "is_valid()"
        form.save()

        # If the save was successful, redirect to another page
        # redirect_url = reverse(article_save_success)
        return HttpResponseRedirect('/cards/')
else:
    print "else"
    form = CreditCardForm(instance=card)

return render_to_response(
    'create_credit.html', 
    {'form': form,},
    context_instance=RequestContext(request)
)

模板

{% include "base.html" %}

<form action="" method="post">{% csrf_token %}
<fieldset>
<legend>Required</legend>

<div class="fieldWrapper">
    {{ form.name_on_card.errors }}
    <label for="id_topic">Name as it appears on card:</label>
    {{ form.name_on_card }}
</div>
<div class="fieldWrapper">
    {{ form.card_number.errors }}
    <label for="id_topic">Last 6 digits of card number:</label>
    {{ form.card_number }}
</div>  
</fieldset>

<fieldset>
<legend>Optional</legend>
<!-- This is for Credit Card's Only -->
<div class="fieldWrapper">
    {{ form.contact_number_on_card.errors }}
    <label for="id_topic">Institution contact number: 1-</label>
    {{ form.contact_number_on_card }}
</div>
</fieldset>
<p><input type="submit" value="Save"></p>
</form>

网址

    url(r'^new/credit/$', views.edit, {}, 'crds_newCredit'),
url(r'^edit/credit/(?P<id>\d+)/$', views.edit, {}, 'crds_editCredit'),

解决方法:

@xizor使用链接而不是按钮来重定向到版本表单,因为该按钮可能是您向视图发送帖子的原因.

PS:请原谅我的英语,如果您认为使它更有用的话,请编辑此答案.

标签:modelform,django-forms,python,django
来源: https://codeday.me/bug/20191202/2085933.html