~widelands-dev/widelands-website/update_beautifulsoup4

« back to all changes in this revision

Viewing changes to wlmaps/forms.py

  • Committer: Shevonar
  • Date: 2012-04-24 21:14:22 UTC
  • mto: This revision was merged to the branch mainline in revision 330.
  • Revision ID: infomh@anmaruco.de-20120424211422-d80y5yd8x9q9gzpx
Maps modul reworked and adjusted to new style.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/env python -tt
2
2
# encoding: utf-8
3
3
 
 
4
import Image
 
5
from cStringIO import StringIO
 
6
 
4
7
from django import forms
5
 
 
6
 
class UploadMapForm(forms.Form):
7
 
    mapfile = forms.FileField()
8
 
    comment = forms.CharField(required=False)
9
 
 
 
8
from django.forms import ModelForm, ValidationError
 
9
 
 
10
from settings import WIDELANDS_SVN_DIR, MEDIA_ROOT
 
11
 
 
12
from wlmaps.models import Map
 
13
from widelandslib.map import WidelandsMap, WlMapLibraryException
 
14
 
 
15
 
 
16
class UploadMapForm(ModelForm):
 
17
    class Meta:
 
18
        model = Map
 
19
        fields = ['file', 'uploader_comment']
 
20
 
 
21
 
 
22
    def clean(self):
 
23
        cleaned_data = super(UploadMapForm, self).clean()
 
24
 
 
25
        file = cleaned_data.get('file')
 
26
        if not file:
 
27
            # no clean file => abort
 
28
            return cleaned_data
 
29
 
 
30
        mapdata = file.read()
 
31
        wlmap = WidelandsMap()
 
32
        try:
 
33
            wlmap.load(StringIO(mapdata))
 
34
        except WlMapLibraryException:
 
35
            raise forms.ValidationError("The map file is invalid.")
 
36
 
 
37
        if Map.objects.filter(name = wlmap.name):
 
38
            raise forms.ValidationError("Map with the same name already exists.")
 
39
 
 
40
        cleaned_data['file'].name = "%s/wlmaps/maps/%s.wmf" % (MEDIA_ROOT, wlmap.name)
 
41
 
 
42
        # Create the minimap
 
43
        minimap = wlmap.make_minimap(WIDELANDS_SVN_DIR)
 
44
        minimap_path = "%s/wlmaps/minimaps/%s.png" % (MEDIA_ROOT, wlmap.name)
 
45
        minimap_url = "/wlmaps/minimaps/%s.png" % wlmap.name
 
46
        minimap_image = Image.fromarray(minimap)
 
47
        minimap_image.save(minimap_path)
 
48
        # TODO: handle filesystem errors
 
49
 
 
50
        # Add information to the map
 
51
        self.instance.name = wlmap.name
 
52
        self.instance.author = wlmap.author
 
53
        self.instance.w = wlmap.w
 
54
        self.instance.h = wlmap.h
 
55
        self.instance.nr_players = wlmap.nr_players
 
56
        self.instance.descr = wlmap.descr
 
57
        self.instance.minimap = minimap_url
 
58
        self.instance.world_name = wlmap.world_name
 
59
 
 
60
        return cleaned_data
 
61
 
 
62
 
 
63
    def save(self, *args, **kwargs):
 
64
        map = super(UploadMapForm, self).save(*args, **kwargs)
 
65
        if not kwargs['commit'] == False:
 
66
            map.save()
 
67
        return map