首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Django不保护BooleanFields的值

Django不保护BooleanFields的值
EN

Stack Overflow用户
提问于 2020-04-15 04:46:19
回答 1查看 38关注 0票数 0

我有以下几个布尔型字段的表单:

代码语言:javascript
运行
复制
class RegistrationForm(UserCreationForm):

    guardianSource = forms.BooleanField(widget=forms.CheckboxInput(attrs={'id':'guardianSource'}),required=False)
    bbcSource = forms.BooleanField(required=False)
    independentSource = forms.BooleanField(required=False)

    categoryCoronaVirus = forms.BooleanField(required=False)
    categoryPolitics = forms.BooleanField(required=False)
    categorySport = forms.BooleanField(required=False)

    #Telling the registration form what kind of data we are going to be modelling/ what the form needs to look like
    class Meta:
        model = Account
        fields = ("username", "password1", "password2", "guardianSource", "bbcSource", "independentSource", "categoryCoronaVirus", "categoryPolitics", "categorySport")

寄存器模板如下所示:

代码语言:javascript
运行
复制
<form class="form-signin" method="POST">{% csrf_token %}

  <h1 class="h3 mb-3 font-weight-normal">Register</h1>



  <label for="username" class="sr-only">Username</label>
  <input type="text" name="username" id="username" class="form-control" placeholder="User name" required autofocus>

  <label for="inputPassword1" class="sr-only">Password</label>
  <input type="password" name="password1" id="inputPassword1" class="form-control" placeholder="Password" required>

  <label for="inputPassword2" class="sr-only">Password</label>
  <input type="password" name="password2" id="inputPassword2" class="form-control" placeholder="Confirm Password" required>
    <br>
  <div  class="form-control">
    <p><b>Please choose news sources!</b></p>

    <label for="guardianSource" >The Guardian</label>
    <input type="checkbox" name="source" id="guardianSource">
    <br>
    <label for="bbcSource" >BBC News</label>
    <input type="checkbox" name="source" id="bbcSource">
    <br>
    <label for="independentSource" >The Independent</label>
    <input type="checkbox" name="source" id="independentSource">
   </div>
   <br>
   <div  class="form-control">
    <p><b>Please choose news category!</b></p>

    <label for="categoryCoronaVirus" >Corona Virus</label>
    <input type="checkbox" name="category" id="categoryCoronaVirus">
    <br>
    <label for="categoryPolitics" >Politics</label>
    <input type="checkbox" name="category" id="categoryPolitics">
    <br>
    <label for="categorySport" >Sport</label>
    <input type="checkbox" name="category" id="categorySport">
   </div>

    {% for field in registration_form %}
        <p>
            {% for error in field.errors %}
                <p class="alert alert-danger card-header text-center flashit"> {{ error }}</p>
            {% endfor %}
        </p>
    {% endfor %}
    {% if registration_form.non_field_errors %}
        <div style="color:red;">
                <p>{{registration_form.non_field_errors}}</p>
        </div>
    {% endif %}
  <h6 class="text-muted">
     NOTE: You <b>MUST</b> select at least 1 choice for each!!!
  </h6>
    <div  id="error_message"> </div>

  <button class="btn btn-lg btn-primary btn-block" type="submit" onclick="valthisform()">Register</button>

</form>

在提交表单之前,有一个JavaScript函数可以检查是否至少选择了一个类别复选框和一个来源复选框:

代码语言:javascript
运行
复制
function valthisform(){

                var guardianSource = document.getElementById("guardianSource").checked;
                var bbcSource = document.getElementById("bbcSource").checked;
                var independentSource = document.getElementById("independentSource").checked;
                var checkedSource = false;

                var categoryCoronaVirus = document.getElementById("categoryCoronaVirus").checked;
                var categoryPolitics = document.getElementById("categoryPolitics").checked;
                var categorySport = document.getElementById("categorySport").checked;
                var checkedCategory = false;



                if(guardianSource ===true || bbcSource===true || independentSource===true){
                    checkedSource = true;
                }
                if(categoryCoronaVirus===true || categoryPolitics===true || categorySport===true){
                    checkedCategory = true;
                }

                if(checkedSource ===false && checkedCategory===false){
                    document.getElementById('error_message').innerHTML = '<div class="alert alert-danger card-header text-center flashit"><strong>Warning!</strong> No source and category selected!</div>';
                    event.preventDefault();
                }
                else if(checkedSource ===false ){
                    document.getElementById('error_message').innerHTML = '<div class="alert alert-danger card-header text-center flashit"><strong>Warning!</strong> No source selected!</div>';
                    event.preventDefault();
                }
                else if(checkedCategory===false){
                    document.getElementById('error_message').innerHTML = '<div class="alert alert-danger card-header text-center flashit"><strong>Warning!</strong> No  category selected!</div>';
                    event.preventDefault();
                }

        }

问题是:当我在注册JavaScript函数时没有选中任何复选框,它会阻止将数据保存到数据库中,并打印任何它应该执行的操作。打印警告消息后,我选中几个框并提交表单。表单提交并重定向到主页,但是,一旦我查看数据库,检查的布尔值就不会保存-它们都是假的。我对register的django视图是:

代码语言:javascript
运行
复制
def registration(request):
    context = {}

    if request.user.is_authenticated: # If user is logged in, redirect to home screen, they cannot register again!
        return redirect('home')
    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            account = authenticate(username=username, password=raw_password)
            login(request, account)
            return redirect('home')
        else:
            context['registration_form'] = form
    else: # GET request
        form = RegistrationForm()
        context['registration_form'] = form
    return render(request, 'accounts/register.html', context)

编辑:在检查了git上的提交并将文件与最早提交的文件进行比较后,我终于发现了这个bug。基本上是寄存器模板中的代码:

代码语言:javascript
运行
复制
<label for="guardianSource" >The Guardian</label>
    <input type="checkbox" name="source" id="guardianSource">
    <br>
    <label for="bbcSource" >BBC News</label>
    <input type="checkbox" name="source" id="bbcSource">
    <br>
    <label for="independentSource" >The Independent</label>
    <input type="checkbox" name="source" id="independentSource">
   </div>
   <br>
   <div  class="form-control">
    <p><b>Please choose news category!</b></p>

    <label for="categoryCoronaVirus" >Corona Virus</label>
    <input type="checkbox" name="category" id="categoryCoronaVirus">
    <br>
    <label for="categoryPolitics" >Politics</label>
    <input type="checkbox" name="category" id="categoryPolitics">
    <br>
    <label for="categorySport" >Sport</label>
    <input type="checkbox" name="category" id="categorySport">
   </div>

出于某种原因,我重命名了每个复选框的名称属性。将值更改为:

代码语言:javascript
运行
复制
<label for="guardianSource" >The Guardian</label>
    <input type="checkbox" name="guardianSource" id="guardianSource">
    <br>
    <label for="bbcSource" >BBC News</label>
    <input type="checkbox" name="bbcSource" id="bbcSource">
    <br>
    <label for="independentSource" >The Independent</label>
    <input type="checkbox" name="independentSource" id="independentSource">
   </div>
   <br>
   <div  class="form-control">
    <p><b>Please choose news category!</b></p>

    <label for="categoryCoronaVirus" >Corona Virus</label>
    <input type="checkbox" name="categoryCoronaVirus" id="categoryCoronaVirus">
    <br>
    <label for="categoryPolitics" >Politics</label>
    <input type="checkbox" name="categoryPolitics" id="categoryPolitics">
    <br>
    <label for="categorySport" >Sport</label>
    <input type="checkbox" name="categorySport" id="categorySport">
   </div>

它起作用了。

EN

回答 1

Stack Overflow用户

发布于 2020-04-15 05:35:15

您似乎再次在表单中重复了一些模型字段。这是不必要的,并且可能会导致此错误。如果在models.py和forms.py中使用以下内容,那么调用save()方法应该保存数据库中的所有字段。

models.py:

代码语言:javascript
运行
复制
class Account(AbstractUser):
    guardianSource = models.BooleanField(blank=True, null=True)
    bbcSource = models.BooleanField(blank=True, null=True)
    independentSource = models.BooleanField(blank=True, null=True)

    categoryCoronaVirus = models.BooleanField(blank=True, null=True)
    categoryPolitics = models.BooleanField(blank=True, null=True)
    categorySport = models.BooleanField(blank=True, null=True)

forms.py:

代码语言:javascript
运行
复制
class RegistrationForm(UserCreationForm):

    class Meta:
        model = Account
        fields = ("username", "password1", "password2", "guardianSource", "bbcSource", "independentSource", "categoryCoronaVirus", "categoryPolitics", "categorySport")
        widget = {'guardianSource': forms.CheckboxInput(attrs={'id':'guardianSource'})}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61216943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档