Mercurial > agora-palash
comparison apps/snippet/forms.py @ 133:ba51d3b7740b
Add ability to upload a file to create a snippet
If a file is specified, the contents of that file are used in preference
to the contents of the 'content' text box.
author | dellsystem <ilostwaldo@gmail.com> |
---|---|
date | Sat, 22 Sep 2012 12:20:24 -0400 |
parents | d858aae811d0 |
children | f299232c82e8 |
comparison
equal
deleted
inserted
replaced
132:4f6977515048 | 133:ba51d3b7740b |
---|---|
17 ) | 17 ) |
18 | 18 |
19 EXPIRE_DEFAULT = 3600*24*30 | 19 EXPIRE_DEFAULT = 3600*24*30 |
20 | 20 |
21 class SnippetForm(forms.ModelForm): | 21 class SnippetForm(forms.ModelForm): |
22 file = forms.FileField(help_text=_("If the snippet you want to post is \ | |
23 saved as a file on your computer, you can upload it directly rather \ | |
24 than having to copy and paste it into the box above. If a file \ | |
25 is specified, the text in the content field above will be \ | |
26 ignored."), | |
27 required=False) | |
22 | 28 |
23 expire_options = forms.ChoiceField( | 29 expire_options = forms.ChoiceField( |
24 choices=EXPIRE_CHOICES, | 30 choices=EXPIRE_CHOICES, |
25 initial=EXPIRE_DEFAULT, | 31 initial=EXPIRE_DEFAULT, |
26 label=_(u'Expires'), | 32 label=_(u'Expires'), |
27 ) | 33 ) |
28 | 34 |
29 def __init__(self, request, *args, **kwargs): | 35 def __init__(self, *args, **kwargs): |
36 request = kwargs.pop('request') | |
30 super(SnippetForm, self).__init__(*args, **kwargs) | 37 super(SnippetForm, self).__init__(*args, **kwargs) |
31 self.request = request | 38 self.request = request |
32 | 39 |
33 try: | 40 try: |
34 if self.request.session['userprefs'].get('display_all_lexer', | 41 if self.request.session['userprefs'].get('display_all_lexer', |
40 try: | 47 try: |
41 self.fields['author'].initial = \ | 48 self.fields['author'].initial = \ |
42 self.request.session['userprefs'].get('default_name', '') | 49 self.request.session['userprefs'].get('default_name', '') |
43 except KeyError: | 50 except KeyError: |
44 pass | 51 pass |
52 | |
53 # Make the content field not required (validated in clean()) | |
54 self.fields['content'].required = False | |
55 self.fields['title'].required = True | |
56 | |
57 def clean(self): | |
58 cleaned_data = super(SnippetForm, self).clean() | |
59 file_data = cleaned_data.get('file') | |
60 content = cleaned_data.get('content') | |
61 | |
62 if file_data: | |
63 file_data.open() | |
64 cleaned_data['content'] = file_data.read() | |
65 elif not content: | |
66 # No snippet data specified | |
67 raise forms.ValidationError(_("Please specify some content for \ | |
68 the snippet, either in the content field or by uploading \ | |
69 a file.")) | |
70 | |
71 return cleaned_data | |
45 | 72 |
46 def save(self, parent=None, *args, **kwargs): | 73 def save(self, parent=None, *args, **kwargs): |
47 | 74 |
48 # Set parent snippet | 75 # Set parent snippet |
49 if parent: | 76 if parent: |