【问题标题】:Setting a field on a model not using a form在不使用表单的模型上设置字段
【发布时间】:2017-08-17 18:26:53
【问题描述】:

我有一个网站,当用户单击引导 glyphicon 链接时,他们应该被重定向到另一个页面,该页面具有相同的 glyphicon,但颜色为绿色,看起来好像通过按下链接他们激活了按钮.在这个过渡期间,我希望我的Profile 上的字段activeFalse 变为True。我有以下代码:

models.py:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    university = models.CharField(max_length=30, blank=True)

    ROLE = (
        ('CUSTOMER', 'User'),  # (value to be set on model, human readable value)
        ('WORKER', 'Worker'),
    )

    role = models.CharField(max_length = 20, choices = ROLE, default = 'USER')


    active = models.BooleanField(default = False)

views.py

def active(request):
    request.user.profile.active = True;
    return render(request, 'core/customer_active.html', {'user': request.user})

home.html:

<a href="{% url 'active' %}"><span class="glyphicon glyphicon-ok-sign" aria-hidden="true"></span></href>

我不知道为什么request.user.profile.active = True; 不更新字段的状态,什么会?

【问题讨论】:

    标签: django django-models django-views


    【解决方案1】:

    正如其他人所说,您需要保存。但是,您需要保存的是 配置文件,而不是用户,因为这是一个单独的模型。

    profile = request.user.profile
    profile.active = True
    profile.save()
    

    【讨论】:

      【解决方案2】:

      这是对“活动”属性的永久更改吗?如果是这样,您需要保存用户对象。像这样:

      def active(request):
          request.user.profile.active = True;
          request.user.save()
          return render(request, 'core/customer_active.html', {'user': request.user})
      

      编辑:可能值得注意的是,这不是更新用户个人资料的最聪明方法,每次点击此视图时保存此属性,但如果您只是想知道为什么 True 值不是坚持,这就是原因。

      【讨论】:

        猜你喜欢
        • 2011-12-02
        • 2012-05-14
        • 1970-01-01
        • 2021-10-19
        • 2014-07-09
        • 2018-04-18
        • 2019-07-18
        • 1970-01-01
        • 2023-04-01
        相关资源
        最近更新 更多