首页 > 解决方案 > Django - 帐户设置 BooleanField

问题描述

我在这里查看了与 Django 和 BooleanField 更新相关的大部分帖子,但我找不到任何与我的问题解决方案相关的帖子。我有一个自定义用户models.py:

# Own custom user model
class Account(AbstractBaseUser):

    username = models.CharField(max_length=30, unique=True)

    guardianSource = models.BooleanField(default=True)
    bbcSource = models.BooleanField(default=False)
    independentSource = models.BooleanField(default=False)

    categoryCoronaVirus = models.BooleanField(default=False)
    categoryPolitics = models.BooleanField(default=False)
    categorySport = models.BooleanField(default=False)

当我注册用户时,它似乎在数据库中注册了复选框的所有正确值。问题是当我想编辑用户信息时,我看不到是否在注册时选中了复选框,它会显示复选框本身,但它们都是空的(False)。但是,它正确地请求用户名并显示它,以便我可以编辑它,但所有复选框都未选中。视图.py:

def account_view(request):
    if not request.user.is_authenticated:
        return redirect('login')
    context = {}
    if request.POST:
        form = AccountUpdateForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            context['success_message'] = "Updated"
    else: # Display the saved user details from database
        form = AccountUpdateForm(
                                initial = {
                                'username':request.user.username,
                                "guardianSource": request.user.guardianSource,
                                "bbcSource": request.user.bbcSource,
                                "independentSource": request.user.independentSource,

                                "categoryCoronaVirus": request.user.categoryCoronaVirus,
                                "categoryPolitics": request.user.categoryPolitics,
                                "categorySport": request.user.categorySport,
                                            })
    context['account_form'] = form
    return render(request, 'accounts/account.html', context)

帐户html:

{% extends 'base.html' %}

{% block content %}

<form class="form-signin" method="POST">{% csrf_token %}

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

  <label for="username" class="sr-only">Username</label>
  <input type="text"   name="username" id="username" class="form-control" placeholder="Username"   value="{{account_form.initial.username}}">
    <br>
   <div  class="form-control">
      <p><b>Please choose news sources!</b></p>

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

      <label for="categoryCoronaVirus" >The Guardian</label>
      <input type="checkbox" name="categoryCoronaVirus" id="categoryCoronaVirus" value="{{account_form.initial.categoryCoronaVirus}}" >

    <br>

      <label for="categoryPolitics" >BBC News</label>
      <input type="checkbox" name="categoryPolitics" id="categoryPolitics" value="{{account_form.initial.categoryPolitics}}" >
    <br>

      <label for="categorySport" >The Independent</label>
      <input type="checkbox" name="categorySport" id="categorySport" value="{{account_form.initial.categorySport}}">

  </div>

    {% for field in registration_form %}
        <p>
            {% for error in field.errors %}
                <p sttle="color:red"> {{ error }}</p>
            {% endfor %}
        </p>
    {% endfor %}
    {% if registration_form.non_field_errors %}
        <div style="color:red;">
                <p>{{registration_form.non_field_errors}}</p>
        </div>
    {% endif %}
    {% for field in account_form %}
        <p>
            {% for error in field.errors %}
                <p sttle="color:red"> {{ error }}</p>
            {% endfor %}
        </p>
    {% endfor %}
    {% if account_form.non_field_errors %}
        <div style="color:red;">
                <p>{{account_form.non_field_errors}}</p>
        </div>
    {% endif %}

    {% if success_message %}
     <p style = "color: green; text-align:center;">{{success_message}}</p>
    {% endif %}
    <h6 class="text-muted">
      If you don't choose a source and category it will automatically assign the ones that are checked!<br>
     NOTE: You <b>MUST</b> select at least 1 choice for each!!!
  </h6>
  <button class="btn btn-lg btn-primary btn-block" type="submit">Save Changes</button>

</form>
<div class="d-flex flex-column">
  <a class="m-auto" href="{% url 'password_change' %}">Change password</a>
</div>


{% endblock content %}

在此先感谢,如果我的帖子被重复,我很抱歉。

编辑:发现问题。在 account.html 文件中,每个输入类型复选框的值都是错误的。我改变了什么:

<input type="checkbox" name="guardianSource" id="guardianSource" value="{{account_form.initial.guardianSource}}" >

至:

<input type="checkbox" name="guardianSource" id="guardianSource" value="{{account_form.guardianSource}}" >

对于用户名输入后的所有输入值,initial必须删除

标签: django

解决方案


初始化 ModelForm 并拥有实例时,您不需要传递初始值

else: # Display the saved user details from database
    form = AccountUpdateForm(instance=request.user)

您可以直接在模板中使用该字段,它将以正确的值呈现,您无需自己构造输入的 html

  <label for="{{ account_form.guardianSource.id_for_label }}">The Guardian</label>
  {{ account_form.guardianSource }}

文档中有一个关于如何手动呈现字段的部分


推荐阅读