Сломал всю голову, перечитал кучу документации, но так и не понял, что сделать валидацию полей. Можете натолкнуть на путь истинный?
view.py
def addAccess(request):
if request.method == 'POST':
frm = AccessesForm(data=request.POST)
if frm.is_valid():
title = request.POST.get('title')
service = request.POST.get('service')
username = request.POST.get('username')
password = request.POST.get('password')
comment = request.POST.get('comment')
Accesses.objects.create(title=title, service=service,
username=username, password=password,
comment=comment, owner=request.session['username'])
frm = AccessesForm()
return HttpResponseRedirect('/')
forms.py
from django import forms
from django.core.exceptions import ValidationError
class AccessesForm(forms.Form):
title = forms.CharField(max_length=50)
service = forms.CharField(max_length=50)
username = forms.CharField(max_length=50)
password = forms.CharField(widget=forms.PasswordInput)
comment = forms.CharField(max_length=150)
def clean(self):
cleaned_data = super(AccessesForm, self).clean()
title = cleaned_data.get('title')
# service = cleaned_data.get('service')
# message = cleaned_data.get('message')
if len(title) < 5:
raise ValidationError('Title should be more 5 characters')
models.py
from django.db import models
# Create your models here.
class Accesses(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
service = models.CharField(max_length=100)
username = models.CharField(max_length=30)
password = models.CharField(max_length=30)
comment = models.CharField(max_length=150, blank=True)
owner = models.CharField(max_length=30)
def __str__(self):
return self.username
view.py
def addAccess(request):
if request.method == 'POST':
frm = AccessesForm(data=request.POST)
if frm.is_valid():
title = frm.cleaned_data['title']
service = frm.cleaned_data['service']
username = frm.cleaned_data['username']
password = frm.cleaned_data['password']
comment = frm.cleaned_data['comment']
Accesses.objects.create(title=title, service=service,
username=username, password=password,
comment=comment, owner=request.session['username'])
return HttpResponseRedirect('/')
else:
frm = AccessesForm()
return render(request, 'index.html', {'accessForm': frm})
request.POST['чтототам']
, всё что вам нужно уже есть внутриfrm
djbook.ru/rel1.9/topics/forms/index.html