from django import new forms as forms <br />
class AddPlaceForm (forms.Form):
title = forms.CharField (max_length = 50)
category = forms.IntegerField ()
text = forms.CharField (widget = forms.Textarea)
tags = forms.CharField (max_length = 50))
city = forms.IntegerField ()
metrostation = forms.IntegerField (null = True)
adress = forms.CharField (max_length = 255)
def clean (self, value):
from my.site.models import Category
try:
item = Category.objects.get (pk = value)
return item
except ObjectDoesNotExist:
raise forms.ValidationError (u'Invalid input ')
class SelectFromModel (forms.Field):
widget = forms.Select ()
def __init __ (self, objects, * args, ** kwargs):
self.objects = objects
super (SelectFromModel, self) .__ init __ (* args, ** kwargs)
self.loadChoices ()
def loadChoices (self):
choices = ()
for object in self.objects.order_by ('title'):
choices + = ((object.id, object.title),)
self.widget.choices = choices
def clean (self, value):
value = int (value)
for cat_id, cat_title in self.widget.choices:
if cat_id == value:
return self.objects.get (pk = cat_id)
raise forms.ValidationError (u'Invalid input ')
Accordingly the form
class AddPlaceForm (forms.Form):
title = forms.CharField (max_length = 50)
category = SelectFromModel (objects = Category.objects.all ())
text = forms.CharField (widget = forms.Textarea)
# More on this later
tags = TagField ()
city = SelectFromModel (objects = City.objects.all ())
metrostation = SelectFromModel (objects = MetroStation.objects.all ())
adress = forms.CharField (max_length = 255)
class TagField (forms.CharField):
def clean (self, value):
from daparty.site.models import Tag, TagCynonym
tags = value.split (',')
resoult = []
for tag in tags:
tag = tag.strip (). lower ()
# We are looking in existing tags or create
dbtag = Tag.objects.get_or_create (title = tag)
resoult.append (dbtag)
return resoult
Source: https://habr.com/ru/post/16472/
All Articles