Beispiel #1
0
def article_update(request, slug=None):
    user = request.user
    #if not user.is_staff or not user.is_superuser:
    #    raise Http404
    instance = get_object_or_404(Article, slug=slug)
    if instance.author != user:
        raise Http404
    # Para poder actualizar un articulo, su imagen es necesario request.FILES or NOne
    form = ArticleForm(request.POST or None, request.FILES or None, instance=instance)
    if form.is_valid():
        instance = form.save(commit=False)
        # form.instance.author = request.user
        instance.save()
        # message success
        # messages.success(request, "<a href='#'>Item</a>Saved", extra_tags='html_safe')
        messages.success(request, "Tu artículo ha sido actualizado")
        return HttpResponseRedirect(instance.get_absolute_url())
    context = {
        'title': instance.title,
        'instance': instance,
        'form': form,
    }
    if user.is_authenticated():
        context['userprofile'] = user.profile
    return render(request, 'blog/article_form.html', context)
Beispiel #2
0
def edit_one_article(request, article_pk=0):
    try:
        article = Article.objects.get(pk=article_pk,
                                      author=request.user.get_profile())
    except Article.DoesNotExist:
        article = None
    if request.method == 'POST':
        form = ArticleForm(request.POST, instance=article)
        if form.is_valid():
            art = form.save(commit=False)
            art.author = request.user.get_profile()
            art.save()

        messages.add_message(request, messages.INFO,
                             _('Your edits have been saved successfully.'))

        return render_to_response('blog/edit_one_article.html', {
            'article_pk': article_pk,
            'form': form
        },
                                  context_instance=RequestContext(request))
    else:
        try:
            article = Article.objects.get(pk=article_pk,
                                          author=request.user.get_profile())
        except Article.DoesNotExist:
            form = ArticleForm()

        return render_to_response('blog/edit_one_article.html', {
            'article_pk': article_pk,
            'form': form
        },
                                  context_instance=RequestContext(request))
Beispiel #3
0
def edit_one_article(request, article_pk=0):
	try:
		article = Article.objects.get(pk=article_pk, author=request.user.get_profile())
	except Article.DoesNotExist:
		article = None
	if request.method == 'POST':
		form = ArticleForm(request.POST, instance=article)
		if form.is_valid():
			art = form.save(commit=False)
			art.author = request.user.get_profile()
			art.save()

		messages.add_message(request, messages.INFO, 
			_('Your edits have been saved successfully.'))

		return render_to_response('blog/edit_one_article.html', 
			{'article_pk': article_pk, 'form': form}, 
			context_instance=RequestContext(request))
	else:
		try:
			article = Article.objects.get(pk=article_pk, author=request.user.get_profile())
		except Article.DoesNotExist:	
			form = ArticleForm()

		return render_to_response('blog/edit_one_article.html', 
			{'article_pk': article_pk, 'form': form}, 
			context_instance=RequestContext(request))
Beispiel #4
0
def add_article(request):
    # context = RequestContext(request)
    topic_tags, other_tags = get_tag_lists()
    current_user = request.user

    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            new_article = form.save()
            raw_tags = form.cleaned_data['tags'].split(',')
            if raw_tags:
                for raw_tag in raw_tags:
                    raw_tag = raw_tag.strip().replace(' ', '_').lower()
                    tag_name = urllib.quote(raw_tag)
                    tag, created = Tag.objects.get_or_create(name=tag_name)
                    if created:
                        tag.article_count = 1
                    else:
                        tag.article_count += 1
                    tag.save()
                    tag.articles.add(new_article)
            return redirect(index)
        else:
            print form.errors
    else:
        form = ArticleForm(initial={'author': current_user})

    context = {
        'form': form,
        'topic_tags': topic_tags,
        'other_tags': other_tags,
    }

    return render(request, 'add_article.html', context)
Beispiel #5
0
def edit_article(request, id):
    next = get_next(request)

    try:
        article = Article.objects.get(id=id)
    except ObjectDoesNotExist:
        return HttpResponseRedirect(next)

    if request.method == 'POST':
        if not request.user.is_authenticated(
        ) or not request.user.is_staff or not request.user.is_active:
            return HttpResponseRedirect('/')
        if request.user != article.user:
            return HttpResponseRedirect('/')
        form = ArticleForm(request.POST, instance=article)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(next)
    else:
        form = ArticleForm(instance=article)
    return render_to_response('blog/edit_article.html', {
        'form': form,
        'article': article,
        'next': next,
    },
                              context_instance=RequestContext(request))
Beispiel #6
0
def add_article(request):
	# context = RequestContext(request)
	topic_tags, other_tags = get_tag_lists()
	current_user = request.user

	if request.method == 'POST':
		form = ArticleForm(request.POST)
		if form.is_valid():
			new_article = form.save()
			raw_tags = form.cleaned_data['tags'].split(',')
			if raw_tags:
				for raw_tag in raw_tags:
					raw_tag = raw_tag.strip().replace(' ', '_').lower()
					tag_name = urllib.quote(raw_tag)
					tag, created = Tag.objects.get_or_create(name=tag_name)
					if created:
						tag.article_count=1
					else:
						tag.article_count +=1
					tag.save()
					tag.articles.add(new_article)
			return redirect(index)
		else:
			print form.errors
	else:
		form = ArticleForm(initial={'author': current_user})

	context = {
		'form': form,
		'topic_tags': topic_tags,
		'other_tags': other_tags,
	}

	return render(request, 'add_article.html', context)	
Beispiel #7
0
def articleform(request):
    if request.method == 'POST':  # S'il s'agit d'une requete POST
        form = ArticleForm(request.POST)  # Nous reprenons les donnees

        if form.is_valid(): # Nous verifions que les donnees envoyees sont valides

            # Ici nous pouvons traiter les donnees du formulaire
            #titre       = form.cleaned_data['titre']
            #slug        = form.cleaned_data['slug']
            #auteur      = form.cleaned_data['auteur']
            #contenu     = form.cleaned_data['contenu']
            #date        = form.cleaned_data['date']
            #categorie   = form.cleaned_data['categorie']
            #Sujet = form.cleaned_data['Sujet']
            #message = form.cleaned_data['message']
            #envoyeur = form.cleaned_data['envoyeur']
            #renvoi = form.cleaned_data['renvoi']

            # Nous pourrions ici envoyer l'e-mail grace aux donnees que nous venons de recuperer

            envoi = True
            form.save()

    else: # Si ce n'est pas du POST, c'est probablement une requete GET
        form = ArticleForm()  # Nous creons un formulaire vide
    
    return render(request, 'blog/articleform.html', locals())
Beispiel #8
0
def addArticle(request):
    '''
    添加文章
    :param request:
    :return:
    '''
    if request.method == "GET":
        article_form = ArticleForm()
        cate_list = models.Category.objects.filter(blog__user = request.user)
        tag_list = models.Tag.objects.filter(blog__user = request.user)

        return render(request,"addArticle.html",locals())
    if request.method == "POST":
        article_form = ArticleForm(request.POST)
        if article_form.is_valid():
            title = article_form.cleaned_data.get("title")
            content = article_form.cleaned_data.get("content")
            cate_obj = request.POST.get("cate_list")
            tag_obj_list = request.POST.getlist("tag_list")


            soup = BeautifulSoup (content,'html.parser')
            content_desc = soup.get_text () [:100]
            with transaction.atomic():
                article_obj = models.Article.objects.create(title=title,desc = content_desc,create_time=datetime.datetime.now(),user=request.user,category_id=cate_obj)
                models.ArticleDetail.objects.create(content=content,article=article_obj)

                if tag_obj_list:
                    for i in tag_obj_list:
                        models.Article_Tag.objects.create(article_id=article_obj.id,tag_id=i)

                return HttpResponse("添加成功")
    else:
        return render(request,'addArticle.html',locals())
Beispiel #9
0
def article(request):
    # Create Article
    current_date = date.today()
    if request.method == "POST":
        form = ArticleForm(request.POST)

        if form.is_valid():
            article = form.save(commit=False)
            article.author = request.user
            article.published_date = timezone.now()
            article.save()
            return redirect('blog_details', id=article.id)
        else:
            return render(request, 'post_edit.html', {
                'form': form,
                'date': current_date
            })

    # Viewing an Article
    else:
        form = CommentForm()
        return render(request, 'post_edit.html', {
            'form': form,
            'date': current_date
        })
Beispiel #10
0
def article_add(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        tag = TagForm(request.POST)
        classification = ClassificationForm(request.POST)
        if form.is_valid() and tag.is_valid() and classification.is_valid():
            cd = form.cleaned_data
            cdtag = tag.cleaned_data
            cdclassification = classification.cleaned_data
            tagname = cdtag['tag_name']
            classification_name = cdclassification["classification_name"]
            for taglist in tagname.split():
                Tag.objects.get_or_create(tag_name=taglist.strip())
            if classification_name != "":
                 Classification.objects.get_or_create(name=classification_name.strip())
            title = cd['caption']
            author = Author.objects.get(id=1)
            content = cd['content']
            article = Article(caption=title, author=author, content=content)
            article.classification = Classification.objects.get(name=classification_name.strip())
            article.save()
            for taglist in tagname.split():
                article.tags.add(Tag.objects.get(tag_name=taglist.strip()))
                article.save()
            id = Article.objects.order_by('-publish_time')[0].id
            return HttpResponseRedirect('/blog/article/%s/%s/' % ('/'.join(str(article.publish_time).split()[0].split('-')), id))
    else:
        form = ArticleForm()
        tag = TagForm(initial={'tag_name': 'notags'})
        classification = ClassificationForm()
    return render_to_response('article_add.html',
        {}, context_instance=RequestContext(request))
Beispiel #11
0
def article_new(request):
    if request.method == "POST":
        form = ArticleForm(request.POST)
        if form.is_valid():
            f = form.save(commit=False)
            ru = request.user.username
            a = form.cleaned_data['author']
            print(a.username)
            print(ru)
            if ru != a.username:
                print('Invalid username auther not same logged user:   '******'Invalid username auther not same logged user:'******'Invalid username auther not same logged user: %(value)s'),
                #                       code='invalid',
                #                       params={'value': value}, )
            else:
                print(form.cleaned_data['post_status'])
                f.author = a
                ps = form.cleaned_data['post_status']
                if ps == 'published':
                    f.published_date = timezone.now()
                f.save()
                send_mail('subject', "new post", '*****@*****.**', [a.mail])
                return redirect('article-detail', pk=f.pk)
    else:
        form = ArticleForm()
    return render(request, 'blog/article_edit.html', {'form': form})
Beispiel #12
0
def article_edit(request, pk):
    article = get_object_or_404(Article, pk=pk)
    if request.method == "POST":
        form = ArticleForm(request.POST, instance=article)
        if form.is_valid():
            f = form.save(commit=False)
            ru = request.user.username
            a = form.cleaned_data['author']
            print(a.username)
            print(ru)
            if ru != a.username:
                messages.add_message(
                    request, messages.ERROR,
                    'Invalid username auther not same logged user:'******'Invalid username auther not same logged user: %(value)s'),
                #                       code='invalid',
                #                       params={'value': value}, )
            else:
                f.author = a
                ps = form.cleaned_data['post_status']
                if ps == 'published':
                    f.published_date = timezone.now()
                f.save()
                return redirect('article-detail', pk=f.pk)
    else:
        form = ArticleForm(instance=article)
    return render(request, 'blog/article_edit.html', {
        'form': form,
        'pk': article.pk
    })
Beispiel #13
0
def update_article(request, id):
    """Enables Article update"""

    article = Article.get_by_id(int(id))

    if article:
        if request.method == 'POST':
            form = ArticleForm(request.POST)

            if form.is_valid():
                article.title = form.cleaned_data['title']
                article.content = form.cleaned_data['content']
                article.put()
                messages.add_message(request,
                                     messages.INFO,
                                     u'Article %s created'
                                     % form.cleaned_data['title'])

                time.sleep(1)

                return redirect('home')

        else:

            form = ArticleForm({'title': article.title,
                                'content': article.content})

        return render(request, 'article/create.html', locals())
    else:
        messages.add_message(request,
                             messages.ERROR,
                             u'Article not found')
        return redirect('home')
Beispiel #14
0
def create_blog(request):
    form = ArticleForm(request.POST)
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = ArticleForm(request.POST, request.FILES)
        # check whether it's valid:
        if form.is_valid():
            title = form.cleaned_data['title']
            lead_paragraph = form.cleaned_data['lead_paragraph']
            content = form.cleaned_data['content']
            title = request.POST['title']
            lead_paragraph = request.POST['lead_paragraph']
            image = request.FILES['image']
            content = request.POST['content']
            #create slug from title-input
            slug = create_slug_text(title)
            new_article = BlogPost(title=title,
                                   lead_paragraph=lead_paragraph,
                                   image=image,
                                   slug=slug,
                                   meta_title=title,
                                   meta_description=lead_paragraph,
                                   content=content)
            new_article.save()
            # redirect to a blog_post_url:
            return redirect('blog_thanks')
            # if a GET (or any other method) we'll create a blank form
        else:
            form = ArticleForm()
    context = {
        'form': form
        }
    return render(request, "blog/edit/form.html", context)
Beispiel #15
0
def update_article(request, id):
    if request.method == 'POST':
        try:
            form = ArticleForm(request.POST, request.FILES)
            # print(form)
            # print(id)
            if form.is_valid():
                # form.save()
                update_article = Article.objects.get(article_id=id)
                update_article.article_title = form.cleaned_data[
                    'article_title']
                update_article.article_description = form.cleaned_data[
                    'article_description']
                update_article.article_image = form.cleaned_data[
                    'article_image']
                print(form.cleaned_data['article_image'])
                update_article.save()
                return JsonResponse({"err": "false", "message": "data added"})
            else:
                return JsonResponse({
                    "err": "true",
                    "message": "data not added"
                })
        except Exception as err:
            errMessage = f"Oops! {sys.exc_info()[1]}"
            return JsonResponse({'err': 'true', 'message': errMessage})
Beispiel #16
0
def create_article(request):  # User creating a new article.
    form = ArticleForm(request.POST)

    if form.is_valid():
        form.save()
        return redirect(reverse('show_all'))
    else:  # Else sends user back to article_form page.
        return render(request, 'article_form.html', {'form': form})
Beispiel #17
0
 def post(request, pk):
     _id = pk
     article_obj = Article.objects.filter(id=_id).first()
     form_obj = ArticleForm(request.POST, instance=article_obj)
     if form_obj.is_valid():
         form_obj.save()
         _next_url = reverse('blog:article', kwargs={'pk': 0})
         return redirect(_next_url)
     return render(request, 'blog/addblog.html', {'form_obj': form_obj, 'id': _id})
Beispiel #18
0
def add_article(request):
	if request.method == 'POST':
		form = ArticleForm(request.POST)

		if form.is_valid():
			envoi = True
	else:
		form = ArticleForm()
	return render(request, 'blog/add_article.html', locals())
Beispiel #19
0
def newForm(request):
    form = ArticleForm()
    if request.POST :
        form = ArticleForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data, form.errors)
            form.save()
            return redirect('/form/')
    return render(request, 'forms.html', {"form": form,'username': auth.get_user(request).username})
Beispiel #20
0
def ajout(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        #prepopulated_fields = {'Article.slug': ('Article.titre', ), }
        if form.is_valid():
            form.save()
            return redirect(view_redirection)
    else:
        form = ArticleForm
    return render(request, 'blog/ajout.html', locals())
Beispiel #21
0
def article(request):
	if request.method == 'POST':
		form = ArticleForm(request.POST)
		if form.is_valid():
			form.save()

	else:
		form = ArticleForm()
	
	return render(request, 'blog/article.html', locals())	
Beispiel #22
0
def create_article(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            form.user = request.user
            form.save()
            return HttpResponseRedirect('/home/')
    else:
        form = ArticleForm()
    return render(request, 'create_article.html', {'form': form})
Beispiel #23
0
def edit_article(request, id_article):
	if request.method == 'POST':
		form = ArticleForm(request.POST)

		if form.is_valid():
			envoi = True
	else:
		article = get_object_or_404(Article, id=id_article)
		form = ArticleForm(instance=article)
	return render(request, 'blog/add_article.html', locals())
Beispiel #24
0
def create(request):
	if request.method == "POST":
		form = ArticleForm(request.POST, request.FILES)
		if form.is_valid():
			form.save()
		return HttpResponseRedirect('/all')
	c = {}
	c.update(csrf(request))
	c['form'] = ArticleForm()
	return render_to_response('create.html', c)
Beispiel #25
0
 def post(self, request):
     """发布文章提交表单处理,验证通过则添加记录重定向到文章详情页面,否则回到发布文章页面显示错误"""
     article_form = ArticleForm(request.POST)
     if article_form.is_valid():
         article_form.instance.user_id = request.session['user']['id']
         article_form.save()
         return redirect(
             reverse('blog:article_detail',
                     args=[article_form.instance.id]))
     return render(request, 'publish_article.html', {'form': article_form})
Beispiel #26
0
def edit_article(request, id):
    if request.method == 'POST':  # S'il s'agit d'une requête POST
        article = get_object_or_404(Article, id=id)
        article_form = ArticleForm(request.POST, instance=article)
        if article_form.is_valid():
            article_form.save()
        return redirect('blog.views.edit_article', id)
    else:
        article = get_object_or_404(Article, id=id)
        article_form = ArticleForm(instance=article)
        return render(request, 'blog/edit_article.html', {'article_form': article_form, 'id': id})
Beispiel #27
0
def nouvel_article(request):
    """AJout d'un article via formulaire"""
    if request.method == "POST":
        form = ArticleForm(request.POST)
        if form.is_valid():
            form.save()
            envoi = True
    else:
        form = ArticleForm()

    return render(request, "blog/nouvel-article.html", locals())
Beispiel #28
0
def create(request):
    title = request.POST.get('title')
    content = request.POST.get('content')
    form = ArticleForm(dict(title=title,
                            content=content,))
    if form.is_valid():
        article = Article(title=title, content=content,)
        article.save()
    #else:
        #return 
    return redirect(show, article_id=article.id)
Beispiel #29
0
def addArticle(request):
    if request.method == 'POST':
        print(request.POST)
        print(request.FILES)
        form = ArticleForm(request.POST, request.FILES)
        # print(form)
        if form.is_valid():
            form.save()
            return JsonResponse({"err": "false", "message": "data added"})
        else:
            return JsonResponse({"err": "true", "message": "data not added"})
Beispiel #30
0
def post_edit(request, pk):
    post = get_object_or_404(BlogPost, pk=pk)
    if request.method == "POST":
        form = ArticleForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
        return redirect('show_blogs_editing')
    else:
        form = ArticleForm(instance=post)
    return render(request, 'blog/edit/form.html', {'form': form})
Beispiel #31
0
def nouvel_article(request):
    """AJout d'un article via formulaire"""
    if request.method == "POST":
        form = ArticleForm(request.POST)
        if form.is_valid():
            form.save()
            envoi = True
    else:
        form = ArticleForm()

    return render(request, "blog/nouvel-article.html", locals())
Beispiel #32
0
def post(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            article = form.save(commit=False)
            article.user = request.user
            article.fileItem_id = request.POST['id_file']
            article.save()
        else:
            print(form.errors)
    return view_media(request)
Beispiel #33
0
def Article_Formu(request):
    article = Article()
    if request.method == 'POST':
        form = ArticleForm(request.POST, instance=article)
        if form.is_valid():
            form.save()

            envoi = True
    else:
        form = ArticleForm(request.POST, instance=article)
    return render(request, 'blog/HTML/creation_article.html', locals())
Beispiel #34
0
def update_post(request, slug, template="create_post.html"):
    post = get_object_or_404(Post.objects.select_related("user"), slug=slug)
    if post.user != request.user:
        raise Http404
    if request.method == "POST":
        form = ArticleForm(instance=post, data=request.POST, files=request.FILES)
        if form.is_valid():
            form.save()
            return redirect("detail", post.slug)
    else:
        form = ArticleForm(instance=post)
    return render(request, template, {"form": form, "is_deletable": True, "slug": slug})
Beispiel #35
0
def article_new(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            article = form.save(commit=False)
            article.article_author = request.user
            article.save()
            return redirect("blog:home")

    else:
        form = ArticleForm()
    return render(request, 'blog/add_article.html', context={"form": form})
Beispiel #36
0
 def post(self, request):
     if request.method == 'POST':
         newArticle = ArticleForm(request.POST)
         if newArticle.is_valid():
             article = newArticle.save(commit=False)
             article.body = newArticle.cleaned_data['body']
             article.title = newArticle.cleaned_data['title']
             article.author = request.user
             if request.user.is_redactor:
                 article.status = 'approve'
             article.save()
     return redirect('all')
Beispiel #37
0
 def post(self, request):
     post = Post(author_id=request.user)
     form = ArticleForm(request.POST, request.FILES, instance=post)
     if form.is_valid():
         form.save()
         return redirect('blog:article_admin')
     else:
         error = form.errors
         return render(request, 'blog/articles/admin/create.html', {
             'form': form,
             'error': error
         })
Beispiel #38
0
def articleform(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            form.save()  #sauvegarder l'article creer
            form = ArticleForm()
            envoi = True

    else:
        form = ArticleForm()

    return render(request, 'blog/articleform.html', locals())
Beispiel #39
0
def new_article(request):
  if request.method == 'POST':
    form = ArticleForm(request.POST)
    if form.is_valid():
      article = form.save(commit=False)
      article.user = request.user
      article.author = article.user
      article.save()
      return redirect('article_details', id=article.id)
  else:
    form = ArticleForm()
  return render(request, 'new_article.html', {'form': form})  
Beispiel #40
0
def articleform(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            form.save()   #sauvegarder l'article creer
            form=ArticleForm()
            envoi=True 

    else:
        form= ArticleForm()

    return render(request,'blog/articleform.html',locals())
Beispiel #41
0
def update_article(request, article_id):
    args = {}
    article = get_object_or_404(Article, id=article_id)
    form = ArticleForm(instance=article)
    if request.POST:
        form = ArticleForm(data=request.POST, instance=article)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.INFO, 'Успешно изменено')
            return redirect('index')
    args['form'] = form
    return render(request, 'cr_up_article_page.html', args)
Beispiel #42
0
def article_add(request):
    # sticks in a POST or renders empty form
    form = ArticleForm(request.POST or None)
    if form.is_valid():
        cmodel = form.save()
        #This is where you might chooose to do stuff.
        #cmodel.name = 'test1'
        cmodel.save()
        return HttpResponse('Record Saved!')

    return render_to_response('blog/contact.html',
                              {'article_form': form},
                              context_instance=RequestContext(request))
Beispiel #43
0
def update(request, article_id):
    article = get_object_or_404(Article, pk=article_id)
    title = request.POST.get('title')
    content = request.POST.get('content')
    form = ArticleForm(dict(title=title,
                            content=content,))
    if form.is_valid():
        article.title = title
        article.content = content
        article.save()
    #else:
        #return 
    return redirect(show, article_id=article.id)
Beispiel #44
0
def add(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            titre = form.cleaned_data['titre']
            auteur = form.cleaned_data['auteur']
            contenu = form.cleaned_data['contenu']
            categorie = form.cleaned_data['categorie']
            form.save()
            return HttpResponseRedirect('/blog/facts')
    else:
        form = ArticleForm()
    return render(request, 'blog/add_fact.html', {'title': 'Ajouter !', 'form': form})
Beispiel #45
0
def create_article(request):
    args = {}
    form = ArticleForm()
    if request.POST:
        form = ArticleForm(data=request.POST)
        if form.is_valid():
            article = form.save(commit=False)
            article.author = request.user
            article.save()
            messages.add_message(request, messages.INFO, 'Статья опубликована')
            return redirect('index')
    args['form'] = form
    return render(request, 'cr_up_article_page.html', args)
Beispiel #46
0
def add(request):
    if request.method == 'POST':
        formData = ArticleForm(request.POST, request.FILES)
        if formData.is_valid():
            edited = formData.save(commit=False)
            edited.user = request.user
            edited.save()
        return redirect("list")

    view_url = reverse("add")
    upload_url, upload_data = prepare_upload(request, view_url)

    return render(request, "add.html", {"form": ArticleForm, "action": "Add new", 'upload_url': upload_url, 'upload_data': upload_data})
Beispiel #47
0
def edit_post(request, id):
    post = get_object_or_404(Article, pk=id, user=request.user.pk)
    if request.method == "POST":
        form = ArticleForm(request.POST, instance=post)
        if form.is_valid():
            updated_post = form.save()
            return HttpResponseRedirect(reverse('post_details',
                                                args=[post.id]))
    else:
        form = ArticleForm(instance=post)
    context = {'title': 'Edit Post', 'form': form, 'post': post}
    html_response = render(request, "edit_post.html", context)
    return HttpResponse(html_response)
Beispiel #48
0
def create_post(request):
    form = ArticleForm(request.POST)
    if form.is_valid():
        new_article = form.instance
        new_article.user = request.user
        new_article.save()
        return HttpResponseRedirect("/posts/")
    else:
        html_string = render(
            request, 'new_post.html', {
                'title': 'Create a new post',
                'article_form': ArticleForm(request.POST)
            })
        return HttpResponse(html_string)
Beispiel #49
0
def article_update(request, year='', month='', day='', id=""):
    id = id
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        tag = TagForm(request.POST)
        if form.is_valid() and tag.is_valid():
            cd = form.cleaned_data
            cdtag = tag.cleaned_data
            tagname = cdtag['tag_name']
            tagnamelist = tagname.split()
            for taglist in tagnamelist:
                Tag.objects.get_or_create(tag_name=taglist.strip())
            title = cd['caption']
            content = cd['content']
            article = Article.objects.get(id=id)
            if article:
                article.caption = title
                article.content = content
                article.save()
                for taglist in tagnamelist:
                    article.tags.add(Tag.objects.get(tag_name=taglist.strip()))
                    article.save()
                tags = article.tags.all()
                for tagname in tags:
                    tagname = unicode(str(tagname), "utf-8")
                    if tagname not in tagnamelist:
                        notag = article.tags.get(tag_name=tagname)
                        article.tags.remove(notag)
            else:
                article = Article(caption=article.caption, content=article.content)
                article.save()
            return HttpResponseRedirect('/blog/article/%s/%s/' % ('/'.join(str(article.publish_time).split()[0].split('-')), id))
    else:
        try:
            article = Article.objects.get(id=id)
            if [year, month, day] != str(article.publish_time).split()[0].split('-'):
                raise Article.DoesNotExist
        except Exception:
            raise Http404
        tags = article.tags.all()
        if tags:
            taginit = ''
            for x in tags:
                taginit += str(x) + ' '
            tag = taginit
        else:
            tag = ''
    return render_to_response('article_add.html',
        {'article': article, 'id': id, 'tag': tag},
        context_instance=RequestContext(request))
Beispiel #50
0
def post_new(request):
    if request.method == "POST":
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            blog = Blog()
            blog.author = request.user
            blog.blog_type = form.cleaned_data['content_type']
            blog.title = form.cleaned_data['title']
            blog.content = form.cleaned_data['text']
            blog.blog_img = request.FILES.get('cover')
            blog.save()
        return redirect('home')
    else:
        form = ArticleForm()
    return render(request, 'blog/blog_post_edit.html', {'form': form})
Beispiel #51
0
def edit(request, pk):
    article = get_object_or_404(Article, pk=pk)
    form = ArticleForm(instance=article)

    if request.method == 'POST':
        formData = ArticleForm(request.POST, request.FILES, instance=article)
        if formData.is_valid():
            edited = formData.save(commit=False)
            edited.user = request.user
            edited.save()
        return redirect("list")

    view_url = reverse("edit", kwargs={"pk":pk})
    upload_url, upload_data = prepare_upload(request, view_url)

    return render_to_response("add.html", {"form": form, "action": "Edit", 'upload_url': upload_url, 'upload_data': upload_data})
Beispiel #52
0
def create_post(request, template="create_post.html"):
    if request.method == "POST":
        form = ArticleForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.date = date.today()
            post.is_active = False
            post.save()
            send_mail_with_template(
                u"Yeni yazı var", settings.MY_MAIL, "mails/newpost.html", {"post": post, "user": request.user}
            )
            return redirect("detail", post.slug)
    else:
        form = ArticleForm()
    return render(request, template, {"form": form})
Beispiel #53
0
def new(request):
	if request.user.is_authenticated():
		if request.method == 'POST':
			form = ArticleForm(request.POST)
			if form.is_valid():
				blag = form.save(commit=False)
				blag.author = request.user
				blag.save()
				return index(request)
			else:
				print form.errors
		else:	
			form = ArticleForm()
	else:
		return HttpResponse("You must be an autheticated user to be here.")
	return render(request, 'blog/new.html', {'form': form})
Beispiel #54
0
 def update(self,request, *args, **kwargs):
     '''
     更新收藏
     URL : /iapi/blog/article/(?P<id>d+)/
     参数:
                     所有参数均可选填
     '''
     f = ArticleForm(request.POST,request=request)
     if f.is_valid():
         try:
             request.data = f.request.data.copy()
             return super(ArticleHandler,self).update(request,*args,**kwargs)
         except:
             log.error('article_edit_error',exc_info=traceback)
             return rc.NOT_FOUND
     else:
         log.debug('article update error')
         raise FormValidationError(f)
Beispiel #55
0
def add_article(request):
    if request.method == 'POST': 
        if not request.user.is_authenticated() or not request.user.is_staff or not request.user.is_active:
            return HttpResponseRedirect('/')
            
        form = ArticleForm(request.POST)
        if form.is_valid(): 
            title = form.cleaned_data['title']
            slug = form.cleaned_data['slug']
            text = form.cleaned_data['text']
            article=Article(title=title, slug=slug, text=text, user=request.user)
            article.save()
            return HttpResponseRedirect('/')
    else:
        form = ArticleForm() 
    return render_to_response('blog/add_article.html', {
        'form': form,
         
    },context_instance=RequestContext(request))
Beispiel #56
0
def formulaire(request):
    if request.method == 'POST':  # S'il s'agit d'une requête POST
        form = ArticleForm(request.POST)  # Nous reprenons les données

        if form.is_valid(): # Nous vérifions que les données envoyées sont valides

            # Ici nous pouvons traiter les données du formulaire
            titreM = form.cleaned_data['titre']
            auteurM = form.cleaned_data['auteur']
            contenuM = form.cleaned_data['contenu']
            categorieM=form.cleaned_data['categorie']
            article = Article(titre=titreM, auteur=auteurM,contenu=contenuM,categorie=categorieM).save()
            # Nous pourrions ici envoyer l'e-mail grâce aux données que nous venons de récupérer

            envoi = True

    else: # Si ce n'est pas du POST, c'est probablement une requête GET
        form = ArticleForm()  # Nous créons un formulaire vide

    return render(request, 'blog/formulaire.html', locals())
Beispiel #57
0
def addArticle(request):
	categories=Category.objects.all();
	if request.method=='POST':
		form=ArticleForm(request.POST,request.FILES)
		if form.is_valid():
			title=form.cleaned_data['title'];summary=form.cleaned_data['summary'];paragraph=form.cleaned_data['paragraph']
			caption=form.cleaned_data['caption'];link=form.cleaned_data['link'];linkText=form.cleaned_data['linkText'];
			image=form.cleaned_data['image'];category=form.cleaned_data['category'];
			envoi=True
			#creation of the section object
			article=Article(title=title,summary=summary,paragraph=paragraph,caption=caption,image=image,link=link,linkText=linkText)
			article.category=category;
			article.save();
			return home(request);
			#return page(request,category);
	else:
		addArticle=True;
		displayForm=True;
		form=ArticleForm()
	return render(request, 'blog/blogForm.html',locals())
Beispiel #58
0
 def create(self,request, *args, **kwargs):
     """
     创建收藏:
     URL:/iapi/blog/article/
     参数:
     title : 收藏标题
     content : 收藏内容
     desc :收藏描述(可选)
     like : 赞
     source : 收藏来源
     ctype : 收藏内容类型 (链接:link)  (可选) 默认是按照纯文字展现
     """
     f = ArticleForm(request.POST)
     if f.is_valid():
         try:
             instance = f.save()
         except:
             log.error('article_create_error',exc_info=traceback)
     else:
         raise FormValidationError(f)
     return instance
Beispiel #59
0
def add_article(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        title = request.POST.get('title')
        summary = request.POST.get('summary')
        content = request.POST.get('content')
        type_id = request.POST.get('article_type_id')
        if form.is_valid():

            Article.objects.get_or_create(title=title, summary=summary, content=content,
                                          article_type_id=type_id, author_id=request.user.id)
            request.session['notice'] = u'%s发布成功' % title
            return redirect('/blog/')
        else:
            print form.errors
            error = form.errors.as_data().values()[0][0].messages[0]
            return render(request, 'blog/article/add_article.html',
                          {'error': error, 'title': title, 'summary': summary,
                           'content': content})
    else:
        return render(request, 'blog/article/add_article.html')
Beispiel #60
0
def create_article(request):
    """Enables Article creation"""

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

        if form.is_valid():
            article = Article(title=form.cleaned_data['title'],
                              content=form.cleaned_data['content'],
                              author=request.session['user'].username)
            article.put()
            messages.add_message(request,
                                 messages.INFO,
                                 u'Article %s created' %
                                 form.cleaned_data['title'])
            time.sleep(1)

            return redirect('home')

    else:
        form = ArticleForm()

    return render(request, 'article/create.html', locals())