【问题标题】:mutiple time data saving problem in django sqllite3django sqlite3中的多次数据保存问题
【发布时间】:2021-08-04 08:24:55
【问题描述】:

我将 django 与 sqllite 一起使用,我在 django 模型和 django 表单的帮助下创建了一个调查表,但是当我点击提交时,我看到有时数据在我的数据库中保存了两次,这是正常发生还是我的代码有问题

from django.shortcuts import render, redirect
from django.contrib import messages
from django.template.response import TemplateResponse
from .forms import SurveyForm


def index(request):
    if request.method == 'POST':
        form = SurveyForm(request.POST)
        if form.is_valid():
            form.save()
            return TemplateResponse(request, 'thankyou.html')
        else:
            return messages.error(request, 'Please fill the form to continue')
    else:
        form = SurveyForm()
        return render(request, 'learnersform.html', {'form': form})

我的表单.py

from django import forms
from django.forms import ModelForm, Textarea
from .models import teacher

class teachersform(forms.ModelForm):
    class Meta:
        model = teacher
        fields = '__all__'
        widgets = {'name': forms.TextInput(attrs={'placeholder':'Your Name'}),
                    'Q3': forms.TextInput(attrs={'placeholder':'Please write your subjects'}),
                    'Q4': forms.RadioSelect(),
                    'Q5': forms.RadioSelect(),
                    'Q6': forms.RadioSelect(),
                    'Q7': forms.RadioSelect(),
                    'Q8': forms.RadioSelect(),
                    'Q9':forms.Textarea(attrs={'placeholder':'Write Here.......'}),
                    'Q10':forms.Textarea(attrs={'placeholder':'Write Here.......'}),
                   }

我的模型.py

from django.db import models

# Create your models here.
class teacher(models.Model):
    name = models.CharField(max_length=80, blank=True,)
    state = models.CharField(max_length=50, choices=state_choice,)
    Q3 = models.CharField(max_length=80, default=None, blank=False)
    Q4 = models.CharField(max_length=80, choices=q4_choice, default=None, blank=False)
    Q5 = models.CharField(max_length=80, choices=q5_choice, default=None, blank=False)
    Q6 = models.CharField(max_length=80, choices=q6_choice, default=None, blank=False)
    Q7 = models.CharField(max_length=80, choices=q7_choice, default=None, blank=False)
    Q8 = models.CharField(max_length=80, choices=q8_choice, default=None, blank=False)
    Q9 = models.TextField(default=None, blank=False)
    Q10 = models.TextField(default=None,blank=False)


    def __str__(self):
        return self.state

【问题讨论】:

  • 您的视图看起来不错,您可以添加您的SurveyForm 类以及相应的模型吗?
  • 请出示相关表格和型号
  • 添加表格和模型
  • 您没有添加正确的表格或模型

标签: django sqlite django-models django-views django-forms


【解决方案1】:

您的问题与 sqlite 无关,而是与 views.py 中的代码有关。保存表单后刷新页面时,会重新提交相同的表单数据;并且多次保存相同的数据。

建议表单数据保存成功后,使用返回HttpResponseRedirectredirect,而不是使用HttpRequest进行渲染。

我将代码重写为

def index(request):
    if request.method == 'POST':
        form = SurveyForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('thankyou/')
            #return TemplateResponse(request, 'thankyou.html')
        else:
            return messages.error(request, 'Please fill the form to continue')
    else:
        form = SurveyForm()
        return render(request, 'learnersform.html', {'form': form})

添加路由到 urls.py 之类的

path( 'thankyou/', views.thankyou, name='thankyou')

在views.py中包含另一个函数thankyou

def thankyou(request):
  return render(request, 'thankyou.html') 

更新:

如果您不想使用 urls.py 路由和额外的视图功能,则可以将路径 thankyou.html 传递给 HttpResponseRedirect 构造函数。在这种情况下,不需要在 urls.py 中创建路由或额外的视图函数。

return HttpResponseRedirect('thankyou.html')

【讨论】:

  • 但是它在网站上创建了一个额外的链接,但我不希望thankyou.html页面有它自己的路径
  • 当然。 HttpResponseRedirect 构造函数的第一个参数可以是 URL、相对路径或绝对路径。您可以简单地将 HttpResponseRedirect 语句替换为 return HttpResponseRedirect('thankyou.html') 在这种情况下,您既不需要 url 路由也不需要视图函数。
【解决方案2】:

我个人建议您在保存之前从表单中提取数据,然后您可以对数据进行操作,或者也可以保存在其他位置:

首先,您将知道数据将如何通过表单中给出的名称发送,因此您可以构建一个值字典...

您需要构建“form_data”部分以获得与您的表单相关的完整字典。

form_data = {
            "name": request.POST['name'],
            "Q3": request.POST['Q3']
my_form = SurveyForm(form_data)

if my_form.is_valid():
    new_form = my_form.save(commit=False)
    """
    Now you can access any data using the dict method - new_form.name, new_form.Q3 
    etc. Even if you don't initially use it, you can leave this section blank but use 
    it in the future at some stage...
    new_form.name for example will be the users name entered on the form.
    new_form.Q3 will be the answer to question 3. 
    Although this may be a longer way of doing things, it will allow you to gather the 
    form data, before saving it. You can also build in additional security features 
    prior to database submission.
    """

    if new_form.Q3 == "Some Specific Answer":
         # Add all users to list who answer Q3 in a certain way
         some_list.extend(new_form.name)  

    # Now your done manipulating data, or pushing it to be saved in other places, you can save the form to your database.
    new_form.save()
else:
    # Form was not valid
    messages.error(request, 'Please fill the form to continue')

不确定您的项目的范围是什么,但上述方式可以让您轻松地在未来扩展其代码,因为您可以操作该数据,例如您可以根据问题结果等将用户名推送到不同的集合中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 2017-10-24
    相关资源
    最近更新 更多