Commits

Anonymous committed 5715b7d

Adding login and edit/add article.

Comments (0)

Files changed (12)

relaxlog/settings.py

     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
-    'django.contrib.sites',
+    'django.contrib.admin',
     'django.contrib.markup',
     'weblog'
 )

relaxlog/static/script.js

+$(document).ready(function(){
+  $('.preview').click(function(e){
+    var url = $(this).attr('action');
+    var form = $('form#article');
+    $.post(url, form.serialize(), function(data, textStatus){
+      $('#preview').html(data);
+    });
+    return false;
+  });
+});

relaxlog/static/styles.css

 em { font-style: italic; }
 strong { font-weight: bold; }
 sup { font-size: 12px; line-height: 12px; vertical-align: top; }
+cite { background: #F0F0F0; }
 
 ul, ol, dl { margin: 0 0 20px 32px; }
 ol li { list-style: decimal outside; }
 ul li { list-style: circle outside; }
 
+form { margin: 30px 0; }
+label { float: left; width: 50px; }
+input[type=text] { width: 340px; }
+input[name=date] { width: auto; }
+input[type=submit] { font-weight: bold; }
+textarea { padding: 6px; width: 516px; height: 460px; }
+
+#login label { display: none; }
+#login input[type="text"], #login input[type=password] { width: auto; }
+
 .body img { display: block; margin: 20px auto; }
 
 .navigation { overflow: hidden; width: 100%; }

relaxlog/templates/base.html

     <link rel="stylesheet" href="http://yui.yahooapis.com/2.5.2/build/reset/reset-min.css" type="text/css">
     <link rel="stylesheet" href="{{ MEDIA_URL }}static/styles.css" type="text/css">
     <link rel="stylesheet" href="{{ MEDIA_URL }}static/friendly.css" type="text/css">
+    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
+    <script src="{{ MEDIA_URL }}static/script.js"></script>
     <link rel="alternate" title="Nýjustu færslur" href="/straumar/faerslur/" type="application/atom+xml">
     <link rel="alternate" title="Nýjustu hlekkir" href="/straumar/hlekkir/" type="application/atom+xml">
 </head>

relaxlog/templates/registration/login.html

+{% extends "base.html" %}
+
+{% block content %}
+  <h1>Sesam</h1>
+  <form action="" method="POST" id="login">
+    {{ form.as_p }}
+    <input type="submit" value="Opnist þú">
+  </form>
+{% endblock %}
 from django.conf.urls.defaults import *
 from django.contrib import admin
 
-# admin.autodiscover()
+admin.autodiscover()
 
 urlpatterns = patterns('',
-    (r'^admin/(.*)', admin.site.root),
-    (r'^meira-um/(?P<slug>[-\w]+)/$', 'views.flatpage'),
-    (r'^blogg/', include('weblog.urls')),
+    url(r'^admin/(.*)', admin.site.root),
+    url(r'^meira-um/(?P<slug>[-\w]+)/$', 'views.flatpage'),
+    url(r'^blogg/', include('weblog.urls')),
+    url(r'^accounts/', include('django.contrib.auth.urls')),
 )
 
 from django.conf import settings

relaxlog/weblog/forms.py

+# coding=utf-8
+
+from datetime import date
+from django import forms
+
+class DocumentForm(forms.Form):
+    
+    title = forms.CharField(label=u'Titill')
+    date = forms.DateField(initial=date.today, label=u'Dags.')
+    content = forms.CharField(widget=forms.Textarea, label=u'')
+
+class DocumentAddForm(DocumentForm):
+    
+    slug = forms.CharField(required=False, label=u'Slóð')
+    

relaxlog/weblog/slugify.py

 from htmlentitydefs import name2codepoint
 from django.utils.encoding import smart_unicode
 
-CHAR_DICT ={
+CHAR_MAP = {
     u'á': u'a', 
     u'ð': u'd', 
     u'é': u'e', 
     u'ö': u'o', 
 }
 
-def slugify(s, entities=True, decimal=True, hexadecimal=True, char_dict={}):
+def slugify(s, entities=True, decimal=True, hexadecimal=True):
     
     s = smart_unicode(s)
     
     #character map
-    for k, v in CHAR_DICT.update(char_dict).items():
+    for k, v in CHAR_MAP.items():
         s = s.replace(k, v)
 
     #character entity reference

relaxlog/weblog/templates/weblog/add.html

+{% extends "base.html" %}
+{% load markup %}
+
+{% block title %}{{ block.super }} » Blogg » Ný færsla{% endblock %}
+
+{% block content %}
+  <h1>Ný færsla</h1>
+  <form action="" method="POST" id="article">
+    {{ form.as_p }}
+    <input type="submit" value="Senda">
+    <input type="button" value="Gægjast" class="preview" action="{% url weblog.views.preview %}">
+  </form>
+  <h1>Gægjast</h1>
+  <div id="preview">...</div>
+{% endblock %}

relaxlog/weblog/templates/weblog/preview.html

+{% load markup %}{{ document.content|restructuredtext }}

relaxlog/weblog/urls.py

 
 urlpatterns = patterns('weblog.views',
     (r'^$', 'latest'),
+    (r'^add/$', 'add'),
+    (r'^preview/$', 'preview'),
     (r'^safn/$', 'archive'),
     (r'^(?P<slug>[-\w]+)/$', 'article'),
+    (r'^(?P<slug>[-\w]+)/edit/$', 'edit'),
 )

relaxlog/weblog/views.py

+# coding=utf-8
+
 import datetime
 from couchdb import client
 from django.conf import settings
-from django.http import Http404
+from django.http import Http404, HttpResponseRedirect, HttpResponse
+from django.views.decorators.http import require_POST
+from django.contrib.auth.decorators import login_required
+from django.core.urlresolvers import reverse
+
 from utils import response
+from weblog.forms import DocumentForm, DocumentAddForm
 
 COUNT = 3
-    
+ISO_DATE = '%Y-%m-%d'
+
 def latest(request):
     
     server = client.Server()
     latest_articles = []
     for document in view_results.rows[:COUNT]:
         article = dict(**document.value)
-        article['date'] = datetime.datetime.strptime(document.value['date'], '%Y-%m-%d')
+        article['date'] = datetime.datetime.strptime(document.value['date'], ISO_DATE)
         latest_articles.append(article)
 
     context = {}
     except client.ResourceNotFound:
         raise Http404
     article = dict(**main)
-    article['date'] = datetime.datetime.strptime(main['date'], '%Y-%m-%d')
+    article['date'] = datetime.datetime.strptime(main['date'], ISO_DATE)
     context = {'article': article, }
-    print article
     
     view_results = db.view('articles/by_date', count=2, 
         startkey=main['date'], startkey_docid=main.id)
     
     return response(request, 'weblog/article.html', context)
 
+
 def archive(request):
     
     server = client.Server()
     archive = db.view('articles/by_date').rows
     
     return response(request, 'weblog/archive.html', {'archive': archive})
-    
+
+
+@login_required
+def add(request):
+    if request.method == "POST":
+        form = DocumentAddForm(request.POST)
+        if form.is_valid():
+            data = form.cleaned_data
+            if not data['slug']:
+                import slugify
+                data['slug'] = slugify.slugify(data['title'])
+            server = client.Server()
+            db = server[settings.COUCHDB_DATABASE]
+            _id = data['slug']
+            db[_id] = {
+                'title': data['title'],
+                'date': data['date'].strftime(ISO_DATE),
+                'content': data['content'],
+                'type': 'Article',
+                'status': 'Online',
+            }
+            return HttpResponseRedirect(reverse('weblog.views.article', args=[_id]))
+    else:
+        form = DocumentAddForm()
+    return response(request, 'weblog/add.html', {'form': form })
+
+
+@require_POST
+def preview(request):
+    form = DocumentForm(request.POST)
+    if form.is_valid():
+        document = form.cleaned_data
+    else:
+        return HttpResponse(u'Skjölun ekki lokið')
+    return response(request, 'weblog/preview.html', {'document': document })
+
+
+@login_required
+def edit(request, slug):
+            
+    server = client.Server()
+    db = server[settings.COUCHDB_DATABASE]
+    
+    try:
+        article = db[slug]
+    except client.ResourceNotFound:
+        raise Http404
+    
+    if request.method == "POST":
+        form = DocumentForm(request.POST)
+        if form.is_valid():
+            data = form.cleaned_data
+            article['title'] = data['title']
+            article['content'] = data['content']
+            article['date'] = data['date'].strftime(ISO_DATE)
+            db[article.id] = article
+            return HttpResponseRedirect(reverse('weblog.views.article', args=[slug]))
+    else:
+        article = dict(**article)
+        date = datetime.datetime.strptime(article['date'], ISO_DATE)
+        article['date'] = datetime.date(*date.timetuple()[:3]) # Convert from datetime to date
+        form = DocumentForm(initial=article)
+    
+    return response(request, 'weblog/add.html', {'form': form })
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.