如何在Django中访问业主详细信息

zsohkypk  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(138)

我有一个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'))
ujv3wf0j

ujv3wf0j1#

首先,我必须说你的数据库设计方法非常混乱,你可以只使用一个带有标志的模型Profile(例如:is_landlordis_agentis_propect)。或者,更好的是,使用Groups
根据你对Models的描述,这里的问题是你试图访问不存在的属性,所以它总是返回None

property_owner = user.agent.profile if hasattr(user.agent, 'profile') else None

一个User有一个Profile,也可以是一个Agent,但它们是不同的属性。这意味着Profile不在Agent内部:

property_owner = user.profile if hasattr(user, 'profile') else None

并且,在模板中显示名称:

{% if property_owner %}
    <p>{{property_owner.user.get_full_name}}</p>
{% endif %}
thtygnil

thtygnil2#

不要使用hasattr来标识用户组。用户将始终具有landlord属性,无论是None还是模型示例。
使用user.landlord is not None代替。

相关问题