Question

I'm working in Django forms. I'm a bit lost with where to put code about forms (forms.py or models.py?) And which code put in my template. I searched about docs but can't figure it out, I'm a bit new in Django, thanks.

I will appreciate if somebody could gave me a complete example of a simple form to understand this stuff.

Thanks.

Was it helpful?

Solution

From the Django docs

You should create your Form classes in forms.py

Example

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

To render the form in your template you need to add it into the context. So your views.py should look something like this.

from django.shortcuts import render
from django.http import HttpResponseRedirect

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        # ContactForm was defined in the the previous section
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render(request, 'contact.html', {
        'form': form,
    })

Notice this part. The dictionary {'form': form} is your request context which means that the keys will be added to your template variables.

return render(request, 'contact.html', {
    'form': form,
})

Now, you can use it in your templates.

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

OTHER TIPS

You can take a Look at this Basic Sample, provided in following link, for Handling a POST form in django.

http://www.pythoncentral.io/how-to-use-python-django-forms/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top