【问题标题】:If statement always returning Trueif 语句总是返回 True
【发布时间】:2016-01-04 08:15:18
【问题描述】:

对于我的 django 项目,我有一个页面允许用户编辑他们的列表,为此我添加了一个检查,以确保打开页面的人是列表的所有者。但是,无论如何,我放入的 if 语句总是返回 true,即使我将它正在检查的内容更改为完全不相关的对象。我什至将它从 != 更改为 == 并且它总是返回 true,有人知道这里发生了什么吗?

@login_required(redirect_field_name='login')
def editlisting(request, pk):

    post = JobListing.objects.get(pk=pk)

    print(type(request.user))
    print(type(post.user))

    if request.user != post.user:
        print("THIS WORKS") #This is for debugging
        print(request.user) #This is for debugging
        print(post.user) #This is for debugging
        return redirect("index")

    if request.method == "POST":
        form = JobListingForm(request.POST, instance=post)

        if form.is_valid():
            profile = form.save(commit=False)
            profile.user = request.user
            profile.save()
            return redirect('index')

    else:
        form = JobListingForm(instance=post)

    context = {
        "form": form
    }

    return render(request, "editlisting.html", context)

任何帮助表示赞赏!

编辑:

这是控制台中的内容- http://puu.sh/kBuuX/30501a9407.png

这也是我的模型代码

class JobListing(models.Model):

    region_choice = (
        ('1', 'Auckland'),
        ('2', 'Wellington'),
        ('3', 'Christchurch')
    )
    industry_choice = (
        ('1', 'Accounting'),
        ('2', 'Agriculture, fishing & forestry'),
        ('3', 'Automotive'),
        ('4', 'Banking, finance & insurance'),
        ('5', 'Construction & Architecture'),
        ('6', 'Customer service'),
    )
    employment_type_choice = (
        ('1', 'Full Time'),
        ('2', 'Part Time'),
        ('3', 'One-off'),
        ('4', 'Other')
    )

    user = models.CharField(max_length=50)
    job_title = models.CharField(max_length=30)
    business_name = models.CharField(max_length=50)
    pay_rate = models.FloatField()
    employment_type = models.CharField(max_length=10, choices=employment_type_choice)
    job_description = models.CharField(max_length=2000)
    business_address_region = models.CharField(max_length=50, choices=region_choice)
    business_address_suburb = models.CharField(max_length=50)
    business_industry = models.CharField(max_length=50, choices=industry_choice)
    contact_method = models.CharField(max_length=50)
    active_listing = models.BooleanField(default=True)

    class Meta:
        verbose_name = 'Job Listing'

    def __unicode__(self):
        return "%s" % self.business_name

【问题讨论】:

  • 它在你的“调试”中打印了什么?
  • 在测试之前移动打印语句,并添加print(type(request.user)); print(type(post.user)) 以确保您正在比较可比较的对象。
  • 另外,尝试使用 .pk,当您期望来自同一个表的两个项目时,这是最简单的比较。

标签: python django if-statement


【解决方案1】:

快速修复:

if str(request.user) != str(post.user):

在您的调试中,您会看到相同的字符串,因为print 函数隐式调用了str 函数(它只能打印字符串)。但是您实际上尝试将一个对象 (request.user) 与一个字符串 (post.user) 进行比较,这会产生意想不到的结果。


耐用修复:

在您的 JobListing 模型中,字段 user 应该是 ForeignKey(而不是 CharField)。

然后您可以比较 request.user 和 post.user 的 pk(主键)属性(如 @Beltiras 所建议的那样)。

【讨论】:

  • 最初我将用户字段设置为 onetoone,但我不得不更改它,因为它不允许用户拥有多个列表,因为用户名需要是唯一的。关于如何解决这个问题的任何想法?
  • 我刚刚意识到为什么我遇到了它不是唯一的问题,这是因为当我保存更新后的表单时,它并没有更新旧的表单,而是试图创建一个新表单并离开旧的一样。有关如何解决此问题的任何想法?
  • 您可能想看看this question。如果您仍然无法解决您的问题,请打开另一个问题。
  • 我知道操作已经接受,但我可以建议你的脏修复变成if request.user.get_username() != post.user:吗?正如docs - "中提到的那样。由于可以换出用户模型,因此您应该使用此方法而不是直接引用用户名属性。"持久修复仍然非常首选
  • 我更喜欢留下我的帖子原样,让人们直接阅读您的评论(因为它是关于不推荐的解决方案)
【解决方案2】:

我不知道你的模型,但我猜JobListing.user 是用户的外键。在这种情况下,您将 User 实例与字符串进行比较,这在任何情况下都会有所不同。也许你需要类似的东西:

if request.user != post.user.username:

检查您的模型以获取正确的属性名称。

【讨论】:

  • 如果它真的是一个 fk 那么操作不是将用户与字符串进行比较,而是将用户与用户进行比较,并且没有解释为什么操作仍然切换布尔运算符返回相同的值
  • 好吧,我们会更了解模型。
  • 我认为我们需要至少在此之前回答 Oliverpool 的评论。 request.user 在默认情况下也始终是 django 中的 User 实例。
  • 我已经添加了我的模型
猜你喜欢
  • 2015-12-16
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
相关资源
最近更新 更多