Exemple #1
0
def dashboard(request):
    articles = Article.objects.filter(author=request.user)
    form = ArticleForm(request.POST or None, request.FILES or None)
    events = Event.objects.all()
    context = {
        "form":form,
        "articles":articles,
        "events":events,
    }
    try:
        
        if form.is_valid():

            new_article = form.save(commit=False)
            new_article.author = request.user
            new_article.save()

            messages.success(request,"Makale eklendi")

    except:

        messages.info(request,"Bir problem oluştu")


    return render(request,"new_article.html",context)
Exemple #2
0
    def post(self, request, *args, **kwargs):
        from communities.models import Community
        from common.templates import render_for_platform
        from article.forms import ArticleForm

        self.form, self.community = ArticleForm(
            request.POST,
            request.FILES), Community.objects.get(pk=self.kwargs["pk"])
        if self.form.is_valid() and request.user.is_staff_of_community(
                self.community.pk):
            article = self.form.save(commit=False)
            new_article = article.create_article(
                creator=request.user,
                content=article.content,
                community=self.community,
                g_image=article.g_image,
                title=article.title,
            )
            return render_for_platform(
                request, 'posts/post_community/admin_article.html', {
                    'object': new_article,
                    'user': request.user
                })
        else:
            from django.http import HttpResponseBadRequest
            HttpResponseBadRequest()
Exemple #3
0
def editArticle(request, article_id):
    arqs = {}
    arqs.update(csrf(request))
    arqs['username'] = auth.get_user(request).username
    arqs['title'] = 'article'
    arqs['article_id'] = article_id
    arqs['is_superUser'] = auth.get_user(request).is_superuser
    if auth.get_user(request).is_superuser == 1:
        if request.POST:
            form = ArticleForm(request.POST, request.FILES)
            if form.is_valid():
                article_edit = form.save( commit=False)
                #article_edit.article_title = Article.objects.get(id = article_id).article_title
                #article_edit.article_text = Article.objects.get(id = article_id).article_text
                article_edit.id = Article.objects.get(id = article_id).id
                article_edit.article_user_id = auth.get_user(request).id
                article_edit.article_date = datetime.datetime.today()
                form.save()
                return redirect('/articles/get/'+str(article_edit.id))
            else:
                arqs['error'] = "huina"
                #return redirect('/',arqs)
        else:
            article_form = ArticleForm
            arqs['form'] = article_form
            arqs['article_title'] = Article.objects.get(id = article_id).article_title
            arqs['article_text'] = Article.objects.get(id = article_id).article_text
            arqs['article_img'] = Article.objects.get(id = article_id).article_img
            return render_to_response('editArticle.html', arqs)
    else:
        arqs['error'] = 'addArticle'
    return render_to_response('error.html',arqs)
Exemple #4
0
def write_article(request):
    if request.method == 'GET':
        aform = ArticleForm()
        return render(request, 'article/write.html', context={'form': aform})
    else:
        aform = ArticleForm(request.POST, request.FILES)
        if aform.is_valid():
            # cleaned_data就是读取表单返回的值,返回类型为字典dict型
            data = aform.cleaned_data
            article = Article()
            article.title = data.get('title')
            article.desc = data.get('desc')
            article.content = data.get('content')
            print(type(data.get('image')))

            article.image = data.get('image')
            article.desc = data.get('desc')
            article.user = request.user  # 1对多 直接赋值
            article.save()

            # 多对多 必须添加到文章保存的后面添加
            article.tags.set(data.get('tags'))
            return redirect(reverse('index'))

        return render(request, 'article/write.html', context={'form': aform})
Exemple #5
0
def write_article(request):
    if request.method == 'GET':
        # 调用写博客表单
        aform = ArticleForm()
        return render(request, 'article/write.html', context={'form': aform})
    else:
        # 接受用户提交的数据
        aform = ArticleForm(request.POST, request.FILES)
        # 判断数据是否存在
        if aform.is_valid():
            # cleaned_data中保存了用户所有提交了的数据
            # 1对多 直接赋值
            data = aform.cleaned_data
            article = Article()
            article.title = data.get('title')
            article.desc = data.get('desc')
            article.content = data.get('content')

            article.image = data.get('image')
            article.desc = data.get('desc')
            article.user = request.user
            article.save()

            # 多对多 必须添加到文章保存的后面添加
            article.tags.set(data.get('tags'))
            # 保存成功后重定向到首页
            return redirect(reverse('index'))

        # 数据不正确重定向,继续填写
        return render(request, 'article/write.html', context={'form': aform})
Exemple #6
0
def addArticle (request):
    arqs = {}
    arqs.update(csrf(request))
    arqs['title'] = 'article'
    arqs['username'] = auth.get_user(request).username
    arqs['is_superUser'] = auth.get_user(request).is_superuser
    if auth.get_user(request).is_superuser == 1:
        if request.POST:
            form = ArticleForm(request.POST, request.FILES) #в скобка пишется при загрузке файлов request.FILES
            if form.is_valid():
                article_add = form.save(commit=False)
                # article_add.article_title = Article.objects.get(request).article_title
                #article_add.article_text = Article.objects.get(request).article_text
                article_add.article_user_id = auth.get_user(request).id
                article_add.article_date = datetime.datetime.today()
                form.save()
                return redirect('/articles/get/'+str(article_add.id))
            else:
                arqs['error'] = "huina"
                # return redirect('/',arqs)
        else:
            article_form = ArticleForm
            arqs['form'] = article_form
            return render_to_response('addArticle.html', arqs)
    else:
        arqs['error'] = 'addArticle'
    return render_to_response('error.html',arqs)
Exemple #7
0
def article_create(request, block_id):
    block_id = int(block_id)
    block = Block.objects.get(id=block_id)
    if request.method == "GET":
        return render(request, "article_create.html", {"b": block})
    else:
        """ 这段检查代码用校验器forms.py来替代
        title = request.POST["title"].strip()
        content = request.POST["content"].strip()
        if not title or not content:
            return render(request, "article_create.html",
                    {"b":block, "error":"标题和内容都不能为空", "title":title, "content":content})
        if len(title) > 1000 or len(content) > 10000:
            return render(request, "article_create.html",
                    {"b":block, "error":"标题和内容不能太长", "title":title, "content":content})
        article = Article(block=block, title=title, content=content, status=0)
        article.save()
        return redirect("/article/list/%s" %block_id)
        """
        form = ArticleForm(request.POST)
        if form.is_valid():
            #article = Article(block=block, title=form.cleaned_data["title"], content=form.cleaned_data["content"], status=0) 可用下面3行替代,字段多的时候很明显优化
            article = form.save(commit=False)
            article.block = block
            article.status = 0
            article.save()
            return redirect("/article/list/%s" % block_id)
        else:
            return render(request, "article_create.html", {
                "b": block,
                "form": form
            })
Exemple #8
0
def addarticle(request):
    form = ArticleForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        article = form.save(commit=False)
        article.author = request.user
        article.save()
        messages.success(request, "Makale Eklendi!")
        return redirect("index")
    return render(request, "addarticle.html", {"form": form})
Exemple #9
0
def article_edit(request, article_id):
    article = Article.objects.get(id=article_id)
    form = ArticleForm(request.POST or None, instance=article)
    args = {}
    args['form'] = form
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            return redirect('/articles/get/%s/' % article_id)
    return render(request, 'article_edit.html', args)
Exemple #10
0
def add_article(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            post = form.save(commit=True)
            #arti.content = form.content
            return detail(request, post.id)
    else:
        form = ArticleForm()
    return render(request, 'article/add_article.html', {'form': form})
Exemple #11
0
def create(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.SUCCESS, "Your Article was added!")
            return redirect('all_articles')
    else:
        form = ArticleForm()
    return render(request, 'article/create_article.html',{'form': form})
Exemple #12
0
def articleCreate(request,context):
    context.update(csrf(request))
    if 'submitArticle' in request.POST: #means you click on submit button named createArticle in submit_article.html
        form = ArticleForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect("/administrator/articles/get/"+str((form.save()).id))
    else:
        form = ArticleForm()#create a simple ArticleForm
    context['method']='articleCreate'
    context['form']=form
    return render_to_response('backEnd/article/submit_article.html',context)
Exemple #13
0
def addarticle(request):
    form = ArticleForm(request.POST or None, request.FILES or None)
    context = {"form": form}
    if form.is_valid():
        article = form.save(commit=False)
        article.author = request.user
        article.save()

        messages.success(request, "Makale başarıyla kayıt edilmiştir.")
        return redirect("index")
    return render(request, "addarticle.html", context)
Exemple #14
0
def articleCreate(request):
    '''
    Create a new article instance
        1. If method is GET, render an empty form
        2 . If method is POST, perform form validation. Display error messages if the form is invalid
        3. Save the form to the model and redirect to the article page
    '''
    template = 'article/articleCreate.html'
    if request.method == 'GET':
        print(ArticleForm())
        return render(request, template, {'articleForm': ArticleForm()})
Exemple #15
0
def article_add(request):
    form = ArticleForm(request.POST)
    args = {}
    args['form'] = form
    args['article_author'] = request.user
    if request.method == 'POST':
        if form.is_valid():
            article = form.save(commit=False)
            article.article_author = request.user
            article.save()
            return redirect('users:profile')
    return render(request, 'article_add.html', args)
Exemple #16
0
def update_article(request, id):
    article = get_object_or_404(Article, id=id)
    form = ArticleForm(
        request.POST or None, request.FILES or None,
        instance=article)  # instance ile formun datasına article'ı yoluyoruz
    if form.is_valid():
        article = form.save(commit=False)
        article.author = request.user
        article.save()
        messages.success(request, "Makale başarıyla güncellendi")
        return redirect("article:dashboard")
    return render(request, "article/update_article.html", {'form': form})
def updateArticle(request,id):
    article = get_object_or_404(Article,id=id)
    form = ArticleForm(request.POST or None,request.FILES or None,instance = article)
    if form.is_valid():
        article = form.save(commit=False)
        article.author = request.user
        article.save()
        messages.success(request,"Makale Başarı ile Güncellendi.")
        return redirect("dashboard")

    
    return render(request,"update.xhtml",{"form":form})
Exemple #18
0
def articleUpdate(request,id):

    article = get_object_or_404(Article, id = id)
    form = ArticleForm(request.POST or None, request.FILES or None, instance = article)
    if request.POST and form.is_valid:
        article = form.save(commit=False)
        article.author = request.user
        article.save()
        messages.success(request,"Article has been successfully updated.")
        return redirect("article:dashboard")
    
    return render(request,"update.html", {"form":form})
def newArticle(request):
	from article.forms import ArticleForm
	if request.method == "POST":
		form = ArticleForm(request.POST)
		if form.is_valid():
			form.save()
			return HttpResponseRedirect("/#agregado")
	else:
		form = ArticleForm()
	ctx ={
		"formulario": form
	}
	return render_to_response("form.html", ctx, context_instance=RequestContext(request))
Exemple #20
0
 def post(self, request, block_id):
     self.init_data(block_id)
     form = ArticleForm(request.POST)
     if form.is_valid():
         article = form.save(commit=False)
         article.block = self.block
         article.status = 0
         article.save()
         return redirect("/article/list/%s" % self.block_id)
     else:
         return render(request, self.template_name, {
             "b": self.block,
             "form": form
         })
Exemple #21
0
def article_edit(request, id=0):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            if id > 0:
                article = Article.objects.get(id=id)
                article.title = request.POST['title']
                category = Category.objects.get(id=request.POST['category'])
                article.category = category
                article.body = request.POST['body']
            else:
                article = form.save(commit=False)
                article.author = request.user
            article.save()
            return article_detail(request, "", article.pk)
        else:
            return HttpResponse(form.errors)
    else:
        if id > 0:
            article = Article.objects.get(id=id)
            if request.user != article.author:
                return article_detail(request, "", article.pk)
            form = ArticleForm(instance=article)
        else:
            form = ArticleForm()
    return render(request, 'article/article_edit.html', {'form': form})
Exemple #22
0
def create(request):
    if request.POST:
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/articles/all/")
    else:
        form = ArticleForm()

    args = {}
    args.update(csrf(request))

    args["form"] = form
    return render(request, "create_article.html", args)
Exemple #23
0
def articleUpdate(request, articleId):
    article = get_object_or_404(Article, id=articleId)
    template = 'article/articleCreateUpdate.html'
    if request.method == 'GET':
        articleForm = ArticleForm(instance=article)
        return render(request, template, {'articleForm': articleForm})

    # POST
    articleForm = ArticleForm(request.POST, instance=article)
    if not articleForm.is_valid():
        return render(request, template, {'articleForm': articleForm})
    articleForm.save()
    messages.success(request, '文章已修改')
    return redirect('article:articleRead', articleId=articleId)
Exemple #24
0
def addArticle(request):
    form = ArticleForm(request.POST or None, request.FILES or None)
    
    if form.is_valid():
        article = form.save(commit=False) # creates only the article object
        article.author = request.user
        article.save()
        messages.success(request,"Successfully added a new article.")
        return redirect("article:dashboard")
    else:
        context = {
            "form":form
        }
        return render(request,"addarticle.html", context)
def addart(request):
    from article.forms import ArticleForm
    form = ArticleForm(request.POST or None,request.FILES or None)
    if form.is_valid():
        article = form.save(commit=False)
        article.author = request.user
        article.save()
        messages.success(request,"Makale Başarı ile oluşturuldu.")
        return redirect("dashboard")
    
    context = {
        "form" : form
    }
    return render(request,"addart.xhtml",context)
Exemple #26
0
def add_article(request):
    form = ArticleForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        article = form.save(
            commit=False
        )  # bu form bir modelform olduğu için bunu kaydetmemiz çok kolay olacak. commit=False -> article objesini form fieldlardan oluştur fakat henüz save yapma
        article.author = request.user  # mevcut oturumdaki kullanıcı article'ın yazarı olsun
        article.save()  # bu sefer commiti yapıyoruz
        messages.success(request, "Makale başarıyla oluşturuldu")
        return redirect("article:dashboard")

        messages.success(request, "Makale başarılı bir şekilde kayıt edildi")
        return
    return render(request, 'article/add_article.html', {'form': form})
Exemple #27
0
def tram_info(request):
	
    if request.POST:
        form = ArticleForm(request.POST)
        form.save()
    
    cur_id = JSONModel_Tram.objects.last().id
	
    json_data = JSONModel_Tram.objects.last().tram_info
	
    form = {}
    form.update(csrf(request))
    form['user_name'] = str(request.user.username)
    form['form'] = ArticleForm()
	
    command = str(Article.objects.last()) 
    form['last_command'] = str(command)
    received_command = str(Article.objects.last()).lower()	    

    if("move" in received_command or "measure" in received_command or "wait" in received_command or "update_autonomous" in received_command or "disable_autonomous" in received_command or "enable_autonomous" in received_command or "accl_tol" in received_command or "msr_tol" in received_command or "accl_sen" in received_command):	
        form['is_valid'] = "The last command was valid."

    else:
	form['is_valid'] = "The last command was not valid please enter a valid command."
	
	
	
    form['name'] = "\n     Remote Environmental Sensing Tram"
    form['position'] = json_data['position']
    form['position_percentage'] = json_data['pos_percentage']
    form['battery_info'] = json_data['battery_info']
    form['timestamp'] = json_data['timestamp']
    form['current_move'] = json_data['command_info']['current_command']
    form['current_move_status'] = json_data['command_info']['status']
    form['shutdown_info'] = json_data['shutdown_info']
    form['id'] = int(cur_id)
	
	
  #  accel_data = 0;
	
#    if(int(json_data['accelerometer']) != 0 or int(json_data['accelerometer']) !=1 or int(json_data['accelerometer']) != 2):
#    	accel_data = 0;
#    else:
#	accel_data = json_data['accelerometer']
	
    form['accelerometer'] = int(json_data['accelerometer'])
    command = str(Article.objects.last()) 
    form['command_is'] = command
	
    return render_to_response('tram_info.html', form)
Exemple #28
0
def updatearticle(request, id):
    article = get_object_or_404(Article, id=id)
    form = ArticleForm(request.POST or None,
                       request.FILES or None,
                       instance=article)
    if form.is_valid():
        article = form.save(commit=False)
        article.author = request.user
        article.save()

        messages.success(request, "Makale başarıyla güncellendi.")
        return redirect("index")
    context = {"form": form}
    return render(request, "updatearticle.html", context)
Exemple #29
0
def add_article(request):
    """
        Adding new article by user who is logged in
    :param request:
    :return:
    """
    # create article form
    article_form = ArticleForm()
    if request.method == "POST":
        # taking form data into variables to use later
        data = request.POST.copy()
        # adding author for th article
        author_id = request.user.id
        data["author"] = author_id
        article_form = ArticleForm(data, request.FILES)
        if article_form.is_valid():
            article_form = ArticleForm(data, request.FILES)
            instance = article_form.save()
            # if article has highlighted image, it will be re-size
            if request.FILES.get("image") is not None:
                tasks.resize_image.delay(instance.image)

            delete_cache()
            return redirect(reverse("articles:my_article"))

    c = {"form": article_form}
    return render(request, "add_article.html", c)
Exemple #30
0
def update(request, id):
    article = get_object_or_404(Article, id=id)
    form = ArticleForm(request.POST or None,
                       request.FILES or None,
                       instance=article)

    if form.is_valid():
        article = form.save(commit=False)
        # article.slug = slugify(article.title)
        article.author = request.user
        article.save()

        messages.success(request, "successfully updated")
        return redirect("user:dashboard")
    return render(request, 'update.html', {'form': form})
Exemple #31
0
def create(request):
    if request.POST:
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            c = form.save(commit=False)
            c.pub_date = timezone.now()
            c.save()
            messages.add_message(request, messages.SUCCESS, "Your article was added")
            return HttpResponseRedirect('/articles/all')
    else:
        form = ArticleForm()
    args = {}
    args.update(csrf(request))
    args['form'] = form
    return render_to_response('create_article.html', args)
Exemple #32
0
def create(request):
    if request.POST:
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/articles/all')
            
    else:
        form = ArticleForm()
        
    data = {}
    data['form'] = form
    data.update(csrf(request))
            
    return render_to_response('create_article.html', data)
Exemple #33
0
def create(request):
    if request.POST:
        form = ArticleForm(request.POST)
        if form.is_valid():
            form.save()

            return HttpResponseRedirect('/articles/all')
    else:
        form = ArticleForm()

    args = {}
    args.update(csrf(request))
    args['form'] = form

    return render_to_response('create_article.html', args)
def ind_article_edit(request, id):
    article = get_object_or_404(Article, id=id)

    form = ArticleForm(request.POST or None,
                       request.FILES or None,
                       instance=article)
    if form.is_valid():
        article = form.save(commit=False)
        article.author = request.user
        article.save()

        messages.success(request, "Article Updated")
        return redirect("article:dashboard")
    return render(request, "update.html", {"forms": form})

    return render(request, "update.html")
Exemple #35
0
    def post(self,request,block_id):
        self.init_data(block_id)
        form = ArticleForm(request.POST)

        #username = request.user
        #userinfo = User.objects.get(username=username)
        if form.is_valid():
            article = form.save(commit=False)
            article.block = self.block
            #获取当前用户的request.user
            article.owner = request.user
            article.status = 0
            article.save()
            return redirect("/article/list/%s" % self.block_id)
        else:
            return  render(request,self.template_name,{'b':self.block,'form':form})
Exemple #36
0
def article_create(request, block_id):
    block_id = int(block_id)
    block = Block.objects.get(id=block_id)
    if request.method == "GET":
        return render(request, "article_create.html", {"b": block})
    else:
        form = ArticleForm(request.POST)
        if form.is_valid():
            article = form.save(commit=False)
            article.owner = request.user
            article.block = block
            article.status = 0
            article.save()
            return redirect("/article/list/%s" % block_id)
        else:
            return render(request, "article_create.html", {"b": block, "form": form})
Exemple #37
0
def submit(request,block_id):
   block_id = int(block_id)
   block = Block.objects.get(id=block_id)
   if request.method == "GET":
       return render(request,"submit.html",{"b":block})
   else:
       form = ArticleForm(request.POST)
       if form.is_valid():
           article = form.save(commit=False)
           article.owner = request.user
           article.block  = block
           article.status = 0
           article.save()
           return redirect("/article/list/%s"%block_id)
       else:
           return render(request,"submit.html",{"b":block,"form":form})
Exemple #38
0
    def get_context_data(self, **kwargs):
        from article.forms import ArticleForm

        context = super(ArticleCommunityCreate,
                        self).get_context_data(**kwargs)
        context['form'] = ArticleForm()
        return context
def editArticle(request, id_article):
	art = getArticleById(id_article)
	from article.forms import ArticleForm
	if request.method == "POST":
		form = ArticleForm(request.POST, instance=art)
		if form.is_valid():
			form.save()
			return HttpResponseRedirect("/#editado")
	else:
		if art:
			form = ArticleForm(instance=art)
		else:
			return HttpResponseRedirect("/#no-existe-ese-articulo")
	ctx ={
		"formulario": form
	}
	return render_to_response("form.html", ctx, context_instance=RequestContext(request))
Exemple #40
0
def addarticle(request):  # форма добавления новой статьи))
    args = {}
    args.update(csrf(request))
    args['username'] = auth.get_user(request).username
    args['form'] = ArticleForm()
    if request.POST:
        newarticle_form = ArticleForm(request.POST, request.FILES)
        if newarticle_form.is_valid():
            cd = newarticle_form.cleaned_data
            cd.update({'user': request.user})
            Article.objects.create(**cd)
            return redirect('/')
        else:
            args[
                'form'] = newarticle_form  # если есть ошибки, снова на страницу
            return redirect('//')
    return render_to_response('addarticle.html', args)
Exemple #41
0
class ArticleCommunityCreate(View):
    def get(self, request, *args, **kwargs):
        from common.templates import get_settings_template

        self.user, self.template_name = User.objects.get(
            pk=self.kwargs["pk"]), get_settings_template(
                "article/c_article_add/create_article.html", request.user,
                request.META['HTTP_USER_AGENT'])
        return super(ArticleCommunityCreate, self).get(request, *args,
                                                       **kwargs)

    def get_context_data(self, **kwargs):
        from article.forms import ArticleForm

        context = super(ArticleCommunityCreate,
                        self).get_context_data(**kwargs)
        context['form'] = ArticleForm()
        return context

    def post(self, request, *args, **kwargs):
        from communities.models import Community
        from common.templates import render_for_platform
        from article.forms import ArticleForm

        self.form, self.community = ArticleForm(
            request.POST,
            request.FILES), Community.objects.get(pk=self.kwargs["pk"])
        if self.form.is_valid() and request.user.is_staff_of_community(
                self.community.pk):
            article = self.form.save(commit=False)
            new_article = article.create_article(
                creator=request.user,
                content=article.content,
                community=self.community,
                g_image=article.g_image,
                title=article.title,
            )
            return render_for_platform(
                request, 'posts/post_community/admin_article.html', {
                    'object': new_article,
                    'user': request.user
                })
        else:
            from django.http import HttpResponseBadRequest
            HttpResponseBadRequest()
Exemple #42
0
def articleUpdate(request, articleId):
    ''' 
    Update the article instance:
        1. Get the article to update; redirect to 404 if not found
        2. Render a bound form if the method is GET
        3. If the form is valid, save it to the model, otherwise render a
            bound form with error messages
    '''
    articleToUpdate = get_object_or_404(Article, id=articleId)
    template = 'article/articleCreateUpdate.html'
    if request.method == 'GET':
        articleForm = ArticleForm(instance=articleToUpdate)
        return render(request, template, {
            'articleForm': articleForm,
            'article': articleToUpdate
        })
    # POST
    articleForm = ArticleForm(request.POST, instance=articleToUpdate)
    if not articleForm.is_valid():
        return render(request, template, {
            'articleForm': articleForm,
            'article': articleToUpdate
        })
    articleForm.save()
    messages.success(request, '文章已修改')
    return redirect('article:articleRead', articleId=articleId)
Exemple #43
0
def articleUpdate(request, articleId):
    '''
    Update the article instance:
        1. Get the article to update; redirect to 404 if not found
        2. If method is GET, render a bound form
        3. If method is POST,
            * vaildate the form and render a bound form if the form is invalid
            * else, save it to the model and redirect to the article page
    '''
    # # TODO: finish the code
    # return render(request, 'article/article.html') 測試
    article = get_object_or_404(Article, id=articleId)
    template = 'article/articleCreateUpdate.html'
    if request.method == 'GET':
        articleForm = ArticleForm(instance=article)
        return render(request, template, {'articleForm': articleForm})

    # POST
    articleForm = ArticleForm(request.POST, instance=article)
    if not articleForm.is_valid():
        return render(request, template, {'articleForm': articleForm})

    articleForm.save()
    messages.success(request, '文章已修改')
    return redirect('article:articleRead', articleId=articleId)
Exemple #44
0
def add_article(request):
    """添加文章"""
    if request.method == 'GET':
        categorys = Category.objects.all()
        return render(request, 'add-article.html', {'categorys': categorys})
    if request.method == 'POST':
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            data['author'] = request.user
            Article.objects.create(**data)
            return HttpResponseRedirect(reverse('article:article'))
        else:
            categorys = Category.objects.all()
            return render(request, 'add-article.html', {
                'form': form,
                'categorys': categorys
            })
Exemple #45
0
 def article_create_view(request, *args, **kwargs):
     initial_data = {'title': f'Test Article_{random.randint(000, 999)}', 'body': '<h1>Article Body</h1>'}
     form = ArticleForm(request.POST or None, initial=initial_data)
     # form = RawArticleForm(request.POST or None)
     if form.is_valid():
         art = form.save()
         # author = Author.objects.get(id=form.cleaned_data["author"])
         # data = {'title': form.cleaned_data["title"], 'subject': form.cleaned_data['subject'], 'body': form.cleaned_data['body'], 'author': author}
         # art = Article.objects.create(**data)
         #
         # 1. Redirect on the same form
         # form = ArticleForm()
         # 2. Make redirect
         return redirect('articles_detail_page', art.id)  # HttpResponseRedirect(f"/articles/{art.id}")
     context = {
         "form": form
     }
     return render(request, 'article_create.html', context)
Exemple #46
0
def articleEdit(request,context,article_id):
    #if article with this article_id doesn't exist ####
    context.update(csrf(request))
    lastArticle=Article.objects.get(id=article_id)
    if lastArticle is None: # Is there any article to edit!
        return HttpResponseRedirect("/administrator/articles/all")

    if 'submitArticle' in request.POST: #make sure that user click save button
        articleForm = ArticleForm(request.POST,instance=lastArticle) #to edit we set instance otherwise this create new article
        if articleForm.is_valid():
            articleForm.save()
            return HttpResponseRedirect("/administrator/articles/get/"+article_id)
    else:# if user enter for first time So needed to show article informations
        articleForm=ArticleForm(instance=lastArticle)
    context['method']='articleEdit'
    context['article_id']=article_id
    context['form']=articleForm
    return render_to_response('backEnd/article/submit_article.html',context)
Exemple #47
0
def edit_article(request, pk=None):
    if pk:
        article = get_object_or_404(Article, pk=pk)
        if article.user != request.user:
            return HttpResponseForbidden()
    else:
        article = Article(user=request.user)

    if request.method == "POST":
        form = ArticleForm(request.POST, instance=article)
    else:
        form = ArticleForm(instance=article)

    if form.is_valid():
        form.save()
        redirect_url = reverse('all')
        return redirect(redirect_url)
    else:
        return render(request, 'article/create_article.html', {'form': form})
Exemple #48
0
def articleCreate(request):
    template = 'article/articleCreateUpdate.html'
    # if request is GET, to write article page
    if request.method == 'GET':
        articleForm = ArticleForm()
        print("articleCreate:GET")
        return render(request, template, {'articleForm': articleForm})
    # if request is POST
    articleForm = ArticleForm(request.POST)
    print("articleCreate:POST")
    # data is invalid, save error data
    if not articleForm.is_valid():
        print("data invalid")
        return render(request, template, {'articleForm': articleForm})
    # data is valid, insert data to database
    articleForm.save()
    # return article(request)
    messages.success(request, '文章以新增')
    return redirect('article:article')
Exemple #49
0
def edit_article(request, pk=None, template=None):
    """编辑日志"""
    if pk:
        article = get_object_or_404(Article, pk=pk)
        if article.author != request.user:
            return HttpResponseForbidden(u"你没有权限编辑别人的文章")
    else:
        article = Article(author=request.user)

    form = ArticleForm(request.user, request.POST or None, instance=article)
    if form.is_valid():
        new_article = form.save()

        attachment = request.POST.get("attachment", None)
        try:
            attachment_pk_list = attachment.split(",")
            attachment_list = Attachment.objects.filter(pk__in=attachment_pk_list)
            new_article.attachment_set.add(*attachment_list)
        except:
            pass

        redirect_url = reverse("view_article", args=[new_article.pk])
        return HttpResponseRedirect(redirect_url)
    return {"form": form}, template