Revision 616564613331 () - Diff

Link to this snippet: https://friendpaste.com/2Rtzh6wOiUMQA0aRJTpC0Q
Embed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# models ********************

class Section(models.Model):
"""
A section has a begin and end valid date
which represents : 'Where can we interact with all related/children objects ?'
"""
title = models.CharField(_(u"Title"), max_length=200)
begin = models.DateField(_(u"Date début"))
end = models.DateField(_(u"Date fin"))


class Article(models.Model):
"""
Simple object
"""
title = models.CharField(_(u"Title"), max_length=200)
section = models.ForeignKey(Section, blank=True)


class Item(models.Model):
"""
This item is related to an article
It has to know when it is valid,
a date between its section begin/end
"""
title = models.CharField(_(u"Title"), max_length=200)
date = models.DateField()



# forms ********************

class ItemForm(forms.ModelForm):
"""
The date has to be a list of choices
from self.article.section.begin / end
"""
date = ChoiceField(choices={})

def __init__(self, section, *args, **kwargs):
super(ItemForm, self).__init__(*args, **kwargs)
begin = date(2009, 06, 16) #section.begin
end = date(2009, 06, 18) #section.end
daterange = end-begin
choices = [('','-----')]
for i in range(daterange.days):
date_in = (begin + timedelta(i))
verbose_date = "%s %s %s" % (date_in.day, month_name(date_in.month), date_in.year)
choices.append((date_in, verbose_date))
self.fields['date'].choices=choices

class Meta:
model = Item


class ArticleForm(ModelForm):
class Meta:
model = Article



# views ********************

def items_form(request, section_id, article_id=None):
"""
Create/Update an article and its related items
"""
section = get_object_or_404(Section, id=section_id)

try:
article = Article.objects.get(id=article_id)
except Article.DoesNotExist:
article = Article()

ItemFormSet = inlineformset_factory(Article, Item, form=ItemForm, extra=2, can_delete=True)

if request.method == "POST":
form = ArticleForm(data=request.POST, instance=article)
formset = ItemFormSet(request.POST, instance=article, **kwargs)
if form.is_valid() and sessionformset.is_valid():
object = form.save(commit=False)
object.section=section
object.save()
sessionformset.save()
# do something ...
else:
form = ArticleForm(instance=article)
formset = ItemFormSet(instance=article, **kwargs)

# render template ...