2017-08-08 78 views
1

無論我如何實現我的表單,我都會收到跟隨錯誤。當我轉到我的表單的URL時會發生這種情況。Django - 'ContactForm'對象沒有任何屬性'get'

forms.py

class ContactForm(forms.ModelForm): 

    class Meta: 
     model = ContactUs 
     fields = ('name', 'email', 'phone', 'message') 

models.py

class ContactUs(models.Model): 
    name = models.CharField(max_length=50, blank=True) 
    email = models.EmailField() 
    phone = models.CharField(max_length=15, blank=True) 
    message = models.TextField() 
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) 

    class Meta: 
     verbose_name_plural = "Contact Us" 

views.py

def contact(request): 
    if request.method == "POST": 
     form = ContactForm(request.POST or None) 
     errors = None 
     if form.is_valid(): 
      ContactUs.objects.create(
       name = form.cleaned_data.get('name'), 
       email = form.cleaned_data.get('email'), 
       phone = form.cleaned_data.get('phone'), 
       message = form.cleaned_data.get('message'), 
       created_at = form.cleaned_data.get('created_at') 
      ) 
      return HttpResponseRedirect("/s/") 
     if form.errors: 
      errors = form.errors 

     template_name = 'contact_us.html' 
     context = {"form": form, "errors": errors} 
     return render(request, template_name, context) 

urls.py

url(r'^contacts/$', views.ContactForm, name='contact_form'), 

html

<form method="POST" class="post-form">{% csrf_token %} 
     {{ form.as_p }} 
     <button type="submit" class="save btn btn-warning">Submit</button> 
</form> 

在此先感謝!

回答

1

以及多數民衆贊成監守你只檢查POST而不是GET方法什麼

def contact(request): 
    template_name = 'contact_us.html' 
    if request.method == "POST": 
     form = ContactForm(request.POST or None) 
     errors = None 
     if form.is_valid(): 
      ContactUs.objects.create(
       name = form.cleaned_data.get('name'), 
       email = form.cleaned_data.get('email'), 
       phone = form.cleaned_data.get('phone'), 
       message = form.cleaned_data.get('message'), 
       created_at = form.cleaned_data.get('created_at') 
      ) 
      return HttpResponseRedirect("/s/") 
     if form.errors: 
      errors = form.errors 

     context = {"form": form, "errors": errors} 
     return render(request, template_name, context) 
    else: 
     form = ContactForm() 
     return render(request, template_name, {'form':form}) 

,改變您的網址

url(r'^contacts/$', views.contact, name='contact_form'), 
2

您已將您的網址指向表單,而不是視圖。它應該是:

url(r'^contacts/$', views.contact, name='contact_form'), 

注意,一旦你已經解決了這個問題,你將有一個問題,因爲你的觀點並沒有對GET請求返回任何東西。

相關問題