我希望能夠爲用戶分配車輛註冊,並且當用戶登錄到網站時,他們的主頁應該有他們擁有的車輛註冊表列表。在多對一模型上過濾
但是我不能讓模型類過濾外鍵。
views.py
@login_required
def home(request):
# This is the basic user landing Page
veh_list = Vehicle.objects.filter(UserProfile.user)
return render(request, 'portal/home.html', {"veh_list": veh_list})
model.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
compName = models.CharField(max_length = 20)
milkco = models.IntegerField()
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user.username
class Vehicle(models.Model):
vehid = models.CharField(max_length = 10)
company = models.ForeignKey(UserProfile, default = 1)
class Meta:
db_table = "vehicle"
def __unicode__(self):
return self.vehid
home.html的
<!DOCTYPE html>
{% extends 'portal/base.html' %}
{% block title %}{{user.first_name }} {{ user.last_name }} Portal{% endblock %}
{% block content %}
<p>This is the home Page</p>
{% if user.is_authenticated %}
<h4>Optiload says... hello {{ user.first_name }} {{ user.last_name }}!</h4>
{% endif %}
{% for veh in veh_list %}
{{ veh}}
{% endfor %}
{% if user.is_authenticated %}
<a href="/logout/">Logout</a><br/>
{% endif %}
{% endblock %}
有人能幫助我,我要去錯在何處?
感謝
工作的呢? 'veh_list = Vehicle.objects.filter(company__user = request.user)' – Sagar
@Sagar是的..這正是我需要的。 – Jim
我將添加它作爲答案:) – Sagar