尝试使用查询集基于外键过滤ModelForm结果时出现Django AttributeError异常。
Request Method: GET
Request URL: http://127.0.0.1:8000/pipelines/surveyview/
Django Version: 2.2.1
Exception Type: AttributeError
Exception Value: 'SurveyDate' object has no attribute 'client_id'
为什么要查找“ client_id”而不是“ client_id_fk”?
models.py
class Client(models.Model):
client_id = models.AutoField(primary_key=True)
# add company ID field to the User model to pair with Client table.
class CustomUser(AbstractUser):
client_id_fk = models.ForeignKey(Client, on_delete=models.CASCADE, blank=True, null=True)
class SurveyDate(models.Model):
client_id_fk = models.ForeignKey(Client, on_delete=models.CASCADE)
pipe_id_fk = models.ForeignKey(Pipeline, on_delete=models.CASCADE)
survey_date = models.DateField()
def __str__(self):
return str(self.survey_date, self.pipe_id_fk)
forms.py
class SurveyDateForm(forms.ModelForm):
class Meta:
model = SurveyDate
fields = ['client_id_fk', 'pipe_id_fk', 'survey_date']
def __init__(self, request, *args, **kwargs):
super(SurveyDateForm,self).__init__(*args, **kwargs)
self.fields['client_id_fk'].queryset = SurveyDate.objects.filter(client_id_fk=request.user.client_id_fk)
views.py
form = SurveyDateForm(request)
return render(request, 'surveydate_list.html', {'form':form}
surveydate_list.html
<form method="get" novalidate>
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
</form>
我希望表单仅显示链接到当前登录用户的结果。