Exemple #1
0
def post_create(request):
    """Route Create Post."""
    errors = ''
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
        else:
            errors = "Cannot save the post"
    else:
        form = PostForm()
    context = {"form": form, "errors": errors}
    return render(request, "main/post_create.html", context=context)
Exemple #2
0
def post_create(request):
    """Route Create Post."""
    errors = ''
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("posts_all")
        else:
            errors = "Не возможно сохранить пост."
    else:
        form = PostForm()
    context = {"form": form, "errors": errors}
    return render(request, "main/post_create.html", context=context)
Exemple #3
0
def index(request):
	latest_post_list = Post.objects.order_by('-created_at')
	if request.method == 'POST':
		form = PostForm(request.POST)
		if form.is_valid():
			form.save()
			return redirect('/blog/')
	else:
		form = PostForm()
	context = {
		'latest_post_list': latest_post_list,
		'form': form
	}
	return render(request, 'main/index.html', context)
Exemple #4
0
def post_admin(request):

    posts = Post.objects.all().order_by('-date_posted')

    context = {"posts": posts}

    if request.method == 'POST':

        id = request.POST.get('id')

        if id:

            post = Post.objects.get(id=id)
            form = PostForm(request.POST, request.FILES, instance=post)

        else:

            form = PostForm(request.POST, request.FILES)

        if form.is_valid():
            post = form.save()
            context['message'] = "Your post has been saved"
        else:
            context['message'] = form.errors

    return render(request, 'post-admin.html', context)
Exemple #5
0
def post_update(request, post_id):
    """Update Posts."""
    err = ""
    pst = get_object_or_404(Post, pk=post_id)

    if request.method == "POST":
        form = PostForm(instance=pst, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect("posts_all")
        else:
            err = "Не возможно обновить пост."
    else:
        form = PostForm(instance=pst)
    context = {"form": form, "err": err}
    return render(request, "main/post_update.html", context=context)
Exemple #6
0
def new_post(request):
    if request.method == 'POST':
        post_form = PostForm(request.POST, request.FILES)
        new_postt = post_form.save(commit=False)
        new_postt.user = request.user
        new_postt.save()
        categories = request.POST.getlist("category")
        for cat in categories:
            new_postt.category.add(cat)
        tagss = request.POST.getlist("tag")
        for ta in tagss:
            new_postt.category.add(ta)
        my_tags = request.POST.get("my_tags")
        my_tags = my_tags.strip()
        my_tags = my_tags.split(",")
        for ta_g in my_tags:
            n_t = my_models.Tag.objects.create(name=ta_g)
            n_t.save()
            new_postt.tag.add(n_t)
        return HttpResponseRedirect(('{}?post_id=' + str(new_postt.id)).format(
            reverse('post', kwargs={})))
    else:
        post_form = PostForm()
        return render(request, 'main/new_post.html', {
            'parts': my_models.Part.objects.all(),
            "post_form": post_form,
        })
Exemple #7
0
def create_post(request):
    form = PostForm(request.POST)
    if form.is_valid():
        post = form.save()
        return redirect('index')
    else:
        message = form.errors
        return render(request, 'index.html', {'message': message})
Exemple #8
0
def create_post(request):
    form = PostForm(request.POST, request.FILES)
    if form.is_valid():
        post = form.save()
        message = 'Your post has been saved'
    else:
        message = form.errors

    return render(request, 'post_admin.html', {'message': message})
Exemple #9
0
def new(request):
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES, instance=Post.default())
        if form.is_valid():
            post = form.save()
            return redirect(view, post.id)
    else:
        form = PostForm()
    context = RequestContext(request, {'form': form})
    return render_to_response('new.html', context)
Exemple #10
0
def add_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post_item = form.save(commit=False)
            post_item.author = request.user
            post_item.save()
            return redirect('post_view', pk=post_item.pk)
    else:
        form = PostForm(instance=Post())
    return render(request, 'post_edit.html', {'form': form, 'action': 'add'})
Exemple #11
0
def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('main.views.post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'main/post_edit.html', {'form': form})
Exemple #12
0
def post_new(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save()
            post.save()
            messages.info(request, 'Your post is added successfully!')

            return redirect('postlist')
    else:
        form = PostForm()
    return render(request, 'main/create or edit post.html', {'form': form})
Exemple #13
0
def post_update(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save()
            post.save()
            messages.info(request, 'Your post is updated successfully!')
            return redirect('postlist')
    else:
        form = PostForm(instance=post)
    return render(request, 'main/create or edit post.html', {'form': form})
Exemple #14
0
def new(request):
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES, instance=Post.default())
        if form.is_valid():
            post = form.save()
            return redirect(view, post.id)
    else:
        form = PostForm()
    context = RequestContext(request, {
        'form': form
    })
    return render_to_response('new.html', context)
Exemple #15
0
def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'main/post_edit.html', {'form': form})
Exemple #16
0
def post_add(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save()
            return redirect('main_page')
    else:
        form = PostForm()
    return render(
        request,
        'post_add.html',
        {'form': form}
    )
Exemple #17
0
def postform(request):
    if request.method == 'POST':
        post = PostForm(request.POST, request.FILES)

        if post.is_valid():
            myPost = post.save(commit=False)
            myPost.created_at = timezone.now()
            myPost.save()
            return redirect('/')

    else:  # blank form
        post = PostForm()
        context = {'form': post}
        return render(request, 'postform.html', context)
Exemple #18
0
def view(request, post_id):
    post = get_object_or_404(Post, id=int(post_id), active=True, parent=None)
    if request.method == 'POST':
        form = PostForm(request.POST,
                        request.FILES,
                        instance=Post.default(parent=post))
        if form.is_valid():
            resp = form.save()
            form = PostForm()
            post.last_resp_at = resp.created_at
            post.save()
    else:
        form = PostForm()
    context = RequestContext(request, {'post': post, 'form': form})
    return render_to_response('view.html', context)
Exemple #19
0
def view(request, post_id):
    post = get_object_or_404(Post, id=int(post_id), active=True, parent=None)
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES,
                        instance=Post.default(parent=post))
        if form.is_valid():
            resp = form.save()
            form = PostForm()
            post.last_resp_at = resp.created_at
            post.save()
    else:
        form = PostForm()
    context = RequestContext(request, {
        'post': post,
        'form': form
    })
    return render_to_response('view.html', context)
Exemple #20
0
def edit(request, post_id):
    post = get_object_or_404(Post, id=int(post_id), active=True)
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES, instance=post)
        if form.is_valid():
            old = Post.objects.get(id=post.id)
            old.id = None
            old.active = False
            old.save()
            post = form.save(commit=False)
            post.old_post = old
            post.updated_at = timezone.now()
            post.save()
            return redirect(view, post.thread.id)
    else:
        form = PostForm(instance=post)
    context = RequestContext(request, {'post': post, 'form': form})
    return render_to_response('edit.html', context)
Exemple #21
0
def add_post(request):
    ImageFormSet = modelformset_factory(Image, form=ImageForm, max_num=1)
    if request.method == 'POST':
        post_form = PostForm(request.POST)
        formset = ImageFormSet(request.POST,
                               request.FILES,
                               queryset=Image.objects.none())
        if post_form.is_valid() and formset.is_valid():
            post = post_form.save()

            for form in formset.cleaned_data:
                image = form['image']
                Image.objects.create(image=image, post=post)
            return redirect(post.get_absolute_url())
    else:
        post_form = PostForm()
        formset = ImageFormSet(queryset=Image.objects.none())
    return render(request, 'add-post.html', locals())
Exemple #22
0
def create_post(request, course_name_slug, forum_name_slug):
    # find lecture object
    try:
        forum = Forum.objects.get(slug=forum_name_slug)
    except Forum.DoesNoExist:
        forum = None

    try:
        course = Course.objects.get(slug=course_name_slug)
    except Course.DoesNotExist:
        course = None

    if course is None or forum is None:
        return redirect('/main/forum/<slug:course_name_slug>/<slug:forum_name_slug/')

    form = PostForm()

    if request.method == 'POST':
        print("after post")
        form = PostForm(request.POST)
        # If input is valid
        if form.is_valid():
            # Save the form
            post = form.save(commit=False)
            post.forum = forum
            post.user = request.user
            # save 1 creates id
            post.save()
            # save 2 uodates slug
            post.save()

            # return redirect('/main/course/<slug:course_name_slug>/<slug:lecture_name_slug>/')
            return redirect(reverse('main:forum',
                                    kwargs={'course_name_slug': course_name_slug,
                                            'forum_name_slug': forum_name_slug}))
        else:
            print(form.errors)

    # return render(request, 'main/course/<slug:course_name_slug>/<slug:lecture_name_slug>/', {'form': form})
    return redirect(reverse('main:forum',
                            kwargs={'course_name_slug': course_name_slug,
                                    'forum_name_slug': forum_name_slug}))
Exemple #23
0
def new_post(request):
    posted = False
    if request.method == 'POST':
        post_form = PostForm(request.POST)
        
        if post_form.is_valid():
            post = post_form.save(commit = False)
            post.op = request.user
            post.save()
            posted=True
        else:
            print(post_form.errors)
    else:
        post_form = PostForm()
        
    context_dict = {}
    context_dict['post_form'] = post_form
    context_dict['posted'] = posted
    
    response = render(request, 'main/newpost.html', context_dict)
    return response
Exemple #24
0
def edit_post(request, pk):
    post_item = get_object_or_404(Post, pk=pk)
    if post_item.author != request.user:
        raise ValidationError(
            'You are not the owner of the post',
            code='error.not.post.owner',
        )
    if request.method == 'POST':
        post_form = PostForm(request.POST)
        if post_form.is_valid():
            new_post_item = post_form.save(commit=False)
            post_item.title = new_post_item.title
            post_item.text = new_post_item.text
            post_item.save()
            return redirect('post_view', pk=post_item.pk)
    else:
        post_form = PostForm(instance=post_item)
    return render(request, 'post_edit.html', {
        'form': post_form,
        'action': 'edit'
    })
Exemple #25
0
def add(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            spk = form.save(commit=False)
            now = datetime.datetime.now()
            spk.time = now
            spk.save()
            form = PostForm()
            return render(request, 'main/add.html', {
                'form': form,
                'ans': 'Добавлено!'
            })
        else:
            return render(request, 'main/add.html', {
                'form': form,
                'ans': 'Форма не валидна'
            })
    else:
        form = PostForm()
        return render(request, 'main/add.html', {'form': form})
Exemple #26
0
def update_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.user == post.user:
        ImageFormSet = modelformset_factory(Image, form=ImageForm, max_num=1)
        post_form = PostForm(request.POST or None, instance=post)
        formset = ImageFormSet(request.POST or None,
                               request.FILES or None,
                               queryset=Image.objects.filter(post=post))
        if post_form.is_valid() and formset.is_valid():
            post = post_form.save()

            for form in formset:
                image = form.save(commit=False)
                image.post = post
                image.save()
                return redirect(post.get_absolute_url())
        else:
            return render(request, 'update-post.html', locals())
    else:
        # return HttpResponse('<h1>403 Forbidden<h/1>')
        return render(request, 'update-post.html', locals())
Exemple #27
0
def edit(request, post_id):
    post = get_object_or_404(Post, id=int(post_id), active=True)
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES, instance=post)
        if form.is_valid():
            old = Post.objects.get(id=post.id)
            old.id = None
            old.active = False
            old.save()
            post = form.save(commit=False)
            post.old_post = old
            post.updated_at = timezone.now()
            post.save()
            return redirect(view, post.thread.id)
    else:
        form = PostForm(instance=post)
    context = RequestContext(request, {
        'post': post,
        'form': form
    })
    return render_to_response('edit.html', context)
Exemple #28
0
def homeTitle(request, id):
    # -----------------------------------------
    # -- Formulaire d'ajout -------------------
    # -----------------------------------------

    jlist = list(Lien.objects.all().values_list('hyperlien', flat=True))
    js_data = json.dumps(jlist)
    ReturnLinks(request)

    if request.method == 'POST':
        form = PostForm(request.POST)

        if form.is_valid():
            post = form.save(commit=False)

            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                ip = request.META.get('REMOTE_ADDR')

            post.ip = ip
            post.save()
            form = PostForm()
    else:
        form = PostForm()

    # -----------------------------------------
    # -- Récupération des Posts ---------------
    # -----------------------------------------
    colors = ['#830012', '#F54A00', '#527CFF', '#818386']
    colorsC = 4
    fonts = [
        'noto-sans',
    ]
    fontsC = 1
    datas = []
    posts = []
    numberLine = 10
    statDouble = 85
    statAdd = 60
    timeToLive = 30
    maxOrderer = 2
    maxRandom = 150
    count = 0
    # Permet de ne pas dépasser un toutes les deux lignes

    now2 = datetime.today() - timedelta(seconds=timeToLive)
    postsOrdered = Post.objects.filter(
        Q(date__gt=now2)).order_by("-date")[:maxOrderer]
    postsRandom = Post.objects.filter(Q(valid=True)).order_by("?")[:maxRandom]
    for post in postsOrdered:
        posts.append(post)
    for post in postsRandom:
        posts.append(post)
    total = len(posts)

    # Enregistrement et creation
    for i in range(total - 1):
        count = count + 1
        j = 0

        data = {}
        data['show'] = True
        data['double'] = False
        data['add'] = False
        data['color'] = colors[random.randint(0, colorsC - 1)]
        data['color'] = data['color'].replace('#', '')
        data['font'] = fonts[random.randint(0, fontsC - 1)]
        if i < maxOrderer:
            j = i
        else:
            if i < total - 1:
                j = random.randint(i, total - 1)
            else:
                j = i

        data['text'] = posts[j].text
        data['id'] = posts[j].id
        posts[j].text = posts[i].text
        posts[j].id = posts[i].id

        if i == 3:
            data['double'] = True
        else:
            data['add'] = random.randint(0, 100) > statAdd
            if data['add']:
                data['double'] = False
            else:
                if count > numberLine * 2 and i % numberLine != 9:
                    data['double'] = random.randint(0, 100) > statDouble
                    if data['double']:
                        count = 0

        datas.append(data)

# Gestion des doubles
    for i in range(total - 1):

        if datas[i]['double']:
            datasAdd = []

            if (i == 3):
                datasAdd.append(datas[i])

            if i % numberLine == 0:
                datas[i + 1]['show'] = False
                datasAdd.append(datas[i + 1])
            else:
                datas[i - 1]['show'] = False
                datasAdd.append(datas[i - 1])

            datas[i + numberLine]['show'] = False
            datasAdd.append(datas[i + numberLine])
            if i % numberLine == numberLine - 2:
                datas[i + numberLine - 1]['show'] = False
                datasAdd.append(datas[i + numberLine - 1])
            else:
                datas[i + numberLine + 1]['show'] = False
                datasAdd.append(datas[i + numberLine + 1])

            for data in datasAdd:
                data = copy.copy(data)
                data['show'] = True
            data['add'] = False
            data['double'] = False
            datas.append(data)

        elif datas[i]['add']:
            data = copy.copy(datas[i])
            data['add'] = False

        data['show'] = True
        data['double'] = False
        datas.append(data)

    title = ""
    if id > 0:
        count = Post.objects.filter(id=id).count()
        if count == 1:
            post = Post.objects.get(id=id)
            if post:
                title = post.text

    return render(request, 'main/home.html.twig', locals())