def newPost(request, id): langCode = request.build_absolute_uri().split("/")[-5] if not request.session.has_key('username'): return redirect('/' + langCode + '/login') if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): content = form.cleaned_data["content"] post = Post() post.content = content post.user = User.objects.get(username=request.session["username"]) post.thread = Thread.objects.get(pk=id) post.date = timezone.now() post.positionInThread = len(post.thread.thread_posts.all()) post.save() print('/' + langCode + '/forum/thread/' + str(id)) return redirect('/' + langCode + '/forum/thread/' + str(id)) else: # GET form = PostForm() thread = Thread.objects.get(pk=id) return render( request, "forum/newpost.html", { "form": form, "thread": thread, "numberOfPosts": thread.thread_posts.count() })
def index(request): if request.method == "POST": post_pk = request.POST.get("post_id", 0) post_obj = Post.objects.filter(pk=post_pk).first() form = PostForm(request.POST, instance=post_obj) if form.is_valid(): post = form.save() return HttpResponseRedirect(reverse('post-view', args=(post.slug,))) else: form.add_error(None, forms.ValidationError( _(u"Кожне поле повинно бути заповненим!"))) elif request.method == "GET": post_pk = request.GET.get("post_id", 0) post_obj = Post.objects.filter(pk=post_pk).first() form = PostForm(instance=post_obj) context = { "latest_posts": Post.objects.all().order_by('-created')[:5], "form": form, "post_on_edit": (post_pk if request.GET.get("mark") else 0) } return render(request, "app/index.html", context)
def thread_detail(request, thread_id): thread = get_object_or_404(Thread, id=thread_id) if request.method == 'POST': # Everyone logged in reply in a thread if not request.user.is_authenticated: return login_required() form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.thread = thread post.author = request.user post.save() return HttpResponseRedirect( reverse('thread_detail', args=[thread_id])) else: # GET form = PostForm() breadcrumbs = _category_breadcrumb(thread.category, last_active=True) return render(request, 'app/thread/detail.html', { 'thread': thread, 'reply_form': form, 'breadcrumbs': breadcrumbs })
def newThread(request): langCode = request.build_absolute_uri().split("/")[-4] if not request.session.has_key('username'): return redirect('/' + langCode + '/login') if request.method == 'POST': thread_form = ThreadForm(request.POST) post_form = PostForm(request.POST) if thread_form.is_valid() and post_form.is_valid(): thread = Thread() thread.title = thread_form.cleaned_data["title"] thread.description = thread_form.cleaned_data["description"] thread.save() post = Post() post.content = post_form.cleaned_data["content"] post.date = timezone.now() post.user = User.objects.get(username=request.session["username"]) post.positionInThread = 0 post.thread = thread post.save() thread.originalPost = post thread.save() return redirect("/" + langCode + "/forum/thread/" + str(thread.pk)) else: # GET return render(request, 'forum/newthread.html', { "thread_form": ThreadForm(), "post_form": PostForm() })
def edit_post(request, post_id): instance = get_object_or_404(Post, id=post_id) post_form = PostForm(request.POST or None, request.FILES or None, instance=instance) if request.method == "POST" and instance.creator.user.username == request.user.username: files = request.FILES.getlist('images') if post_form.is_valid(): instance = post_form.save(commit=False) instance.save() for f in files: post_image = PostImage(image=f) post_image.save() instance.images.add(post_image) return redirect('{}/{}'.format(reverse('profile'), '1')) context = { 'post_form': post_form, 'post_id': post_id, } return render(request, 'edit_post.html', context)
def thread(request, thread_id): ''' A view for rendering the threads ''' thread_id = int(thread_id) try: current_thread = Thread.objects.get(id=thread_id) except Thread.DoesNotExist: return HttpResponse("404 Thread does not exist") context_dict = { 'thread': current_thread, 'thread_report_form': ThreadReportForm(), 'post_report_form': PostReportForm() } if request.method == 'POST': post_form = PostForm(request.POST) if post_form.is_valid(): post = post_form.save(commit=False) post.thread = current_thread post.poster = request.META['REMOTE_ADDR'] post.save() current_thread.last_post_time = post.time_posted current_thread.post_count += 1 current_thread.save() print(str(current_thread.last_post_time)) else: print(post_form.errors) context_dict['post_form'] = PostForm() context_dict['posts'] = Post.objects.filter(thread=current_thread) context_dict['num_posts'] = len(context_dict['posts']) return render(request, 'app/thread.html', context_dict)
def index(request): if request.method == "POST": post_pk = request.POST.get("post_id", 0) post_obj = Post.objects.filter(pk=post_pk).first() form = PostForm(request.POST, instance=post_obj) if form.is_valid(): post = form.save() return HttpResponseRedirect( reverse('post-view', args=(post.slug, ))) else: form.add_error( None, forms.ValidationError( _(u"Кожне поле повинно бути заповненим!"))) elif request.method == "GET": post_pk = request.GET.get("post_id", 0) post_obj = Post.objects.filter(pk=post_pk).first() form = PostForm(instance=post_obj) context = { "latest_posts": Post.objects.all().order_by('-created')[:5], "form": form, "post_on_edit": (post_pk if request.GET.get("mark") else 0) } return render(request, "app/index.html", context)
def thread(request, thread_id): ''' A view for rendering the threads ''' thread_id = int(thread_id) try: current_thread = Thread.objects.get(id=thread_id) except Thread.DoesNotExist: return HttpResponse("404 Thread does not exist") context_dict = { 'thread': current_thread, 'thread_report_form': ThreadReportForm(), 'post_report_form': PostReportForm() } if request.method == 'POST': post_form = PostForm(request.POST) if post_form.is_valid(): post = post_form.save(commit = False) post.thread = current_thread post.poster = request.META['REMOTE_ADDR'] post.save() current_thread.last_post_time = post.time_posted current_thread.post_count += 1 current_thread.save() print(str(current_thread.last_post_time)) else: print(post_form.errors) context_dict['post_form'] = PostForm() context_dict['posts'] = Post.objects.filter(thread = current_thread) context_dict['num_posts'] = len(context_dict['posts']) return render(request, 'app/thread.html', context_dict)
def get(self, request, *args, **kwargs): show_followed = 'all' if 'index' in request.session: show_followed = request.session['index'] if show_followed == 'followed': # posts = Post.objects.all() posts = request.user.followed_posts() else: posts = Post.objects.all() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.timestamp = datetime.utcnow() post.save() return redirect('index') else: form = PostForm() context = { 'posts': posts, 'form': form, 'show_followed': show_followed, } return render(request, "index.html", context)
def postedit(request, pk, template_name='edit.html'): post = get_object_or_404(Post, pk=pk) form = PostForm(request.POST or None, instance=post) if form.is_valid(): form.save() return redirect('index') return render(request, template_name, {'form': form})
def postcreate(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() return redirect('index') form = PostForm() return render(request, 'create.html', {'form': form})
def home_view(request): if request.method == 'GET': post_form = PostForm() elif request.method == 'POST': post_form = PostForm(request.POST) if post_form.is_valid(): obj = post_form.save(commit=False) obj.user_fk = request.user obj.save() return render(request, 'app/home.html', context={'post_form': post_form})
def post_form_view(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() title = form.cleaned_data['title'] return HttpResponse('%s successfully saved!' % title) else: form = PostForm() context = {'form': form, 'title': 'Post Form'} return render(request, 'base.html', context)
def test_form_valid(self): Syntax.objects.create(syntax_name="syntax_name1") post_obj_data = { u'title': u'title', u'code': u'code', u'ttl_option': u'minutes=10', u'syntax': "1" } post_form = PostForm(data=post_obj_data) self.assertTrue(post_form.is_valid())
def post(request): current_user = request.user if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = current_user post.save() posts = Post.objects.filter(user=request.user.id) return render(request, 'pers_profile.html', {"form": form, "posts": posts})
def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('index') else: form = PostForm() return render(request, 'post_edit.html', {'form': form})
def post_form_view(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save() messages.success(request, '%s successfully saved.' % post.title) return redirect('test_markdownify') else: form = PostForm() context = {'form': form, 'title': 'Post Form'} theme = getattr(settings, 'MARTOR_THEME', 'bootstrap') return render(request, '%s/form.html' % theme, context)
def post_form_view(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save() messages.success(request, "%s successfully saved." % post.title) return redirect("test_markdownify") else: form = PostForm() context = {"form": form, "title": "Post Form"} theme = getattr(settings, "MARTOR_THEME", "bootstrap") return render(request, "%s/form.html" % theme, context)
def post_edit(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(commit=False) post.author = request.user post.save() return redirect('app.views.post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'app/post_edit.html', {'form': form})
def post_create(request): title = 'Create' form = PostForm(request.POST or None, request.FILES or None) author = get_author(request.user) if request.method == 'POST': if form.is_valid(): form.instance.author = author form.save() return redirect( reverse("post-detail", kwargs={'pk': form.instance.pk})) context = {'title': title, "form": form} return render(request, "post_create.html", context)
def dbPost(request): args = {} if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save( commit = False) post.feature_id = request.POST.get("feature_id", "") specId = request.POST.get("species", "") citeId = request.POST.get("citation", "") post.username = request.POST.get("username", "") post.dt = request.POST.get("dt", "") post.species_id = Species.objects.get(species_id_html = specId) post.traits = request.POST.get("traits", "") if request.POST.get("mean","") == "": post.mean = None else: post.mean = float(request.POST.get("mean","")) if request.POST.get("range0","") == "": r1 = None else: r1 = float(request.POST.get("range0","")) if request.POST.get("range1","") == "": r2 = None else: r2 = float(request.POST.get("range1","")) post.range = [r1,r2] post.uncertainty = request.POST.get("uncertainty","") post.units = request.POST.get("units","") post.cite = Citation.objects.get(citation_name = citeId) post.save() cnt = CitationNumerictraitSpecies() cnt.relation_id = CitationNumerictraitSpecies.objects.all().order_by('-relation_id').values_list()[0][0] + 1 cnt.feature = NumericTraits.objects.get(feature_id = request.POST.get("feature_id", "")) cnt.cite = Citation.objects.get(citation_name = citeId) cnt.species = Species.objects.get(species_id_html = specId) cnt.save() return HttpResponse('') else: print form.errors else: form = PostFormOther() args['form'] = form return render(request, 'app/lifehistory.html', args)
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 if 'picture' in request.FILES: profile.picture = request.FILES['picture'] post.save() return redirect('app.views.post_detail', pk=post.pk) else: form = PostForm() return render(request, 'app/post_edit.html', {'form': form})
def submission(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): data = form.cleaned_data Post.objects.create( is_boast=data['is_boast'], content=data['content'] ) return HttpResponseRedirect(reverse('homepage')) form = PostForm() return render(request, 'submission.html', {'form': form})
def post_edit(request, pk): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = Post.objects.get(pk=pk) post.text = form.cleaned_data['text'] post.save() return redirect(reverse_lazy("post_detail", kwargs={"pk": pk})) elif request.method == "GET": post = Post.objects.get(pk=pk) data = {"text": post.text} form = PostForm(initial=data) return render(request, "post_update.html", {"post": post, "form": form})
def new_post(request): if request.method == "GET": return render(request, "new_post.html") if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): content = form.cleaned_data["content"] published = form.cleaned_data["published"] new_post = Post.objects.create(author=request.user, content=content, published=published) return redirect("home") else: return render(request, "new_post.html", {"form": form})
def post_form(request,pk): user = get_object_or_404(User,pk=pk) if request.method=='POST': form = PostForm(data=request.POST) if form.is_valid(): post_filled_form = form.save(commit=False) post_filled_form.user = user post_filled_form.save() return redirect('app:post_detail',pk=user.pk) else: form = PostForm() return render(request, 'app/post_form.html', {'post_filled_form': form})
def post(self, request, *args, **kwargs): user = User.objects.get(pk=request.session['user']['id']) form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = user post.save() return JsonResponse({ 'status': 'success', }) else: return JsonResponse({ 'status': 'failed', })
def posts(request): postform = PostForm() if request.method == 'POST': postform = PostForm(request.POST) if postform.is_valid(): x = Post() x.owner = request.user x.caption = postform.cleaned_data['caption'] x.save() return HttpResponseRedirect('/feed') elif request.method == 'GET': posts = Post.objects.all() serializer = PostSerializer(posts, many=True) # not sure of the implications of safe=false return (JsonResponse(serializer.data, safe=False, status=200))
def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) if request.method == 'GET': form = PostForm() else: form = PostForm(request.POST) # Bind data from request.POST into a PostForm if form.is_valid(): imgURL = form.cleaned_data['content'] app_id = "DbZ4NzfrPL-K_CHHf4y4srnvBUSgMo4Dz9BIbeXt" app_secret = "crjTy-8St_kiFkL0wZZCFyrcoWJyOdets8Fa1BNi" clarifai_api = ClarifaiApi(app_id,app_secret) tags = '' embedLink = '' try: result = clarifai_api.tag_image_urls(imgURL) except: #if url is invalid based on clarifai API call tags = 'invalid url' imgURL = '' if tags!='invalid url': tagList = result['results'][0]['result']['tag']['classes'] bestGenre = imgscore(tagList,genres) r = requests.get('https://api.spotify.com/v1/search?q=%22'+bestGenre+'%22&type=playlist') jsonStuff = r.json() uri = jsonStuff['playlists']['items'][0]['uri'] embedLink = "https://embed.spotify.com/?uri="+uri return render( request, 'app/index.html', { 'form': form, 'imgsrc': imgURL, 'debugText': tags, 'playlistURI': embedLink, 'year':datetime.now().year, } ) return render( request, 'app/index.html', { 'form': form, 'imgsrc': '', 'debugText': '', 'playlistURI': '', 'year':datetime.now().year, } )
def get_queryset(self): form = PostForm(self.request.query_params) if not form.is_valid(): return Post.objects.none() queryset = Post.objects.order_by('-date') manual_editing = form.cleaned_data['me'] if manual_editing == 'true': queryset = queryset.filter(last_update__isnull=False) status = form.cleaned_data['status'] if status: queryset = queryset.filter(status=status) return queryset
def post_form_view(request): form = PostForm() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save(commit=True) #title = form.cleaned_data['title'] print(form.cleaned_data['title']) print(form.cleaned_data['description']) #print(form.cleaned_data['wiki']) #return HttpResponse('%s successfully saved!' % title) return HttpResponse('successfully saved!') else: context = {'form': form, 'title': 'Post Form'} return render(request, 'custom_form.html', context)
def submit_post(request): """Create a form to submit post. """ context = RequestContext(request) if request.POST: postform = PostForm(data=request.POST) if postform.is_valid(): postform.save(commit=True) return HttpResponseRedirect('/app/blog') else: print postform.errors else: postform = PostForm() print postform context_dict = { 'postform': postform, } return render_to_response("app/submitpost.html", context_dict, context)
def post(self, request, **kwargs): format = kwargs.get("format") if not format: return redirect("index") if format == "event": form = PostForm(request.POST) elif format == "information": form = InformationForm(request.POST) else: return redirect("index") if form.is_valid(): request.session["post_form_data"] = request.POST request.session["post_form_data_format"] = format return redirect("post_confirm") context = { "form": form, } return render(request, "app/post/input.html", context)
def thread_create(request, category_id): try: category = Category.objects.get(id=category_id) except Category.DoesNotExist: category = None if request.method == 'POST': # Everyone logged in can create a new thread if not request.user.is_authenticated: return login_required() thread_form = ThreadForm(request.POST) post_form = PostForm(request.POST) if thread_form.is_valid() and post_form.is_valid(): with transaction.atomic(): post = post_form.save(commit=False) post.author_id = request.user.id post.thread_id = 0 post.save() thread = thread_form.save(commit=False) thread.original_post_id = post.id thread.save() post.thread_id = thread.id post.save() return HttpResponseRedirect( reverse('thread_detail', args=[thread.id])) else: thread_form = ThreadForm(initial={'category': category}) post_form = PostForm() return render(request, 'app/thread/create.html', { 'thread_form': thread_form, 'post_form': post_form })
def add(request): if not request.user.is_authenticated(): return admin(request) if request.method == 'POST': if request.user.is_anonymous(): return redirect('/') form = PostForm(request.POST) if form.is_valid(): ftitle = form.cleaned_data['title'] ftext = form.cleaned_data['text'] newpost = Post(author=request.user, title=ftitle, text=ftext) newpost.save() return redirect('/') else: form = PostForm() return render_to_response("add.html", { 'form':form, }, context_instance = RequestContext(request) )
def post_edit(request, post_id): post = get_object_or_404(Post, id=post_id) if request.method == 'POST': # Only an author can edit their post if not request.user.is_authenticated or request.user.id != post.author_id: raise PermissionDenied form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return HttpResponseRedirect( reverse('thread_detail', args=[post.thread_id])) else: # GET form = PostForm(instance=post) return render(request, 'app/post/edit.html', { 'post': post, 'post_form': form })
def create_post(request): post_form = PostForm(request.POST or None, request.FILES or None) if request.method == "POST": files = request.FILES.getlist('images') if post_form.is_valid(): p = post_form.save(commit=False) p.creator = ExtendedUser.objects.get(user_id=request.user.id) p.is_shown = True p.save() for f in files: post_image = PostImage(image=f) post_image.save() p.images.add(post_image) return redirect(reverse('index')) context = { 'post_form': post_form, } return render(request, 'createPost.html', context)