def read_lf_notifiation(request, id, slug):
lf = LostAndFound.objects.get(slug=slug)
notf = N_lostandfound.objects.get(id=id, lf=lf)
if notf.read == False:
notf.read = True
notf.save()
return HttpResponseRedirect('/lostandfound/%s/?notif_id=%s' %(slug, notf.id))
So read_lf_notification is supposed to read the notfication and redirect to the same page but with the url parameter of notif_id. So I want to give the value of notif_id, the id of notf, but when it redirects to the same page, the response is
http://localhost:8000/this-is-slug/?notf_id=id
But what I want is
http://localhost:8000/this-is-slug/?notf_id=12
What am I doing wrong here?
Thanks in advance
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 am trying to figure out how to display an image on the webform page when a certain option is selected from the select field. And then getting the image to change when a different option is selected. The url image link is stored in the Sqlite3 database with the respective select field options. I am having trouble putting this all together and was wondering if someone may be able to help. Here is some code that may make things easier to understand.
The select field I am focusing on is the Host field and the extra part of the Host class is where the URL image link is stored.
class LoginForm(FlaskForm):
host = SelectField('Host Solution Required', choices = [], validators= .
[validators.InputRequired('Please select a Board')])
#app.route('/', methods=['GET', 'POST'])
def form():
form = LoginForm()
form.device.choices = [(device.id, device.name) for device in
Device.query.filter_by(cat=None).all()]
form.host.choices= [(host.id, host.name) for host in Host.query.all()]
#if form.validate_on_submit(): To use this I will have to figure out how
to validate the choices for device
if request.method =='POST':
device = Device.query.filter_by(id=form.device.data).first()
host = Host.query.filter_by(id= form.host.data).first()
#This code takes care of changing the format of the ordering link
that is put into bugzilla.
if host.name =='None' and form.cat.data == 'None':
return '<h1> You did not order anything, please go back and fill
out cat or host</h2>'
elif host.name == 'None':
return '<h1> ({} x {}) for {}</h1>'.format(form.number.data,
device.name, form.team.data)
elif form.cat.data == 'None':
return '<h1> ({} x {}-{}) for {} .
</h1>'.format(form.quantity.data, host.name, form.finish.data,
form.team.data)
else:
return '<h1> ({} x {}-{}) AND ({} x {}) for {} .
</h1>'.format(form.quantity.data, host.name, form.finish.data,
form.number.data, device.name, form.team.data)
return render_template('form.html', form=form, street = host.extra)
class Host(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
customer = db.Column(db.Boolean())
engineering = db.Column(db.Boolean())
extra = db.Column(db.String(400))
#app.route('/host/<name>')
def host(name):
hosts = Host.query.filter_by(name = name).all()
hostArray = []
for host in hosts:
hostObj = {}
hostObj['id'] = host.id
hostObj['name'] = host.name
hostObj['extra'] = host.extra
hostArray.append(hostObj)
return jsonify({'hosts':hostArray})
<br>
{{form.host.label}}
{{form.host}}
<img src={{street}} alt = 'pic' align = 'right' width = '200' height =
'200' />
<script>
var host_select = document.getElementById("host");
host_select.onchange = function() {
name = host_select.extra;
fetch('/host/' + name).then(function(response)){
response.json().then(function(data)){
for(host of data.hosts){
document.getElementById("tweet").src= host.extra;
}
})
});
}*/
</script>
The snippet above does not work, but it is where the image is being shown in the HTML.
Please let me know if I can clarify anything further.
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 have a method in Django where I get POST data from a mobile app and all I do is save it and send a Response. The problem is though the the data gets saved but no matter what the app receives the response code 500.
<Response [500]>
code:
#csrf_exempt
def store_recordings(request):
if request.method == 'POST':
print "In POST",request.POST
driverName = request.POST['driverName']
driverMobileNum = request.POST['driverMobileNum']
customerMobileNum = request.POST['customerMobileNum']
salesOrderNo = request.POST['salesOrderNo']
callRecord = request.POST['callRecord']
latitude = request.POST['latitude']
longitude = request.POST['longitude']
callStart = request.POST['callStart']
callEnd = request.POST['callEnd']
callDuration = request.POST['callDuration']
callType = request.POST['callType']
driverrecording = DriverRecording(driverName=driverName,driverMobileNum=driverMobileNum,customerMobileNum=customerMobileNum,salesOrderNo=salesOrderNo,callRecord=callRecord,latitude=latitude,longitude=longitude,callStart=callStart,callEnd=callEnd,callDuration=callDuration,callType=callType)
save_or_not = driverrecording.save()
driverexist = DriverNames.objects.all()
new_driver_flag = False
driverName_list = [each.driverName for each in driverexist]
driverName_list = list(set(driverName_list))
if driverName in driverName_list:
pass
else:
DriverNames(driverName=driverName,driverMobileNum=driverMobileNum).save()
return HttpResponse(status=201)
else:
return HttpResponse(status=400)
I am perplexed what is the problem.
Thanks.
Almost certainly, one or more of those fields is not being sent, so you are getting a KeyError. If you set DEBUG to True you would see the traceback.
You should be using Django's forms framework, instead of directly accessing the POST data. That will validate the input and allow you to display any errors.
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)