我创建了一个Django应用程序。在这种情况下,当我单击index.html页面上的更新按钮时,它必须重定向到一个显示具有3个字段(标题,用户,正文)的表单的网页。每次我单击更新时,该表单都不会生效。它总是返回false。实际上,如果我们按下更新按钮,则用户字段应显示当前用户的ID。但是它显示默认值。身体字段每次都变为空。
forms.py:
class ImmediateForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly'}),initial="Immediate",max_length=20)
class Meta:
model = Immediate
fields = ['title','user','body',]
widgets = {
'user': TextInput(attrs={'readonly': 'readonly'})
}
Models.py:
class Immediate(models.Model):
title = models.CharField(default="Immediate",max_length=30)
user = models.ForeignKey(User, default=1,on_delete=models.CASCADE)
body = models.TextField(default="")
def __str__(self):
return self.title
views.py:
def update_immediate(request,pk):
if not request.user.is_authenticated:
return render(request, 'set_goals/index.html')
else:
print(pk)
try:
if request.method=='POST' :
print('Inside if')
immediate = Immediate.objects.get(user_id=pk)
form = ImmediateForm(request.POST or None, instance=immediate or None)
if form.is_valid():
print("no")
immediate = form.save(commit=False)
immediate.user = request.user.username
immediate.body = form.cleaned_data['body']
immediate.save()
return render(request, 'set_goals/detail_immediate.html', {'immediate': immediate})
context = {
"form": form,
}
return render(request, 'set_goals/create_template.html', context)
except:
if request.method=='POST' :
print('Inside if')
form = ImmediateForm(request.POST or None)
if form.is_valid():
print("yes")
immediate = form.save(commit=False)
immediate.user = request.user
immediate.body = form.cleaned_data['body']
immediate.save()
return render(request, 'set_goals/detail_immediate.html', {'immediate': immediate})
context = {
"form": form,
}
return render(request, 'set_goals/create_template.html', context)
按钮所在的html页面:
index.html:
<div class="col-md-6">
<div class="card mb-4">
<div class="card-header">
Immediate
</div>
<img class="card-img-top" style="width:495px;height:400px;" src="" alt="Card image cap">
<div class="card-body">
<h2 class="card-title">Empty for now</h2>
<p class="card-text"></p>
<form class="form-horizontal" role="form" action="" method="POST" enctype="multipart/form-data">
<a href="{% url 'set_goals:update_immediate' user.id %}" class="btn btn-primary">Update →</a>
<a href="{% url 'set_goals:detail_immediate' user.id %}" class="btn btn-primary">Read More →</a>
</form>
</div>
</div>
</div>
这是什么错误?为什么InstantForm()不起作用?该怎么做才能纠正这个问题?
答案 0 :(得分:0)
要调试此问题,可以在form.is_valid之前或之后立即使用form.errors。然后只需输出到控制台,您就会发现问题所在。