为什么实例模型的属性不会改变

时间:2019-04-20 22:44:15

标签: django postgresql django-views

我创建了一个财务经理,我需要用户更改帐户活动(指示是否为活动帐户),但是当我发送更改表格时,model属性不会更改,并且始终为TRUE

我也尝试通过帐户副本来执行此操作,但这也不是结果的结果 Account.objects.get(user = self.request.user,id = id).is_active = False

models.py

class Account(models.Model):
    type_of_currency = models.CharField(max_length=20)
    user = models.ForeignKey(get_user_model(), blank=True,
                             related_name='user_account',
                             on_delete=models.CASCADE)
    count = models.DecimalField(max_digits=12, decimal_places=2, blank=True)
    created = models.DateTimeField(default=datetime.datetime.now)
    is_active = models.BooleanField()

    def __str__(self):
        return f'{self.type_of_currency} - {self.count}'

views.py

class AccountDetailView(DetailView, UpdateView):
    model = Account
    form_class = AccountCreateForm
    template_name = 'account_detail.html'

    def post(self, request, *args, **kwargs):
        id = self.request.POST['accountid']  
        self.request.user.user_account.get(id=6).is_active = False
        print(self.request.user.user_account.get(
            id=id).is_active)  # always True why?
        return redirect('/counts/' + id)

模板

{% extends 'base.html' %}
{% block content %}
    <div class="col-sm-5">
        <h1>account: {{ account.id }}</h1>

        <p><strong>Author:</strong> {{ account.user }}</p> <!-- author detail link not yet defined -->
        <p><strong>Type:</strong> {{ account.type_of_currency }}</p>
        <p><strong>count:</strong> {{ account.count }}</p>
        <p><strong>IsCreated:</strong> {{ account.created }}</p>
        <p><strong>IsActive:</strong>{{ account.is_active }}</p>
        <a class="btn btn-outline-primary"
           href="{% url 'account-list' %}">Back</a>
        {% if account.is_active %}
            <form method="post">
                {% csrf_token %}
                <input type="hidden" value="{{ account.id }}" name="accountid">
                <button type="submit" class="btn btn-outline-danger">Deactivate</button>
            </form>
        {% else %}
            <form method="post">
                {% csrf_token %}

                <button type="submit" class="btn btn-outline-success">Activate</button>
            </form>
        {% endif %}
    </div>
{% endblock %}

在发布方法DetailViews中,我希望在按下按钮之后,用户活动将发生变化,但结果始终为True

1 个答案:

答案 0 :(得分:1)

您永远不会将更改提交给数据库。

此外,我不会使用以下语法:self.request.user.user_account.get(id=6).is_active = False

您可以尝试:self.request.user.user_acocount.filter(id=6).update(is_active=False)

但是,如果您在使用.get()时已死定了:

user_acc = self.request.user.user_account.get(id=6)
user_acc.is_active = False
user_acc.save()