blog

Saving changes for pull

Author
Maarten 'Vngngdn' Vangeneugden
Date
March 25, 2018, 3:31 a.m.
Hash
8063eeae2b810b99b8087172c242dda7728250a2
Parent
a63d7baae9a651b3327347bc7a48dae00c2e6b39
Modified files
models.py
views.py

models.py

4 additions and 1 deletion.

View changes Hide changes
1
1
from django.utils import translation
2
2
from django.template.defaultfilters import slugify
3
3
from django.db import models
4
4
import datetime
5
5
import os
6
6
7
7
def post_title_directory(instance, filename):
8
8
    """ Files will be uploaded to MEDIA_ROOT/blog/<year of publishing>/<blog
9
9
    title>
10
10
    The blog title is determined by the text before the first period (".") in
11
11
    the filename. So if the file has the name "Trains are bæ.en.md", the file
12
12
    will be stored in "blog/<this year>/Trains are bæ". Name your files
13
13
    properly!
14
14
    It should also be noted that all files are stored in the same folder if they
15
15
    belong to the same blogpost, regardless of language. The titles that are
16
16
    displayed to the user however, should be the titles of the files themselves,
17
17
    which should be in the native language. So if a blog post is titled
18
18
    "Universities of Belgium", its Dutch counterpart should be titled
19
19
    "Universiteiten van België", so the correct title can be derived from the
20
20
    filename.
21
21
22
22
    Recommended way to name the uploaded file: "<name of blog post in language
23
23
    it's written>.org". This removes the maximum amount of redundancy (e.g. the
24
24
    language of the file can be derived from the title, no ".fr.org" or something
25
25
    like that necessary), and can directly be used for the end user (the title
26
26
    is what should be displayed).
27
27
    """
28
28
    english_file_name = os.path.basename(instance.english_file.name) # TODO: Test if this returns the file name!
29
29
    english_title = english_file_name.rpartition(".")[0]
30
30
    year = datetime.date.today().year
31
31
32
32
    return "blog/{0}/{1}/{2}".format(year, english_title, filename)
33
33
34
34
class Post(models.Model):
35
35
    """ Represents a blog post. The title of the blog post is determnined by the name
36
36
    of the files.
37
37
    A blog post can be in 5 different languages: German, Spanish, English, French,
38
38
    and Dutch. For all these languages, a seperate field exists. Thus, a
39
39
    translated blog post has a seperate file for each translation, and is
40
40
    seperated from Django's internationalization/localization system.
41
41
    Only the English field is mandatory. The others may contain a value if a
42
42
    translated version exists, which will be displayed accordingly.
43
43
    """
44
44
    published = models.DateTimeField(auto_now_add=True)
45
45
    english_file = models.FileField(upload_to=post_title_directory, unique=True, blank=False)
46
46
    dutch_file = models.FileField(upload_to=post_title_directory, blank=True)
47
47
    french_file = models.FileField(upload_to=post_title_directory, blank=True)
48
48
    german_file = models.FileField(upload_to=post_title_directory, blank=True)
49
49
    spanish_file = models.FileField(upload_to=post_title_directory, blank=True)
50
50
    # Only the English file can be unique, because apparantly, there can't be
51
51
    # two blank fields in a unique column. Okay then.
52
52
53
53
    def __str__(self):
54
54
        return self.slug("en")
55
55
56
56
    def slug(self, language_code=translation.get_language()):
57
57
        """ Returns a slug of the requested language, or None if no version exists in that language. """
58
58
        possibilities = {
59
59
            "en" : self.english_file,
60
60
            "de" : self.german_file,
61
61
            "nl" : self.dutch_file,
62
62
            "fr" : self.french_file,
63
63
            "es" : self.spanish_file,
64
64
            }
65
65
        if possibilities[language_code]:
66
66
            return slugify(os.path.basename(possibilities[language].name).rpartition(".")[0])
67
67
        else:
68
68
            return None
69
69
70
70
class Comment(models.Model):
71
71
    """ Represents a comment on a blog post.
72
72
73
73
    Comments are not linked to an account or anything, I'm trusting the
74
74
    commenter that he is honest with his credentials. That being said:
75
75
    XXX: Remember to put up a notification that comments are not checked for
76
76
    identity, and, unless verified by a trustworthy source, cannot be seen as
77
77
    being an actual statement from the commenter.
78
78
    Comments are linked to a blogpost, and are not filtered by language. (So a
79
79
    comment made by someone reading the article in Dutch, that's written in
80
80
    Dutch, will show up (unedited) for somebody whom's reading the Spanish
81
81
    version.
82
82
    XXX: Remember to notify (tiny footnote or something) that comments showing
83
83
    up in a foreign language is by design, and not a bug.
84
84
    """
85
85
    date = models.DateTimeField(auto_now_add=True)
86
86
    name = models.CharField(max_length=64)
87
87
    text = models.TextField()
88
88
    post = models.ForeignKey(Post) # TODO: Finish this class and the shit...
89
-
+
89
        Post,
+
90
        on_delete=Models.CASCADE,
+
91
        null=False) # TODO: Finish this class and the shit...
+
92

views.py

1 addition and 0 deletions.

View changes Hide changes
1
1
import subprocess
2
2
3
3
from django.utils.translation import ugettext as _
4
4
from django.shortcuts import get_object_or_404, render # This allows to render the template with the view here. It's pretty cool and important.
5
5
from django.http import HttpResponseRedirect, HttpResponse
6
6
from django.core.urlresolvers import reverse # Why?
7
7
from django.template import loader # This allows to actually load the template.
8
8
from django.contrib.auth.decorators import login_required
9
9
from django.contrib.auth import authenticate, login
10
10
from .models import Post
11
11
from django.core.exceptions import ObjectDoesNotExist
12
12
from django.utils import translation
13
13
14
14
GERMAN = "de"
15
15
SPANISH = "es"
16
16
FRENCH = "fr"
17
17
DUTCH = "nl"
18
18
ENGLISH = "en"
19
19
20
20
# FIXME: Remove this template trash. THIS IS A VIEW, NOT A FUCKING TEMPLATE FFS
21
21
context = {
22
22
    'materialDesign_color': "green",
23
23
    'materialDesign_accentColor': "purple",
24
24
    'navbar_title': "Blog",
25
25
    'navbar_fixed': True,
26
26
    'navbar_backArrow': True,
27
27
    #'footer_title': "Maarten's blog",
28
28
    #'footer_description': "My personal scribbly notepad.",
29
29
    #'footer_links': footer_links,
30
30
    }
31
31
32
32
def org_to_html(file_path):
33
33
    """ Converts the given org formatted file to HTML.
34
34
    This function directly returns the resulting HTML code. This function uses
35
35
    the amazing Haskell library Pandoc to convert the file (and takes care
36
36
    of header id's and all that stuff).
37
37
    """
38
38
    # FIXME: Remove hardcoded link to media. Replace with media tag!
39
39
    return subprocess.check_output(["pandoc", "--from=org", "--to=html", "/srv/django/website/media/"+file_path])
40
40
41
41
def get_available_post_languages(post):
42
42
    """ Returns the language codes for which a blog post exists. This function
43
43
    always returns English (because that field mustn't be empty).
44
44
    So say a blog post has an English, Dutch and French version (which means
45
45
    english_file, french_file and dutch_file aren't empty), the function will return {"en",
46
46
    "fr", "nl"}. """
47
47
    available_languages = {ENGLISH}
48
48
    if post.german_file is not None:
49
49
        available_languages.add(GERMAN)
50
50
    if post.spanish_file is not None:
51
51
        available_languages.add(SPANISH)
52
52
    if post.french_file is not None:
53
53
        available_languages.add(FRENCH)
54
54
    if post.dutch_file is not None:
55
55
        available_languages.add(DUTCH)
56
56
    return available_languages
57
57
58
58
def get_preferred_post_language(post, language):
59
59
    """ Returns the post language file that best suits the given language. This
60
60
    is handy if you know what language the user prefers, but aren't sure whether
61
61
    you can provide that language. This function will try to provide the file
62
62
    for that language, or return English if that's not possible. """
63
63
    if language == GERMAN and post.german_file is not None:
64
64
        return post.german_file
65
65
    if language == SPANISH and post.spanish_file is not None:
66
66
        return post.spanish_file
67
67
    if language == FRENCH and post.french_file is not None:
68
68
        return post.french_file
69
69
    if language == DUTCH and post.dutch_file is not None:
70
70
        return post.dutch_file
71
71
    return post.english_file  # Returned if all other choices wouldn't be satisfactory, or the requested language is English.
72
72
73
73
def index(request):
74
74
    template = "blog/index.html"
75
75
    posts = Post.objects.all()
76
76
    language = translation.get_language()
77
77
78
78
    post_links = []
79
79
    for post in posts:
80
80
        blog_file = get_preferred_post_language(post, language)
81
81
        # TODO: Find a cleaner way to determine the title. First and foremost:
82
82
        # If the language differs from English, the other language file needs to
83
83
        # be loaded. Plus: look for a built in function to remove the full path
84
84
        # and only return the file name.
85
85
        title = (blog_file.name.rpartition("/")[2]).rpartition(".")[0]
86
86
        human_title = title.replace("_"," ")
87
87
        date = post.published
88
88
        blog_text = org_to_html(blog_file.name)
89
89
        # TODO: The link can possibly be reversed in the DTL using the title, which is actually
90
90
        # a cleaner way to do it. Investigate.
91
91
        link = reverse("blog-post-language", args=[language, post.slug(language)])
92
92
        post_links.append([title, date, blog_text, link])
93
93
94
94
    context = {
95
95
            'posts': post_links,
96
96
            'materialDesign_color': "brown",
97
97
            'materialDesign_accentColor': "yellow",
98
98
            'navbar_title': _("Notepad from a student"),
99
99
            'navbar_backArrow': True,
100
100
            }
101
101
    return render(request, template, context)
102
102
103
103
def post(request, post_slug, language=None):
104
104
    if language is not None:
105
105
        if translation.check_for_language(language):
106
106
            translation.activate(language)
107
107
            request.session[translation.LANGUAGE_SESSION_KEY] = language
108
108
        return post(request, post_slug)
109
109
    else:
110
110
        language = translation.get_language()
111
111
112
112
    template = "blog/post.html"
113
113
    posts = Post.objects.all()
114
114
    for post in posts:
+
115
    for post in posts:
115
116
        if post.slug(language) == post_slug:
116
117
            blog_file = get_preferred_post_language(post, language)
117
118
            blog_text = org_to_html(blog_file.name)
118
119
            context = {
119
120
                'human_post_title': blog_file.name.replace("_"," "),
120
121
                'materialDesign_color': "brown",
121
122
                'materialDesign_accentColor': "yellow",
122
123
                'article': blog_text,
123
124
                'title': str(blog_file),
124
125
                'navbar_title': ((blog_file.name.rpartition("/")[2]).rpartition(".")[0]).replace("_"," "),
125
126
                'navbar_backArrow': True,
126
127
                }
127
128
            return render(request, template, context)
128
129