我可以發誓這是過去工作,但顯然我沒有測試,因爲我應該有。我有一個表格,允許用戶請求關於特定房地產列表的信息。有四(4)個單獨的視圖,其中一個顯示所有,另三個簡單地按屬性過濾列表,即租賃,僅限於房地產等。不同意見共享Django聯繫表
表單的工作方式應該像它應該在視圖中列出對象.all()和我以爲我可以在我的其他視圖中調用form_class,但是當我在被過濾的頁面上時,表單不起作用...瀏覽器中沒有錯誤消息或任何東西,電子郵件只是從來沒有到達我們的收件箱。
如果你可以看看我的觀點並提供一些反饋,我將非常感激,請讓我知道如果你需要看到任何其他的東西。謝謝。
from django.template.loader import get_template
from django.core.mail import EmailMessage
from django.template import Context
from django.shortcuts import render, redirect
from .models import Listing
from .forms import ContactForm
def listing_list(request):
listings = Listing.objects.all().order_by('listing_order')
form_class = ContactForm
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('contact_name', '')
contact_phone = request.POST.get('contact_phone', '')
contact_email = request.POST.get('contact_email', '')
contact_listing = request.POST.get('contact_listing', '')
form_content = request.POST.get('content', '')
# Email the profile with the
# contact information
template = get_template('contact_template.txt')
context = Context({
'contact_name': contact_name,
'contact_phone': contact_phone,
'contact_email': contact_email,
'contact_listing': contact_listing,
'form_content': form_content,
})
content = template.render(context)
email = EmailMessage("Form Submission from Listings Page", content, contact_email,
['[email protected]', '[email protected]'], ['[email protected]'])
email.send()
return redirect('listing_list')
return render(request, 'listing/listing_list.html', {'listings': listings, 'form': form_class})
def full_service(request):
listings = Listing.objects.filter(location_type='FULL_SERVICE').order_by('listing_order')
form_class = ContactForm
return render(request, 'listing/listing_list.html', {'listings': listings, 'form': form_class})
def quick_serve(request):
listings = Listing.objects.filter(location_type='QUICK_SERVE').order_by('listing_order')
form_class = ContactForm
return render(request, 'listing/listing_list.html', {'listings': listings, 'form': form_class})
def with_real(request):
listings = Listing.objects.filter(location_type='WITH_REAL').order_by('listing_order')
form_class = ContactForm
return render(request, 'listing/listing_list.html', {'listings': listings, 'form': form_class})
以及在其他3次,你沒有form.is_valid整個塊,實際處理表格併發送電子郵件...或者我錯過了什麼?只需將其作爲mixin並將其包含到每個視圖即可。此外,這整個設計都很糟糕,您必須將代碼複製到每個視圖,只需使用不同的'location_type'。 –
感謝您使用mixin的快速反饋和參考。是的,我可恥地把我的髒代碼放在這裏給大家看:)我知道它可以好多了,但我仍然通過學習Python/Django來攻擊我的方式,並且隨着我的進展,我會折射。謝謝。 –
我通常使用基於類的視圖,所以我使用了mixin,因爲它是我腦中彈出的第一個東西,但是您可以將普通函數視爲視圖,但只需使用參數就可以實現所有功能。 –