Ad

Django - 'ContactForm' Object Has No Attribute 'get'

- 1 answer

I get the follow error no matter what way I do achieve my forms. This happens when I go to the URL of my form.

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>

Thanks in advance!

Ad

Answer

well thats becuase you are only checking POST and not anything for GET method

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})

and also change your url to

url(r'^contacts/$', views.contact, name='contact_form'),
Ad
source: stackoverflow.com
Ad