Send request to View Django, without receiving any response - django

I ask the user a question on my website and if the answer is yes, I will send two data to view Django using a JavaScript file and using Ajax. I want to get this data in View Django and not send any HttpResponse to the user.
If we do not send a response in the view, it will give an error. How should I do this?
When the condition if request.is_ajax ():
Runs, I get the following error:
ValueError: The view tourist.views.planing did not return an HttpResponse object. It returned None instead.
Thanks
def planing(request):
if request.is_ajax():
# Get user location from user location.js file:
latitude = request.POST.get('latitude', None)
longitude = request.POST.get('longitude', None)
# To save data
request.session['latitude'] = latitude
request.session['longitude'] = longitude
elif request.method == "GET":
return render(request, "tourist/planing.html")
elif request.method == "POST":
# To retrive data:
latitude = request.session.get('latitude')
longitude = request.session.get('longitude')
if latitude is not None :
latitude = float(latitude)
longitude = float(longitude)
.
.
.
return render(request, "tourist/map.html")

You can return an empty JSON. Like so:
from django.http import JsonResponse
if request.is_ajax():
# Get user location from user location.js file:
latitude = request.POST.get('latitude', None)
longitude = request.POST.get('longitude', None)
# To save data
request.session['latitude'] = latitude
request.session['longitude'] = longitude
return JsonResponse({})
This will ensure there is a response back to the AJAX request.

Related

The view courses.views.checkout.verifypayment didn't return an HttpResponse object. It returned None instead

i have this code for verify payment , when user buy some course he will redirect to other page called mycourse but when i try to buy course it show error
The view courses.views.checkout.verifypayment didn't return an HttpResponse object. It returned None instead.
View.py :
#csrf_exempt
def verifypayment(request):
if request.method == 'POST':
data = request.POST
context = {}
try:
client.utility.verify_payment_signature(data)
razorpay_order_id = data['razorpay_order_id']
razorpay_payment_id = data['razorpay_payment_id']
payment = Payment.objects.get(order_id = razorpay_order_id)
payment.payment_id = razorpay_payment_id
payment.status = True
userCourse = UserCourse(user = payment.user , course = payment.course)
userCourse.save()
payment.user_course = userCourse
payment.save()
return redirect('mycourse')
except:
return HttpResponse("Invalid Payment Details")
Django views must return an HttpResponse object, Your view returns HttpResponse only for the POST requests, in case your URL corresponding to this view, got a GET request it will through this error because you are not returning an HttpResponse for the get requests.
Solution
#csrf_exempt
def verifypayment(request):
if request.method == 'POST':
data = request.POST
return redirect('mycourse')
except:
return HttpResponse("Invalid Payment Details")
return HttpResponse("Got a GET Request") #add this line

Django returning None instead of a HTTP response

OK im probably doing this all wrong!
I am trying to run a function in a view which calls another view.
This seems to pass my request into the next function as a POST method before loading the form from the second function.
my views.py
''' This section of hte code seems to function correctly '''
#login_required()
def joinLeague(request):
if request.method == 'POST':
league = JoinLeagueQueue(user=request.user)
form = JoinLeagueForm(instance=league, data=request.POST)
if form.is_valid():
form.save()
context = int(league.id) # displays id of model, JoinLeagueQueue
return HttpResponseRedirect(confirmLeague(request, context))
else:
form = JoinLeagueForm()
context = {'form':form}
return render(request, 'userteams/joinleagueform.html', context)
This section of the views file is not working correctly.
it seems to run the POST request without displaying the GET request with the form first.
#login_required()
def confirmLeague(request, league):
# gets ID of application to join league
joinleagueid=JoinLeagueQueue.objects.get(id=league)
pin = joinleagueid.pin # gets pin from application
user = joinleagueid.user # get user from application
leagueinquestion=League.objects.get(leaguePin=pin) # gets the league record for applied league
manager=leagueinquestion.leagueManager # Gets the league manager for league applied for
leaguename=leagueinquestion.leagueName # Gets the league name for league applied for
if request.method == 'POST':
if 'accept' in request.POST:
LeaguesJoinedTo.objects.create(
leaguePin = pin,
playerjoined = user,
)
return redirect('punterDashboard')# user homepage
else:
print("Error in POST request")
else:
context = {'leaguename':leaguename, 'pin':pin, 'manager':manager}
return render(request, 'userteams/confirmleague.html', context)
I now get an error saying Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/userteams/None
Using the URLconf defined in fanfoo_proj.urls, Django tried these URL patterns, in this order:
... im skipping a list of the patterns.
10. userteams/ confirmLeague [name='confirmLeague']
Ok i think the better way would be a HttpRedirect to the second view:
return confirmLeague(request, context)
should change to something like:
return redirect(confirmLeague,args=league)
django doc to urlresolvers: https://docs.djangoproject.com/en/3.0/topics/http/shortcuts/#redirect
def joinLeague(request):
if request.method == 'POST':
league = JoinLeagueQueue(user=request.user)
form = JoinLeagueForm(instance=league, data=request.POST)
if form.is_valid():
form.save()
context = league.id
return HttpResponseRedirect( reverse("your_confirmLeague_url",kwargs={'league':context}) )
else:
form = JoinLeagueForm()
context = {'form':form}
return render(request, 'userteams/joinleagueform.html', context)
def confirmLeague(request, league):
league = get_object_or_404(JoinLeagueQueue, pk=league)
pin = league.pin
if request.method == 'POST':
if 'accept' in request.POST: # This refers to the action from my form which is waiting for a button press in a html form.
LeaguesJoinedTo.objects.create(
leaguePin = pin,
playerjoined = request.user.id,
)
return redirect('punterDashboard')
else:
context = {'league':league}
return render(request, 'userteams/confirmleague.html', context)

Django view gives error of Forbidden (CSRF token missing or incorrect.) while using the userdefined decorator for checking the session

I created the userdefined decorator to check the session is active or not. Following is the function defination
def session_required(func):
"""
Decorator to check the session is active or not for logged in user
:param func: Name of function for which you have to check the session is active or not
:return:
"""
def wrap(request, *args, **kwargs):
"""
Wrapper function for the decorator
:param request: request parameter for called URL
:return:
"""
if not request.session.get("admin_id"):
return redirect("/")
func_return = func(request, *args, **kwargs)
return func_return
return wrap
I am using this decorator on the respective function based view. At some places it works absolutely fine but when I do some POST or PUT operation then it gives me error
Forbidden (CSRF token missing or incorrect.):
My function based view is like
#csrf_exempt
#session_required
def mover_profile_handler(request):
"""
mover profile handler function for viewing and editing the details
:param request:
:return:
"""
try:
if request.method == "GET":
login_id = request.session.get("admin_id")
login_info_obj = Login.objects.get(id=login_id)
mover_info_obj = Mover.objects.get(fk_login=login_info_obj)
country_obj = Country.objects.all()
currency_obj = CurrencyType.objects.all()
subscription_detail = SubscriptionMoverDetail.objects.filter(fk_mover=mover_info_obj).order_by("-id")
# Extracting data for showing the subscription package details
current_subscription_detail = {}
subscription_detail_history = []
for index, item in enumerate(subscription_detail):
subscription_master_detail = SubscriptionMaster.objects.get(id=item.fk_subscription_master_id)
subscription_detail_json = {
"plan_name": subscription_master_detail.subscription_plan_name,
"subscription_start_date": item.subscription_date,
"subscription_end_date": item.subscription_end_date,
"amount_paid": item.amount_paid,
"users": subscription_master_detail.customer_permitted_count
}
if index == 0:
current_subscription_detail = subscription_detail_json
else:
subscription_detail_history.append(subscription_detail_json)
return render(request, "mover_profile.html", {
"mover_info_obj": mover_info_obj,
"country_obj": country_obj,
"currency_obj": currency_obj,
"login_info_obj": login_info_obj,
"current_subscription_detail": current_subscription_detail,
"subscription_detail_history": subscription_detail_history
})
elif request.method == "PUT":
request = convert_method_put_to_post(request)
mover_id = request.POST.get("id")
if Mover.objects.filter(id=mover_id).exists():
mover_info_obj = Mover.objects.get(id=mover_id)
mover_info_obj.mover_name = request.POST.get("name")
mover_info_obj.address = request.POST.get("address")
mover_info_obj.phone_no = request.POST.get("phone")
mover_info_obj.mover_size = request.POST.get("size")
mover_info_obj.reg_no = request.POST.get("reg_no")
mover_info_obj.website = request.POST.get("website")
mover_info_obj.fk_country_id = request.POST.get("country")
mover_info_obj.fk_currency_id = request.POST.get("currency")
operational_countries = request.POST.getlist("operational_countries[]")
mover_info_obj.countries_in_operation.set(operational_countries)
mover_info_obj.save()
return HttpResponse("success")
except Exception as e:
error_save(str(traceback.format_exc()))
return redirect('error_handler_500')
I tried with
#csrf_protect #csrf_exempt
in view and also tried {% csrf_token %} in html file
without using #session_required code is working absolutely fine.
So please tell me what is wrong with this stuff!!

Why is this Django view being executed twice on post?

I have a Django view that signs a user up to a free trial through Stripe. When the view makes a POST request, it does so twice.
I've tried idempotency keys, both after the if request.method == 'POST' line and in the initial rendering of the view. The customer in Stripe always ends up with two identical payment sources and two identical subscriptions to the plan.
def start_trial(request):
title = 'get started'
description = title
form = MembershipForm()
key = settings.STRIPE_PUBLISHABLE_KEY
trial_days = 30
coupon = None
custom_message = ''
subscription_idempotency = str(uuid.uuid4())
source_idempotency = str(uuid.uuid4())
try:
vendor = Vendor.objects.get(user=request.user)
custom_message = vendor.message
coupon = Coupon.objects.get(vendor.coupon)
coupon = coupon.stripe_coupon_id
trial_days = vendor.trial_days
except Vendor.DoesNotExist:
pass
try:
partner = Partner.objects.get(user=request.user)
custom_message = partner.message
coupon = Coupon.objects.get(partner.coupon)
coupon = coupon.stripe_coupon_id
trial_days = partner.trial_days
except Partner.DoesNotExist:
pass
if request.method == 'POST':
form = MembershipForm(request.POST)
if form.is_valid():
user = request.user
plan = Membership.objects.get(type_of=form.cleaned_data['plan'])
# stripe needs to attempt to create a customer
# TODO what if there's already a membership/subscription?
user_membership = UserMembership.objects.get(user=request.user)
stripe_subscription = stripe.Subscription.create(
customer=user_membership.stripe_customer_id,
items=[
{"plan": plan.stripe_plan_id}
],
trial_period_days=trial_days,
coupon=coupon,
idempotency_key=subscription_idempotency,
)
subscription = Subscription.objects.create(
user_membership=user_membership, stripe_subscription_id=stripe_subscription.id)
subscription.save()
stripe.Customer.create_source(user_membership.stripe_customer_id,
source=request.POST.get('stripeToken'),
idempotency_key=source_idempotency)
user_membership.membership = plan
user_membership.save()
user.is_subscriber = True
user.save()
# if subscription status is incomplete, display error.
# if passes, redirect to onboarding
message = 'yay'
messages.success(request, message=message)
return HttpResponseRedirect('/onboarding/')
return render(request, 'memberships/free_trial.html',
{'title': title, 'description': description, 'form': form,
'key': key, 'custom_message': custom_message})
Data always ends up in Stripe twice. Log shows:
[18/Jun/2019 11:05:21] "POST /memberships/free-trial/ HTTP/1.1" 302 0
[18/Jun/2019 11:05:22] "POST /memberships/free-trial/ HTTP/1.1" 302 0
Thanks to #duck for pointing me in the right direction. I had unseen (to me) JavaScript duplicating what was happening in the view. Removed the offending file and the problem is solved.

How can I create a csv importer in django?

I have an application in which the database shows people information.
I currently import the data from a csv file through the following script:
import csv, sys, os
dir_projeto =
"/home/danilo/Documentos/Projetos/transparencia/transparencia/"
sys.path.append(dir_projeto)
os.environ['DJANGO_SETTINGS_MODULE']='settings'
import django
django.setup()
from pessoal.models import Pessoa
data = csv.reader(open("CC_JUNHO.csv"), delimiter=";")
for linha in data:
importacao = Pessoa()
importacao.matricula = linha[0]
importacao.funcionario = linha[1]
importacao.cargo = linha[2]
importacao.data_admissao = linha[3]
importacao.salario_fixo = linha[4]
importacao.tota_bruto = linha[5]
importacao.total_desconto = linha[6]
importacao.liquido = linha[8]
importacao.save()
However, is it possible to do this import through a view and a django template? Example: The template would have a form to add the csv file, in which it would be imported into the db by the view. It is possible? If yes, how?
You can like you said create a form to gather your data. The form then performs a POST to a URL, which triggers a view that processes the data.
The following Django Tutorial elaborates this: https://docs.djangoproject.com/en/2.0/topics/forms/
For Example if your form sends a name, you can use the following to process it:
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})