def view_save_news(request): pk = request.POST.get('id') try: news_article = NewsArticle.objects.get(pk=pk) if pk else None except NewsArticle.DoesNotExist as err: return HttpResponse(get_error('Новость не существует!')) form_news = NewsForm(request.POST, instance=news_article) if form_news.is_valid(): form_news.save() new_pk = form_news.instance.pk current_site = get_current_site(request) view_url = '{}://{}{}'.format(settings.SCHEMA, current_site.domain, reverse('view_news', args=[new_pk])) answer = get_success( 'Статья {}'.format('обновлена' if pk else 'добавлена'), {'data': { 'view_url': view_url, 'id': new_pk }}) else: absent_fields, msg_err = get_absent_fields_list(form_news) answer = get_error('Ошибка: {}'.format(msg_err), {'absent_fields': absent_fields}) return HttpResponse(answer)
def newsReleaseViews(request): """ mxl """ if request.method == 'POST': files = request.FILES.getlist("news_document") newsform = NewsForm(request.POST) if newsform.is_valid(): new_news = News(news_title = newsform.cleaned_data["news_title"], news_content = newsform.cleaned_data["news_content"], news_date = newsform.cleaned_data["news_date"], news_category = NewsCategory.objects.get(id = newsform.cleaned_data["news_category"]) ) new_news.save() if files: for f in files: doc = DocumentFile(news_document = f, news = new_news) doc.save() # return redirect("/news/newslist/%s" % new_news.id) return redirect("/management/newsManagement") else: newsform = NewsForm() context = { 'newsform' : newsform } return render(request, "management/news_release.html", context)
def test標題或內容不能空白(self): form = NewsForm(data={'content':'內容'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['title'], ['必填']) form = NewsForm(data={'title':'標題'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['content'], ['必填'])
def post(self, request): today_news = News.objects.filter(updated_at__gte=date.today()).all() form = NewsForm(self.request.POST) if form.is_valid(): _new = News(title=self.request.POST["title"], body=self.request.POST["body"]) _new.save() form = NewsForm1() return render(self.request, 'news/index.html', context={'news': today_news, 'form': form})
def post(self, request): form = NewsForm(request.POST) if form.is_valid(): form.save() return redirect('/news') return render(request, "news/news_form.html", { "form" : form })
def addNews(request): template = 'news/addNews.html' if request.method=='GET': return render(request, template, {'form':NewsForm(), 'folderName':'news'}) # POST form = NewsForm(request.POST) if not form.is_valid(): return render(request, template, {'form':form}) form.save() messages.success(request, '最新消息已發布') return redirect('news:news')
def edit_news(request, news_id): item = News.objects.get(id=news_id) if request.method == "POST": form = NewsForm(request.POST, instance=item) if form.is_valid(): item.save() return redirect("news") else: form = NewsForm(instance=item) data = {"item": item, "form": form} return render(request, "edit_news.html", data)
def add_news(request): if request.method == 'POST': form = NewsForm(request.POST) if form.is_valid(): News.objects.create(category=form.cleaned_data['category'], url=form.cleaned_data['url'], title=form.cleaned_data['title'], news_text=form.cleaned_data['news_text'], user=request.user) return redirect("news") else: form = NewsForm() data = {'form': form} return render(request, 'add_news.html', data)
def test_class_form(self): data = { 'title': "title", 'description': "test description", 'publish_date': timezone.now() } form = NewsForm(data=data) form.save() self.assertTrue(form.is_valid()) x = NewsItem.objects.get(title="title") self.assertTrue(x)
def add(request): news_form = NewsForm(request.POST) if news_form.is_valid(): try: news_form.save() for t in TeamProfile.objects.all(): t.nb_unread_news += 1 t.save() messages.add_message(request, messages.SUCCESS, "The news has been posted.") except Exception: logger.exception("Error adding news:") return redirect(reverse("news:list"))
def editNews(request, newsId): template = 'news/editNews.html' newsToUpdate = get_object_or_404(News, id=newsId) if request.method=='GET': return render(request, template, {'form':NewsForm(instance=newsToUpdate), 'news':newsToUpdate, 'folderName':'news'}) # POST form = NewsForm(request.POST, instance=newsToUpdate) if not form.is_valid(): return render(request, template, {'form':form, 'news':newsToUpdate, 'command':'news'}) form.save() messages.success(request, '消息修改成功') return redirect('news:news')
def news_index(request): if request.method == "GET": today_news = News.objects.filter(updated_at__gte=date.today()).all() form = NewsForm() return render(request, 'news/index.html', context={'news': today_news, 'form': form}) elif request.method == "POST": today_news = News.objects.filter(updated_at__gte=date.today()).all() form = NewsForm(request.POST) if form.is_valid(): _new = News(title=request.POST["title"], body=request.POST["body"]) _new.save() form = NewsForm() return render(request, 'news/index.html', context={'news': today_news, 'form': form})
def news_index(request): if request.method == "POST": form = NewsForm(request.POST) if form.is_valid(): _new = News(**form.cleaned_data) _new.save() return HttpResponseRedirect('/news/') else: form = NewsForm() today_news = News.objects.filter(updated_at__gte=date.today()).all() return render(request, 'news/index.html', context={'news': today_news, 'form': form})
def post(self, request): today_news = News.objects.filter(updated_at__gte=date.today()).all() form = NewsForm(self.request.POST) if form.is_valid(): _new = News(title=self.request.POST["title"], body=self.request.POST["body"]) _new.save() form = NewsForm1() return render(self.request, 'news/index.html', context={ 'news': today_news, 'form': form })
def edit_news(request, news_id): news = News.objects.get(id=news_id) form = NewsForm(instance=news) NewsFormPreview(NewsForm) url = reverse('create_news', ) return HttpResponseRedirect(url)
def admin(request): ctf_settings = CTFSettings.objects.first() ctf_state = ctf_settings.get_state_display() ctf_has_been_started = ctf_settings.has_been_started or request.user.is_staff challenges = Challenge.all_objects.all().order_by('difficulty') for c in challenges: c.nb_of_validations = len(c.flaggers.filter(team__is_staff=False)) c.nb_points = c.get_nb_points() categories = Challenge.CATEGORY_CHOICES challs_validated = request.user.teamprofile.validated_challenges try: r = requests.get(ctf_settings.url_challenges_state) challenges_states = r.json() logger.info(challenges_states) except Exception: challenges_states = {} logger.exception("Error requesting challenges monitoring") news = News.objects.all().order_by("-updated_date") if request.user.is_staff: news_form = NewsForm() return render(request, 'challenges/admin.html', locals())
def news_index(request): if request.method == "POST": form = NewsForm(request.POST) if form.is_valid(): _new = News(**form.cleaned_data) _new.save() return HttpResponseRedirect('/news/') else: form = NewsForm() today_news = News.objects.filter(updated_at__gte=date.today()).all() return render(request, 'news/index.html', context={ 'news': today_news, 'form': form })
def reportnewsView(request): if request.method == 'POST': form = NewsForm(request.POST, request.FILES) if form.is_valid(): news_publish = NewsPublish() news_publish.title = form.cleaned_data['title'] news_publish.stitle = form.cleaned_data['stitle'] news_publish.description = form.cleaned_data['description'] if form.cleaned_data['image'] != None: news_publish.newsimage = form.cleaned_data['image'] news_publish.category = form.cleaned_data['category'] news_publish.pub_date = timezone.now(); news_publish.reporter = request.user news_publish.save() return redirect('news:index') else : form = NewsForm() return render(request, 'reportnews.html', {'form': form})
def NewsRelease(request): news_list = News.objects.all().order_by("-news_date") page = request.GET.get('page') if request.method == 'POST': newsform = NewsForm(request.POST, request.FILES) if newsform.is_valid(): new_news = News(news_title = newsform.cleaned_data["news_title"], news_content = newsform.cleaned_data["news_content"], news_date = newsform.cleaned_data["news_date"], news_category = NewsCategory.objects.get(id=newsform.cleaned_data["news_category"]), news_document = request.FILES.get("news_document", None),) new_news.save() loginfo(newsform.cleaned_data["news_content"]) else: loginfo(p=newsform.errors.keys(), label="news form error") return redirect('/newslist/%d' % new_news.id) else: context = getContext(news_list, page, 'news', 0) context.update({"newsform": NewsForm}) return render(request, "adminStaff/news_release.html", context)
def editView(request, category, news_id, news_title): news_publish = NewsPublish.objects.get(pk=news_id) if request.method == 'POST': form = NewsForm(request.POST, request.FILES) if form.is_valid(): news_publish.title = form.cleaned_data['title'] news_publish.stitle = form.cleaned_data['stitle'] news_publish.description = form.cleaned_data['description'] if form.cleaned_data['image'] != None: news_publish.newsimage = form.cleaned_data['image'] news_publish.category = form.cleaned_data['category'] news_publish.save() return redirect('news:detailnews', category, news_id, news_publish.title) else : form = NewsForm(initial={ 'title': news_publish.title, 'stitle' : news_publish.stitle, 'description' : news_publish.description, 'category' : news_publish.category, }) return render(request, 'editnews.html', {'form': form, 'news' : news_publish })
def newsReleaseViews(request): """ mxl """ if request.method == 'POST': files = request.FILES.getlist("news_document") newsform = NewsForm(request.POST) if newsform.is_valid(): new_news = News(news_title=newsform.cleaned_data["news_title"], news_content=newsform.cleaned_data["news_content"], news_date=newsform.cleaned_data["news_date"], news_category=NewsCategory.objects.get( id=newsform.cleaned_data["news_category"])) new_news.save() if files: for f in files: doc = DocumentFile(news_document=f, news=new_news) doc.save() # return redirect("/news/newslist/%s" % new_news.id) return redirect("/management/newsManagement") else: newsform = NewsForm() context = {'newsform': newsform} return render(request, "management/news_release.html", context)
def form_valid(self, form): tags = self.request.POST.get('tags') news = News(**form.cleaned_data) news.save() self.increase_news_quantity(self.request) if len(tags): tags_list = tags.split() for elem in tags_list: tag, _ = Tag.objects.get_or_create(name=elem) news.tags.add(tag) news.save() return HttpResponseRedirect(reverse('news_details', kwargs={'pk': news.id})) news = NewsForm() return render(self.request, 'news/create_news.html', {'news': news})
def modify(request, id_news): news = get_object_or_404(News.objects, id=id_news) if request.method == "POST": news_form = NewsForm(request.POST, instance=news) if news_form.is_valid(): try: news_form.save() for t in TeamProfile.objects.all(): t.nb_unread_news += 1 t.save() messages.add_message(request, messages.SUCCESS, "The news has been updated.") except Exception: logger.exception("Error adding news: ") messages.add_message(request, messages.ERROR, "Error while updating the news.") return redirect(reverse("news:list")) elif request.method == "GET": news_form = NewsForm(instance=news) return render(request, "news/modify.html", locals())
def news_form(request): if request.method == 'POST': form = NewsForm(request.POST) if form.is_valid(): cd = form.cleaned_data news = form.save(commit=False) news.author_id = request.user.pk news.date = datetime.now() news.save() messages.add_message(request, messages.INFO, 'News successfully created!', extra_tags='alert-success') return HttpResponseRedirect('/news/' + str(news.id)) else: form = NewsForm() return render(request, 'news/news.html', {'form': form})
def add_news(request): if request.method == 'POST': form = NewsForm(request.POST) if form.is_valid(): pieceOfNews = form.save(commit=False) pieceOfNews.source = "FII" if request.user.is_authenticated: pieceOfNews.author_name = request.user.first_name + ' ' + request.user.last_name else: pieceOfNews.author_name = 'Anonymous' pieceOfNews.inserted_time = datetime.datetime.now() pieceOfNews.published_time = datetime.datetime.now() pieceOfNews.expire_time = datetime.datetime.now() + relativedelta( years=1) pieceOfNews.save() return redirect('/news') else: form = NewsForm() return render(request, 'add_news.html', {'form': form})
def news_add(request): form = NewsForm() now = datetime.datetime.now() print(now) year = now.year month = now.month day = now.day print(day) if len(str(day)) == 1: day = "0" + str(day) if len(str(month)) == 1: month = "0" + str(month) today = str(year) + "/" + str(month) + "/" + str(day) time = str(now.hour) + ":" + str(now.minute) cat = SubCat.objects.all() if request.method == 'POST': newstitle = request.POST.get('newstitle') newscat = request.POST.get('newscat') newstxtshort = request.POST.get('newstxtshort') newstxt = request.POST.get('newstxt') newsid = request.POST.get('newscat') if newstitle == "" or newstxtshort == "" or newstxt == "" or newscat == "": error = "All Fields Requirded" return render(request, 'back/news_add.html', { 'error': error, 'now': now, 'form': form }) try: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) url = fs.url(filename) if str(myfile.content_type).startswith("image"): if myfile.size < 5000000: newsname = SubCat.objects.get(pk=newsid).name b = News(name=newstitle, short_txt=newstxtshort, body_txt=newstxt, date=now, picname=filename, picurl=url, writer="-", catname=newsname, catid=newsid, show=0, time=time) b.save() return redirect('news_list') else: fs = FileSystemStorage() fs.delete(filename) error = "Your File Is Bigger Than 5 MB" return render(request, 'back/error.html', {'error': error}) else: fs = FileSystemStorage() fs.delete(filename) error = "Your File Not Supported" return render(request, 'back/error.html', {'error': error}) except: error = "Please Input Your Image" return render(request, 'back/error.html', {'error': error}) context = {'now': now, 'form': form, 'cat': cat} return render(request, 'back/news_add.html', context)
def test新增消息表單內容正確(self): form = NewsForm() self.assertIn('標題', form.as_p()) self.assertIn('內容', form.as_p())
def test_can_not_write_body_spam(self): f = NewsForm({'title': 'qwe', 'body': 'spam'}) f.is_valid() self.assertIn(u"Уберите `spam` из сообщения.", f.errors['body'])