我有一个功能,可以为模型添加问题和答案。当我提交表单有效时,保存它将其重定向到另一个将显示问题和答案的视图。问题到了,当我重新加载该页面时,另一个对象将再次创建并显示?怎么可能?
views.py用于添加问题和答案
if request.method == 'POST':
form = FaqForm(request.POST)
faq_formset = FaqFormset(request.POST ,prefix='faq_formset')
if form.is_valid() and faq_formset.is_valid():
for ch in faq_formset:
course = ch.cleaned_data.get('course')
ques = ch.cleaned_data.get('ques')
ans = ch.cleaned_data.get('ans')
Faq(
course=course,
ques=ques,
ans=ans,
).save()
return faq(request)
用于显示它:
def faq(request):
faq = Faq.objects.all()
lms_faculty = request.session['lms_faculty']
context = {
'dash_title' : 'View FAQ',
'heading' : 'FAQ',
'lms_faculty' : lms_faculty,
'faq' : faq,
}
return render(request, 'lmsadmin/view_faq.html', context)
views.py我最初尝试过的
if request.method == 'POST':
form = FaqForm(request.POST)
faq_formset = FaqFormset(request.POST ,prefix='faq_formset')
if form.is_valid() and faq_formset.is_valid():
for ch in faq_formset:
course = ch.cleaned_data.get('course')
ques = ch.cleaned_data.get('ques')
ans = ch.cleaned_data.get('ans')
Faq(
course=course,
ques=ques,
ans=ans,
).save()
faq = Faq.objects.all()
lms_faculty = request.session['lms_faculty']
context = {
'dash_title' : 'View FAQ',
'heading' : 'FAQ',
'lms_faculty' : lms_faculty,
'faq' : faq,
}
return render(request, 'lmsadmin/view_faq.html', context)
在重新加载网页时,我不想创建现有对象的重复对象。请帮帮我,我也在其他地方使用过这种类型。请指正。
要重定向你应该
from django.http import HttpResponseRedirect
...
return HttpResponseRedirect(request.path)