So I have a view that displays some data based on the Person that is searched from the home page:
def film_chart_view(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
# grab the first person on the list
try:
person_search = Person.objects.filter(short = q)[0]
filminfo = filmInfo(person_search.film_set.all())
film_graph_data = person_search.film_set.all().order_by('date')
#Step 1: Create a DataPool
return render_to_response('home/search_results.html',{'query': q, 'high': filminfo[0],
'graph_data': film_graph_data}, RequestContext(request))
except IndexError:
return render_to_response('home/not_found.html',{'query': q}, RequestContext(request))
On the homepage I also want to have a random button that displays some data from a random person on the database and display it with the above view. So far I have this view:
def random_person(request):
# 1282302 is max number of people currently
get_random = random.randint(1,1282302)
get_person = Person.objects.get(pk=get_random)
person_name = get_person.full
but I'm not sure how to complete it so it redirects to the film_chart_view.
You can redirect from random view appropriate url to the specified view as
def random_person(request):
# 1282302 is max number of people currently
get_random = random.randint(1,1282302)
get_person = Person.objects.get(pk=get_random)
person_name = get_person.full
return HttpResponseRedirect(reverse('film_chart_view')+"?q="+get_person.short)
Related
I am trying to get my view to redirect to another page after clicking a button that triggers the POST request. I cannot seem to figure out why the redirect doesn't work or why it doesn't even seem to try to redirect.
Here is my view:
def cart1(request):
if request.user.is_authenticated:
#POST
if request.method == "POST":
#JSON Data
data = request.body
new_data = ast.literal_eval(data.decode('utf-8'))
customer = request.user
user_order = Order(user=customer)
user_order.save()
x = 0
while x < len(new_data.keys()):
obj_title = new_data[x]["title"]
obj_price = new_data[x]["price"]
obj_quantity = new_data[x]["quantity"]
obj_extra = new_data[x]["extra"]
total = round(float(obj_price.replace("$", "")))
m = OrderItem(order=user_order, title=obj_title, price=total, quantity=obj_quantity, extra=obj_extra)
m.save()
x += 1
return redirect('checkout-page')
return render(request, 'cart.html')
Any help would be appreciated, thank you
redirect(…) [Django-doc] produces a HttpRedirectResponse, you need to return it, so:
return redirect('checkout-page')
redirect(…) itself thus does not stop the code flow to redirect return a HTTP redirect response, it constructs such response, and your view should then return that response.
you need to be sure the URL name =checkout-page is in the current app otherwise you need to make it redirect('app:checkout-page')
However,I suggest to use from django.http import HttpResponseRedirect
I have two views. One which is called gameReportRoster, and the other gameReportStats.
The basic flow of the views is as follows:
gameReportRoster receives a PK from another view. It then renders some forms and processed some data to get a list of the players who played in the game, as well as players who are being added to the roster.
When the user hits submit, some business logic is completed with some data stored to a temporary Model. At this point, we then need to call the gameReportStats to render the next set of forms. When calling gameReportStats, we need to pass to it one variable called game.
The issue I am facing is that when we call gameReportStats, the URL is not changing. So the Post Request is getting handled in gameReportRoster, although we should now be in gameReportStats.
def gameReportRoster(request, pk):
#login_required(login_url="/login/")
def gameReportRoster(request, pk):
**QUERIES AND FORM RENDERING HERE**
if request.method == 'POST':
if 'submitRoster' in request.POST:
print('submitRoster Was Pressed')
homePlayedList = request.POST.getlist('homePlayed')
awayPlayedList = request.POST.getlist('awayPlayed')
formsetHome = PlayerFormSet(data=request.POST, prefix='home')
formsetAway = PlayerFormSet(request.POST, prefix='away')
**OMMITED FORM PROCESSING DONE HERE FOR READABILITY**
tempGameResult = TempGameResults(game=game)
tempGameResult.save()
tempGameResult.homePlayers.set(homePlayersPlayed)
tempGameResult.awayPlayers.set(awayPlayersPlayed)
return gameReportStats(request, game)
**MORE QUERIES AND FORM RENDERING HERE**
return render(request, "home/game-report-roster.html", context)
def gameReportStats(request, game):
#login_required(login_url="/login/")
def gameReportStats(request, game):
tempGameResult = TempGameResults.objects.get(game=game)
# teams = Team.objects.filter(id__in=teamList)
homeTeam = Team.objects.get(id=game.homeTeam_id)
awayTeam = Team.objects.get(id=game.awayTeam_id)
teamList = [homeTeam.id, awayTeam.id]
teams = Team.objects.filter(id__in=teamList)
homePlayersPlayed = Player.objects.filter(id__in=tempGameResult.homePlayers.values_list('id'))
awayPlayersPlayed = Player.objects.filter(id__in=tempGameResult.awayPlayers.values_list('id'))
gameResultForm = GameResultForm(teams=teams)
formsetGoalHome = GoalFormSet(
queryset=Goal.objects.none(),
form_kwargs={'players': homePlayersPlayed},
prefix='goalHome'
)
formsetGoalAway = GoalFormSet(
queryset=Goal.objects.none(),
form_kwargs={'players': awayPlayersPlayed},
prefix='goalAway'
)
formsetPenaltyHome = PenaltyFormSet(
queryset=Penalty.objects.none(),
form_kwargs={'players': homePlayersPlayed},
prefix='penaltyHome'
)
formsetPenaltyAway = PenaltyFormSet(
queryset=Penalty.objects.none(),
form_kwargs={'players': awayPlayersPlayed},
prefix='penaltyAway'
)
context = {
'formsetGoalHome': formsetGoalHome,
'formsetPenaltyHome': formsetPenaltyHome,
'formsetGoalAway': formsetGoalAway,
'formsetPenaltyAway': formsetPenaltyAway,
'gameResultForm': gameResultForm,
'homeTeam': homeTeam,
'awayTeam': awayTeam,
}
** THIS IF NEVER GETS CALLED **
if request.method == 'POST':
print('Test')
** TEMPLATE GETS PROPERLY RENDERED, BUT URL NEVER CHANGES **
return render(request, "home/game-report-stats.html", context)
urls.py
path('game-report-roster/<str:pk>', views.gameReportRoster, name="gameReportRoster"),
path('game-report-stats/', views.gameReportStats, name="gameReportStats"),
what the actual URL looks like
http://127.0.0.1:8000/game-report-roster/fc4cd6db-d7f9-43b3-aa80-f9d4abfff0e5
Maybe instead of
return gameReportStats(request, game)
try:
return redirect('myappname:your_name_in_urls.py', game)
Im trying to add a custom action to django app, where i can redirect to a html (pdf) page i created.
currently the html page only shows 1 result, What im trying to do is to show as many as objects i selcet from the action bar in django admin. here is my code.. admin.py
def print_pdf(modelAdmin, request, queryset, **kwargs):
from django.template.loader import get_template
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from calculator.models import Transaction
from xhtml2pdf import pisa
chp = []
for f in queryset:
chp.append(f.chp_reference)
for q in range(len(queryset)): # here im trying to know how many times to iterate based on how many qs selected
transaction = get_object_or_404(Transaction, chp_reference=chp[1]) #im not sure what to do here
template_path = 'report-pdf.html'
context = {"transactions":transactions}
response = HttpResponse(content_type='Application/pdf')
response['Content-Disposition'] = 'filename="report.pdf'
template = get_template(template_path)
html = template.render(context)
pisa_status = pisa.CreatePDF(html, dest=response)
if pisa_status.err:
return HttpResponse('we had some errors' + html )
return response
print_pdf.short_description = 'bulk pdf'
actions = [export_csv, print_pdf]
here is my code. I know its messed up, but i been trying to figure out to do this but im lost.
help would be appreciated
What's happening is the difference between the following snipppets.
def f(x)
for i in range(x):
return i ** 2
f(5) # 0 ONLY
def f(x):
results = []
for i in range(x):
results.append(i ** 2)
return results
You're returning after the first iteration, so the loop finishes after the first iteration.
You need to do the same as the second one, collect all results and return them at the end.
To illustrate what you want, this is based on your reply here. You can use something like
transactions = Transaction.objects.none()
for pk in chp:
qs = Transaction.objects.filter(chp_reference=i)
transactions = transaction.union(qs)
return transactions
and improve it based on your needs
I have a page called 'Read Later' where the users read later posts are stored. I have the Read Later on the nav bar. Now, when the user has no read later posts and clicks on Read Later, the user is redirected back to the original page. I have a function based def for Read Later.
views.py :
def show_readlater(request, *args):
global redirect
global redirect_lock
global return_address
if not(redirect_lock):
redirect = None
else:
redirect_lock = False
if not(request.user.is_authenticated()):
raise PermissionDenied
else:
user_instance = User.objects.get(username = request.user.username)
userprofile_instance = UserProfile.objects.get(user = user_instance)
readlater_objects = ReadLaterList.objects.all()
readlater_list = []
count = 0
for x in readlater_objects:
if x.username == request.user.username:
readlater_post = Post.objects.get(slug = x.slug)
readlater_list.append(readlater_post)
count = count + 1
if count == 0 :
redirect = "no_readlater"
redirect_lock = True
return HttpResponseRedirect(return_address) # The user is redirect back to the original page
post_title = "Read Later"
template = "posts/show_posts.html"
dictionary = {
"total_posts" : readlater_list,
"title" : post_title,
"count" : count,
"redirect" : redirect,
}
return render(request, template, dictionary)
Here, redirect is to display a message that no Read Later posts are there, in the original page.
The issue is that, when the redirect happens, Django says page not found, but upon refresh the page is loaded.
What is happening ?
first of all change this
global redirect
global redirect_lock
global return_address
to
request.session['redirect']= redirect
for all global variables
and use redirect instead HttpResponseRedirect
Make sure the url specified in the global variable "return_address" is correct and specified in your app/urls.py.
I am having a hard time with tests in Django and Python, for my final project I am making a forums website, but I don't really have any idea how or what my tests should be. Here is the views page from mysite file. Could someone please walk me through what I should test for besides if a user is logged in.
from django.core.urlresolvers import reverse
from settings import MEDIA_ROOT, MEDIA_URL
from django.shortcuts import redirect, render_to_response
from django.template import loader, Context, RequestContext
from mysite2.forum.models import *
def list_forums(request):
"""Main listing."""
forums = Forum.objects.all()
return render_to_response("forum/list_forums.html", {"forums":forums}, context_instance=RequestContext(request))
def mk_paginator(request, items, num_items):
"""Create and return a paginator."""
paginator = Paginator(items, num_items)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
items = paginator.page(page)
except (InvalidPage, EmptyPage):
items = paginator.page(paginator.num_pages)
return items
def list_threads(request, forum_slug):
"""Listing of threads in a forum."""
threads = Thread.objects.filter(forum__slug=forum_slug).order_by("-created")
threads = mk_paginator(request, threads, 20)
template_data = {'threads': threads}
return render_to_response("forum/list_threads.html", template_data, context_instance=RequestContext(request))
def list_posts(request, forum_slug, thread_slug):
"""Listing of posts in a thread."""
posts = Post.objects.filter(thread__slug=thread_slug, thread__forum__slug=forum_slug).order_by("created")
posts = mk_paginator(request, posts, 15)
thread = Thread.objects.get(slug=thread_slug)
template_data = {'posts': posts, 'thread' : thread}
return render_to_response("forum/list_posts.html", template_data, context_instance=RequestContext(request))
def post(request, ptype, pk):
"""Display a post form."""
action = reverse("mysite2.forum.views.%s" % ptype, args=[pk])
if ptype == "new_thread":
title = "Start New Topic"
subject = ''
elif ptype == "reply":
title = "Reply"
subject = "Re: " + Thread.objects.get(pk=pk).title
template_data = {'action': action, 'title' : title, 'subject' : subject}
return render_to_response("forum/post.html", template_data, context_instance=RequestContext(request))
def new_thread(request, pk):
"""Start a new thread."""
p = request.POST
if p["subject"] and p["body"]:
forum = Forum.objects.get(pk=pk)
thread = Thread.objects.create(forum=forum, title=p["subject"], creator=request.user)
Post.objects.create(thread=thread, title=p["subject"], body=p["body"], creator=request.user)
return HttpResponseRedirect(reverse("dbe.forum.views.forum", args=[pk]))
def reply(request, pk):
"""Reply to a thread."""
p = request.POST
if p["body"]:
thread = Thread.objects.get(pk=pk)
post = Post.objects.create(thread=thread, title=p["subject"], body=p["body"],
creator=request.user)
return HttpResponseRedirect(reverse("dbe.forum.views.thread", args=[pk]) + "?page=last")
First read the Django testing documentation. You might also want to read this book. It's dated in some areas, but testing is still pretty much the same now as it was in 1.1.
It's a bit much of a topic to cover in an SO answer.
Well, you could test:
If you have the right number of pages for the objects you're paginating.
If the page you're viewing contains the right object range. If trying to access a page that doesn't exist returns the
appropriate error.
If your views for listing objects and object detail return the correct HTTP status code (200)
For starters. Hope that helps you out.