django forms

django 中的 form 和 model 的用法很像,都是定义一个类,然后指定一些字段就可以了

最简单的form

“`
from django import forms

class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
email = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea)

def clean_message(self):
message = self.cleaned_data[‘message’]
num_words = len(message.split())
if num_words < 4: raise forms.ValidationError("Not enough words!") return message ``` ``` def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data send_mail( cd['subject'], cd['message'], cd.get('email', 'noreply@example.com'), ['siteowner@example.com'], ) return HttpResponseRedirect('/contact/thanks/') else: form = ContactForm() return render(request, 'contact_form.html', {'form': form}) ``` ```

{{ form.as_table }}

{% csrf_token %}

“`

方法 | 用法
——|——
form.__str__() | return table representation
form.as_p() | return p representation
form.as_li() | return li representation
form.__getitem__() | return element tag
form.__init__(dict) | fill values
form.is_bound |
form.is_valid() |
form.cleaned_data |

Note not include table/ul/form tags, just the inside tags

# ajax

## ajax 中如何指定 crsf token

axios 中:

import axios from ‘axios’;
axios.defaults.xsrfHeaderName = “X-CSRFTOKEN”;
axios.defaults.xsrfCookieName = “csrftoken”;

settings.py 中

CSRF_COOKIE_NAME = “csrftoken”

[参考](https://stackoverflow.com/questions/39254562/csrf-with-django-reactredux-using-axios)

About 逸飞

后端工程师

发表评论

电子邮件地址不会被公开。 必填项已用*标注