我有一个Django视图,所有用户(房东,代理和前景)都可以访问,在这个视图上,我想在我的模板上显示房产所有者的名字,但每当潜在客户用户在视图上时,我只显示None。了解这三个用户的模型与用户模型具有一对一字段关系。我也有一个与用户模型具有相同关系的配置文件模型。查看下面的视图代码:
def property_detail(request, property_id):
user = request.user
#Check if user is authenticated
if user.is_authenticated:
#Check if user is Landlord
if hasattr(user, 'landlord'):
properties = Property.objects.filter(landlord=user.landlord).prefetch_related('agent').order_by('-last_updated')[:4]
property_owner = user.landlord.profile if hasattr(user.landlord, 'profile') else None
#Check if user is Agent
elif hasattr(user, 'agent'):
properties = Property.objects.filter(agent=user.agent).prefetch_related('landlord').order_by('-last_updated')[:4]
property_owner = user.agent.profile if hasattr(user.agent, 'profile') else None
else:
properties = Property.objects.order_by('-last_updated')[:4]
property_owner = None
#Get the Property by its Product key from DB
property_instance = get_object_or_404(Property, pk=property_id)
#Send Notification to property owner
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
content = form.cleaned_data['content']
subject = form.cleaned_data['subject']
Message.objects.create(property=property_instance, sender=user, recipient=property_owner, subject=subject, content=content)
messages.success(request, 'Notification sent successfully with your Contact Details.')
else:
form = MessageForm()
context = {
'form':form,
'properties':properties,
'property_owner': property_owner,
'page_title': 'Property Detail',
'property': property_instance,
}
return render(request, 'realestate/landlord_agent_property.html', context)
# Handle the case when the user is not authenticated
logout(request)
messages.warning(request, 'Session expired. Please log in again.')
return redirect(reverse('account-login'))
2条答案
按热度按时间ujv3wf0j1#
首先,我必须说你的数据库设计方法非常混乱,你可以只使用一个带有标志的模型
Profile
(例如:is_landlord
、is_agent
和is_propect
)。或者,更好的是,使用Groups
。根据你对
Models
的描述,这里的问题是你试图访问不存在的属性,所以它总是返回None
:一个
User
有一个Profile
,也可以是一个Agent
,但它们是不同的属性。这意味着Profile
不在Agent
内部:并且,在模板中显示名称:
thtygnil2#
不要使用
hasattr
来标识用户组。用户将始终具有landlord
属性,无论是None
还是模型示例。使用
user.landlord is not None
代替。