django form code example

Example 1: django model form

class YourForm(ModelForm):
	class Meta:
    	model = YourModel
    	fields = ['pub_date', 'headline', 'content', 'reporter']

Example 2: in function how to get data from django form

from django.core.mail import send_mail

if form.is_valid():
    subject = form.cleaned_data['subject']
    message = form.cleaned_data['message']
    sender = form.cleaned_data['sender']
    cc_myself = form.cleaned_data['cc_myself']

    recipients = ['[email protected]']
    if cc_myself:
        recipients.append(sender)

    send_mail(subject, message, sender, recipients)
    return HttpResponseRedirect('/thanks/')

Example 3: django forms

<div class="fieldWrapper">
    {{ form.subject.errors }}
    {{ form.subject.label_tag }}
    {{ form.subject }}
</div>

Example 4: django get form id from request

# html
<input type="submit" value="Reply" name ="message_frm">

# views.py
if 'message_frm' in request.POST:
    #do somethings

Example 5: initial form

form = MyForm(initial={'name': 'Peter'})