changeset 183:cdcbfaa65cfe

Catch integrity error when creating bundles If the user has already created a bundle with that name, then the form should raise a ValidationError instead of showing a 500.
author dellsystem <ilostwaldo@gmail.com>
date Sat, 27 Oct 2012 15:41:58 -0400
parents 4a63f5d762a3
children b711f0087709
files apps/bundle/forms.py apps/bundle/views.py
diffstat 2 files changed, 17 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/apps/bundle/forms.py
+++ b/apps/bundle/forms.py
@@ -6,11 +6,24 @@
 class BundleForm(forms.ModelForm):
     class Meta:
         model = Bundle
-        fields = ('name', 'description', 'free_license')
+        fields = ('uploader', 'name', 'description', 'free_license',
+            'octave_format')
 
     file = forms.FileField(help_text=("Upload a plain text file or an \
         archive file."))
 
+    def clean(self):
+        data = self.cleaned_data
+        name_used = Bundle.objects.filter(uploader=data.get('uploader'),
+            name=data.get('name')).exists()
+
+        # If a bundle with this user/name combo exists, raise an error
+        if name_used:
+            raise forms.ValidationError("You have already created a bundle"
+                " with this name.")
+
+        return data
+
 
 class BundleEditForm(forms.ModelForm):
     """
--- a/apps/bundle/views.py
+++ b/apps/bundle/views.py
@@ -48,12 +48,12 @@
 def index(request):
     if request.method == 'POST':
         post_data = request.POST.copy()
-        bundle = Bundle(uploader=request.user)
-        form = BundleForm(post_data, request.FILES, instance=bundle)
+        post_data['uploader'] = request.user.id
+        form = BundleForm(post_data, request.FILES)
 
         if form.is_valid():
             file = request.FILES.get('file')
-            form.save()
+            bundle = form.save()
 
             bundle.file_name = file.name
             bundle.save()