Implemented mandant based blog posts

This commit is contained in:
2016-06-17 22:37:43 +02:00
parent e3ef06a41a
commit c2eede9500
5 changed files with 93 additions and 53 deletions

View File

@@ -10,10 +10,10 @@
{% block body %} {% block body %}
<div id="content-main"> <div id="content-main">
{% if form.errors %} {% if form_bp.errors %}
<div> <div>
<p class="errornote"> <p class="errornote">
{% if form.errors.items|length == 1 %} {% if form_bp.errors.items|length == 1 %}
{% trans "Please correct the error below." %} {% trans "Please correct the error below." %}
{% else %} {% else %}
{% trans "Please correct the errors below." %} {% trans "Please correct the errors below." %}
@@ -22,21 +22,38 @@
{% endif %} {% endif %}
<div class="row"> <div class="row">
<div class="col-md-8"> <div class="col-md-8">
<form class="form-horizontal" action="" method="post">{% csrf_token %} <form class="form-horizontal" action="" method="post">
{% csrf_token %}
<div class="form-group"> <div class="form-group">
{{form.content.errors}} {{form_bp.content.errors}}
<label for="id_content" class="col-sm-4 control-label required">{% trans 'Content' %}</label> <label for="id_content" class="col-sm-4 control-label required">
{% trans 'Content' %}
</label>
<div class="col-sm-5"> <div class="col-sm-5">
<textarea class="form-control" maxlength="256" rows="2" id="id_content" name="content"></textarea> <textarea class="form-control" maxlength="256" rows="2"
id="id_content" name="content"></textarea>
{% if has_choices %}
{{ form_mandants }}
{% endif %}
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
<div class="col-sm-offset-2 col-sm-10"> <div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">{% trans 'Sent' %}</button> <button type="submit" class="btn btn-default">
{% trans 'Sent' %}
</button>
</div> </div>
</div> </div>
</form> </form>
</div> </div>
</div> </div>
{% if debug %}
<div class="row">
<div class="col-md-5">
<h2 class="form-signin-heading">{% trans 'Debug' %}</h2>
{{ debug }}
</div>
</div>
{% endif %}
</div> </div>
{% endblock %} {% endblock %}

View File

@@ -18,7 +18,7 @@ You should have received a copy of the GNU General Public License
along with TipPy. If not, see <http://www.gnu.org/licenses/>. along with TipPy. If not, see <http://www.gnu.org/licenses/>.
""" """
from tipp.models import Team, Match, Tipp, Score, Mandant, RelUserMandant, Competition, Post, UserProfile from tipp.models import *
from django.contrib import admin from django.contrib import admin
class PostAdmin(admin.ModelAdmin): class PostAdmin(admin.ModelAdmin):
@@ -41,4 +41,5 @@ admin.site.register(Score)
admin.site.register(RelUserMandant) admin.site.register(RelUserMandant)
admin.site.register(Competition) admin.site.register(Competition)
admin.site.register(Post, PostAdmin) admin.site.register(Post, PostAdmin)
admin.site.register(RelPostMandant)

View File

@@ -22,7 +22,7 @@ from django import forms
from django.forms import ModelForm from django.forms import ModelForm
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.core.files.images import get_image_dimensions from django.core.files.images import get_image_dimensions
from tipp.models import Match, Competition, Post, UserProfile from tipp.models import Match, Competition, Post, UserProfile, Mandant, RelUserMandant
class NumberInput(forms.TextInput): class NumberInput(forms.TextInput):
input_type = 'number' input_type = 'number'
@@ -48,6 +48,13 @@ class BlogpostForm(ModelForm):
model = Post model = Post
fields = ['content'] fields = ['content']
class MandantsForm(forms.Form):
mandants = forms.MultipleChoiceField(
label= "Mandanten",
widget=forms.CheckboxSelectMultiple()
)
class UserForm(forms.ModelForm): class UserForm(forms.ModelForm):
class Meta: class Meta:
model = User model = User

View File

@@ -123,7 +123,6 @@ class Post(models.Model):
published = models.BooleanField(default=True) published = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User) author = models.ForeignKey(User)
mandant = models.ForeignKey(Mandant)
class Meta: class Meta:
ordering = ['-created'] ordering = ['-created']
@@ -131,4 +130,12 @@ class Post(models.Model):
def __unicode__(self): def __unicode__(self):
return u'%s' % self.created return u'%s' % self.created
class RelPostMandant(models.Model):
post = models.ForeignKey(Post)
mandant = models.ForeignKey(Mandant)
class Meta:
unique_together = ("post", "mandant")
def __unicode__(self):
return (str(self.post) + " -> " + str(self.mandant))

View File

@@ -72,7 +72,6 @@ def profile(request, pk):
debug = [] debug = []
debug.append('avatar: ' + str(img)) debug.append('avatar: ' + str(img))
# If it's a HTTP POST, we're interested in processing form data.
if request.method == 'POST': if request.method == 'POST':
user_form = UserForm(data=request.POST, instance=user) user_form = UserForm(data=request.POST, instance=user)
profile_form = UserProfileForm(data=request.POST, instance=profile) profile_form = UserProfileForm(data=request.POST, instance=profile)
@@ -84,10 +83,8 @@ def profile(request, pk):
profile = profile_form.save(commit=False) profile = profile_form.save(commit=False)
profile.user = user profile.user = user
# Did the user provide a profile picture?
if 'avatar' in request.FILES: if 'avatar' in request.FILES:
profile.avatar = request.FILES['avatar'] profile.avatar = request.FILES['avatar']
# Now we save the UserProfile model instance.
profile.save() profile.save()
# create thumbnail # create thumbnail
@@ -106,16 +103,11 @@ def profile(request, pk):
for item in request.POST: for item in request.POST:
debug.append(str(item) + " -> " + str(request.POST[item])) debug.append(str(item) + " -> " + str(request.POST[item]))
# Invalid form or forms - mistakes or something else?
# Print problems to the terminal.
# They'll also be shown to the user.
else: else:
print user_form.errors, profile_form.errors print user_form.errors, profile_form.errors
return redirect( '/accounts/profile/' + str(user.id) ) return redirect( '/accounts/profile/' + str(user.id) )
# Not a HTTP POST, so we render our form using two ModelForm instances.
# These forms will be blank, ready for user input.
else: else:
user_form = UserForm( user_form = UserForm(
initial={ 'last_name': user.last_name, initial={ 'last_name': user.last_name,
@@ -398,8 +390,9 @@ def matchday(request, ls, season, matchday, template_name='md.html'):
matches.append(item) matches.append(item)
# get the newest blogposts # get the newest blogposts
pIDs = RelPostMandant.objects.filter(mandant__in=mandants).values_list('post', flat=True)
posts = [] posts = []
for post in Post.objects.filter(published=True)[:1]: for post in Post.objects.filter(published=True, id__in=pIDs)[:1]:
try: try:
avatar = UserProfile.objects.get(user_id=post.author_id).avatar.name avatar = UserProfile.objects.get(user_id=post.author_id).avatar.name
except: except:
@@ -478,8 +471,13 @@ def charts(request, ls, season, pos='default', template_name='charts.html'):
@login_required @login_required
def blogindex(request, page): def blogindex(request, page):
# get the blog posts that are published # get the blog posts that are published
# and related to mandant
mandants = RelUserMandant.objects.filter(user=request.user).values_list('mandant', flat=True)
posts = RelPostMandant.objects.filter(mandant__in=mandants).values_list('post', flat=True)
post_list = [] post_list = []
for post in Post.objects.filter(published=True): for post in Post.objects.filter(published=True, id__in=posts):
try: try:
avatar = UserProfile.objects.get(user_id=post.author_id).avatar.name avatar = UserProfile.objects.get(user_id=post.author_id).avatar.name
except: except:
@@ -507,52 +505,62 @@ def blogindex(request, page):
@login_required @login_required
def newBlogpost(request): def newBlogpost(request):
""" debug = ''
if this is a POST request we need to process the form data ms = Mandant.objects.filter(
""" id__in=RelUserMandant.objects.filter(user=request.user).values_list('mandant', flat=True)
if request.method == 'POST': )
# create form instance and populate it with data from the request choices = []
form = BlogpostForm(request.POST) for m in ms:
# check whether it's valid: choices.append((m.name, m.description))
if form.is_valid():
data = form.cleaned_data has_choices = False
p = Post(author_id=request.user.id, content=data['content']) if ms.count() > 1:
has_choices = True
if request.method == "POST":
form_bp = BlogpostForm(request.POST)
if form_bp.is_valid():
p = Post(author_id=request.user.id, content=form_bp.cleaned_data['content'])
p.save() p.save()
# ... if has_choices is True:
# redirect to a new URL: form_mandant = MandantsForm(request.POST)
return redirect( '/blog/1') form_mandant.fields["mandants"].choices = choices
# if a GET (or any other method) we'll create a blank form if form_mandant.is_valid():
else: for m in form_mandant.cleaned_data['mandants']:
blogpostForm = BlogpostForm() r = RelPostMandant(mandant=Mandant.objects.get(name=m), post=p)
return render(request, 'newblogpost.html', { r.save()
'form': blogpostForm, else:
'ls': get_current_ls(), r = RelPostMandant(mandant=Mandant.objects.get(name=ms[0]), post=p)
'season': get_current_season() r.save()
})
return redirect( '/blog/1')
blogpostForm = BlogpostForm()
form_mandant = MandantsForm()
form_mandant.fields["mandants"].choices = choices
return render(request, 'newblogpost.html', {
#'debug': debug,
'form_bp': blogpostForm,
'form_mandants': form_mandant.as_table(),
'has_choices': has_choices,
'ls': get_current_ls(),
'season': get_current_season()
})
def logout(request): def logout(request):
"""
Log users out and re-direct them to the main page.
"""
logout(request) logout(request)
return HttpResponseRedirect('/') return HttpResponseRedirect('/')
def get_current_md(ls): def get_current_md(ls):
"""
get current matchday()
returns dict with keys
['groupName']
['groupOrderID']
['groupID']
"""
try: try:
ol = OpenLiga() ol = OpenLiga()
cur_md = ol.getCurrentGroup(ls) cur_md = ol.getCurrentGroup(ls)
except: except:
cur_md = {'groupName': u"1. Spieltag", 'groupOrderID': 1} cur_md = 1
return(cur_md['groupOrderID']) return(cur_md['groupOrderID'])