2017-10-15 79 views
0

我在我的主頁上創建了一個聯繫表單,但直到我第一次點擊提交表單時才顯示該表單。即調用get方法。我想保留它作爲我的主頁的獨立視圖,以便重新點擊「提交」時不會影響我的主頁。我的主頁加載時有沒有辦法加載我的'def email'?如何在Django中初始化我的表單?

模板形式

<form method="post" action="{% url 'home_page:email' %}"> 
      {% csrf_token %} 
{#   {% bootstrap_form form.as_p %}#} 
      {{ form.as_p }} 
      <input type="submit" value="Sign Up" class="btn btn-default"> 
     </form> 

網址

urlpatterns = [ 
    url(r"^$", views.HomePage.as_view(), name="home"), 
    url(r'^email/$', views.email, name='email'), 
    url(r'^success/$', views.success, name='success'), 
] 

視圖

class HomePage(MessageMixin, TemplateView): 
    template_name = "index.html" 

def email(request): 
    if request.method == 'GET': 
     form = ContactForm() 
    else: 
     form = ContactForm(request.POST) 
     if form.is_valid(): 
      subject = form.cleaned_data['subject'] 
      from_email = form.cleaned_data['from_email'] 
      message = form.cleaned_data['message'] 
      try: 
       send_mail(subject, message, from_email, ['[email protected]']) 
      except BadHeaderError: 
       return HttpResponse('Invalid header found.') 
      return redirect('success') 
    return render(request, "index.html", {'form': form}) 

回答

1

包括在主頁視圖上下文的形式。像這樣:

class HomePage(MessageMixin, TemplateView): 
    template_name = "index.html" 

    def get_context_data(self, **kwargs): 
     context = super(HomePage, self).get_context_data(**kwargs) 
     context['form'] = ContactForm(None) 
     return context 
+0

正如那句老話:「像魅力一樣工作......」 – Josh