我的django項目我有一個頁面允許用戶編輯他們的列表,爲此我添加一個檢查,確保打開頁面的人是列表的所有者。然而,即使我將它正在檢查的內容更改爲完全不相關的對象,我放入的if語句也總是返回true。我甚至將它從!=改爲==,它總是返回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
它在你的「調試」中打印什麼? – oliverpool
在測試前移動打印語句,並添加'print(type(request.user)); print(type(post.user))'確保你比較了可比的對象。 –
此外,嘗試使用.pk,當您期望來自同一個表的兩個項目時,最簡單的比較。 –