有没有什么方法可以避免在Django中刷新页面时创建新对象?

时间:2019-04-20 11:41:04

标签: django

我有一个功能,可以向模型添加问题和答案。当我提交表单是否有效时,将其保存,将其重定向到另一个视图,该视图将显示问题和答案。问题是当我重新加载该页面时,另一个对象会再次创建并显示吗?那怎么可能?

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)

在重新加载网页时,我不想创建现有对象的重复对象。请帮助我,我在其他领域也使用过这种类型。请纠正我。

1 个答案:

答案 0 :(得分:0)

要重定向,您应该

from django.http import HttpResponseRedirect
...
return HttpResponseRedirect(request.path)