对于我的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
答案 0 :(得分:3)
快速脏修复:
if str(request.user) != str(post.user):
在调试中,您会看到相同的字符串,因为print
函数隐式调用str
函数(它只能ptrint字符串)。但实际上你试图将一个对象(request.user)与一个strin(post.user)进行比较,这会产生意想不到的结果。
耐用修复:
在JobListing
模型中,字段user
应为ForeignKey(而不是CharField)。
然后,您可以比较request.user和post.user的pk
(主键)属性(由@Beltiras建议)。
答案 1 :(得分:-3)
我不知道你的模型,但我想JobListing.user
是一个用户的ForeignKey。在这种情况下,您将User实例与字符串进行比较,在任何情况下都会有所不同。也许你需要这样的东西:
if request.user != post.user.username:
检查您的模型是否有正确的属性名称。