提交表單(輸入)後,它將重定向到另一個頁面(結果)並在此結果頁面中顯示錶單信息。爲什麼提交後Django表單數據無法顯示
現在的問題是提交的信息不會顯示在結果頁面中。
我懷疑原因是因爲在結果'views.py,我想顯示提交的形式從輸入,但表單的數據沒有保存或我不應該從模型中獲取數據,我應該獲取從視圖中的數據,所以它不能顯示該表:
上下文[「輸入」] = Input.objects.all()
請糾正我,如果我的猜測是正確與否。預先感謝您的建議。
輸入 - models.py
class Input(models.Model):
company=models.CharField(max_length=100,default='Empty')
region=models.CharField(max_length=100,default='Empty')
start_date=models.DateField(auto_now=False, auto_now_add=False,default='Empty')
end_date=models.DateField(auto_now=False, auto_now_add=False,default='Empty')
輸入 - 形式
class Inputform(forms.ModelForm):
company=forms.CharField()
regionlist = forms.ModelChoiceField(queryset=Result.objects.values('region').distinct())
start_date=forms.DateField(widget=DateInput(),required=True)
end_date = forms.DateField(widget=DateInput(),required=True)
class Meta:
model = Input
fields = ('company', 'region','start_date','end_date')
widgets = {
'start_date': forms.DateInput(attrs={'class':'datepicker'}),
'end_date': forms.DateInput(attrs={'class':'datepicker'}),
}
輸入 - 的HTML代碼的一部分
<form action="result_list/" method="post">{% csrf_token %}
<!--enter company-->
<div class="field">
<p>Company:<input type="text" name="Company" value="{{company}}"/>
</div>
<!--select region-->
<div class="field" >
<label> Select the Region:
{{ form.regionlist }}
{% for region in form.regionlist.choices %}
<option value="{{ val }}" {% ifequal data.val val %}selected {% endifequal %}></option>
{% endfor %}
</label>
</div>
....
<div class="fieldWrapper">
<p><input type="submit" value="Submit" /></p></div>
</form>
輸入--views
from django.http import HttpResponseRedirect
from django.shortcuts import render,render_to_response,get_object_or_404
from inputform.forms import Inputform
from inputform.models import Input
from result.models import Result
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.list import ListView
@csrf_exempt
def input(request):
if request.method == 'POST':
form = Inputform(request.POST)
if form.is_valid():
cd = form.cleaned_data
print (cd['company'])
form.save()
return redirect('result')
網址
from inputform import views
from django.views.generic.list import ListView
from inputform.views import input
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^result_list/$',ResultView.as_view(),name='result'),
(r'^input/$', RedirectView.as_view(url='/result_list/')),
}
結果--views.py
class ResultView(ListView):
context_object_name = 'result_list'
template_name = 'result_list.html'
queryset = Result.objects.all()
def get_context_data(self, **kwargs):
context = super(ResultView, self).get_context_data(**kwargs)
context['input'] = Input.objects.all()
return context
結果 - HTML
{% for input_object in input %}
<table border="1" cellpadding="1">
<tr>
<td align="left">Company</td>
<td>{{input_object.company}}</td>
</tr>
<tr>
<td align="left">Region</td>
<td>{{input_object.region}}</td>
</tr>
...
</table>
{% endfor %}
html代碼只是片段,我已將所有字段傳遞給模板。所以我認爲還有其他一些原因。 –