1

So say I had a django views.py file with the following:

def addauthorView(request):
if request.method == 'POST':
     f = ContactForm(request.POST)
     if form.is_valid():
        first_name = form.cleaned_data['firstname']
        last_name = form.cleaned_data['lastname']
        user_email = form.cleaned_data['email']
        c = Contact(firstname=first_name, lastname=last_name, email=user_email)
     else:
        form = ContactForm(request.POST)
        return render(request, 'addauthor.html', {'form': ContactForm})
else:
    return render(request, 'addauthor.html', {'form': ContactForm})

A forms.py file like such

class ContactForm(forms.Form):
    firstname = forms.CharField(max_length=50)
    lastname =forms.CharField(max_length=50)
    email = forms.EmailField()

and a HTML file like such

<html>
<head>
    <title>Head</title>
</head>

<body>
    <ul>
    {{form.as_ul}}
    <input type="submit">  
    </ul>
</body>

How do I make it the case that when the <input type="submit"> button is pressed, my ContactFormview will execute some code. Is there a specific way to group buttons into a forms.py? Or is there any other way to do this. If someone could help me rework this code, that would be great.

Thanks in advance.

1 Answer 1

1

Just enclose form.as_ul and submit button into the form tag:

<form action="/your_url_here/" method="post">{% csrf_token %}
{{ form.as_ul }}
<input type="submit" value="Submit" />
</form>

Also see Displaying a form using a template.

Hope that helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I almost thought it wasn't that easy ;P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.