過去幾周我一直在慢慢學習 Django,并將其應用于作業原型。我有一個簡單的個人資料模型,稱為申請人。這存盤了客戶的個人欄位。它包含一個鏈接到 Django Auth User 模型的 OnetoOne 欄位,因為我使用它來要求登錄和控制對資料的訪問。我正在努力弄清楚如何在視圖類中執行檢查(在視圖函式中似乎更容易),我需要一種方法來檢查用戶是否已經有一個申請人條目,然后再向他們展示 CreateView 表單。
以前為了顯示這個申請人的個人資料資料(通過管理頁面創建),我使用了 DetailView.get_object 中的 get_object_or_404 來捕獲 Http404 并在他們沒有個人資料時回傳 None 。這將提供一個指向“創建”頁面的鏈接。我需要在 CreateView 上實作反向邏輯,以保護它們免于創建多個申請人條目。
任何建議都會很棒,即使只是為我指明正確的方向。
我用于 DetailView 的代碼:
class ApplicantProfileDetailView(LoginRequiredMixin, generic.DetailView):
model = Applicant
template_name ='profile.html'
def get_object(self, queryset=None):
try:
return get_object_or_404(Applicant, user=self.request.user)
except Http404:
return None
<h1>Applicant Profile</h1>
{% if applicant %}
...
{% else %}
<p>You have not created an Applicant profile, click below to create one.</p>
<a href="/profile/create" class="btn btn-primary"> Create Profile </a>
{% endif %}
嘗試對 CreateView 執行相同的操作,無論如何只會顯示表單:
class ApplicantProfileCreateView(LoginRequiredMixin, generic.CreateView):
model = Applicant
fields = [...]
template_name = 'profile_create_form.html'
success_url = '/'
def get_object(self, queryset=None):
try:
return get_object_or_404(Applicant, user=self.request.user)
except Http404:
return None
{% if applicant %}
<p>You already have an Applicant profile. If you'd like to edit it, please use the edit option on the profile page.</p>
<a href="/profile/" class="btn btn-primary"> View Profile </a>
{% else %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
{% endif %}
uj5u.com熱心網友回復:
generic.CreateView沒有定義get_object方法,因此您的授權檢查永遠不會運行。你可以把它放在get函式中,因為大概,用戶需要在發布之前請求頁面(除非這是一個 ajax 視圖)。
class ApplicantProfileCreateView(LoginRequiredMixin, generic.CreateView):
model = Applicant
fields = [...]
template_name = 'profile_create_form.html'
success_url = '/'
def get(self, request, *args, **kwargs):
if Application.objects.filter(user=self.request.user).exists():
return redirect('/profile/') # ideally you'd use the url name here instead.
return super().get(request, *args, **kwargs)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371708.html
標籤:姜戈 django-views
上一篇:根據用戶是否屬于專案團隊進行過濾
