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)
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 in my controller default.py:
def images():
record = db.images(request.args(0))
form = SQLFORM(db.images, record, deletable=True,
upload=URL('download'), fields=['image'])
if request.vars.image!=None:
# form.vars.image_filename = request.vars.image.filename
form.vars.image_filename = "picture_spark_"+str(auth.user.id)
# form.vars.image_filename = "default"
if form.process().accepted:
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
return form
def dashboard():
return dict(img_upload_form=images())
In my view dashboard.html, I use the form like this:
{{=img_upload_form}}
However, the problem is that it doesn't work. I choose an image but after I click Submit, there is no change.
Any help is appreciated!
To solve this problem,
I added a print record line to my default.py controller.
What I observed was that the output was None.
My URL is http://127.0.0.1:8000/Spark/default/home. In essence, home.html does an AJAX call to dashboard.html.
Now, in my controller, I defined it as follows:
def dashboard():
return dict(img_upload_form=images())
What I needed to do was return the same form for home.html
def home():
return dict(img_upload_form=images())
This allowed me to successfully upload images!
I'm using Django for a per project. When I use an external API call in my views (function based view), I'm getting bad responses.
Here are my code snippits:
views.py
def stock_name(request):
if request.method == 'POST':
form = StockForm(request.POST)
if form.is_valid():
stock_ticker = form.cleaned_data["stock_ticker"]
return render(request, 'article/stockinfo.html', get_search_query(stock_ticker),context_instance=RequestContext(request))
else:
form = StockForm
return render(request, 'article/index.html', {"form" : form })
.
def get_search_query(stock_ticker):
print stock_ticker
api = articleAPI('e4534187a7915ba69b41c1beab029d0f:8:71762357')
articles = api.search(q = stock_ticker,
fq = {"news_desk" : "technology"},
fl = ["headline", "abstract", "pub_date", "news_desk", "_id"],
sort = "newest",
begin_date = str(20100101),
end_date = str(20150401),
)
print articles
return articles
It seems I'm getting some kind of bad response and it looks like a wsgi error. But If run the get_serach_query as a standalone code, it works. The get_search_query takes a stock ticker and retrieves results with New York Times Article API.
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)
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.