I am using razorpay integration with Django, I have tested the integration on localhost and it worked, also the checkout process and the payment collection works fine but when it comes to verifying the payment it seems to break on the live server.
The order amount and details sent to razorpay seem to be working fine but response capture is maybe breaking.
Below is my copy of views.py
class CheckOutW2(View):
def get(self, request, customer_phone):
dtt = dt.datetime.now()
phone = request.session.get('customer')
customer_object = Customer.objects.filter(phone=phone, date__hour= str(dtt.hour))
customer_object = customer_object.reverse()[0]
address = Addresses.objects.filter(customer=customer_object, date__hour= str(dtt.hour))
address = address.reverse()[0]
cart = request.session.get('cart')
products = Product.get_products_by_id(list(cart.keys()))
ot = 0
for p in products:
summed = p.price * cart.get(str(p.id))
ot = ot+summed
ot_rz = ot *100
context = {'userD':customer_object, 'address':address, 'ot':ot_rz }
return render(request, 'checkoutW2.html', context)
def post(self, request, customer_phone):
dtt = dt.datetime.now()
cart = request.session.get('cart')
products = Product.get_products_by_id(list(cart.keys()))
ot = 0
for p in products:
summed = p.price * cart.get(str(p.id))
ot = ot+summed
order_amount = ot
order_currency = 'INR'
order_reciept = ('{}_{}_{}_{}'.format(dtt.day,dtt.month,dtt.year,customer_phone))
# response = client.order.create(amount=order_amount, currency=order_currency, reciept=order_reciept )
# order_id = response['id']
order_status = 'created'
if order_status == 'created':
return render(request,'checkoutW2.html', {'rzp_oid':order_id})
#csrf_exempt
def payment_status(request ):
response = request.POST
phone = request.session.get('customer')
cart = request.session.get('cart')
products = Product.get_products_by_id(list(cart.keys()))
dtt = dt.datetime.now()
customer_object = Customer.objects.filter(phone=phone, date__hour= str(dtt.hour))
customer_object = customer_object.reverse()[0]
address = Addresses.objects.filter(customer=customer_object, date__hour= str(dtt.hour))
address = address.reverse()[0]
params_dict = {
'razorpay_payment_id': response['razorpay_payment_id'],
'razorpay_order_id': response['razorpay_order_id'],
'razorpay_signature': response['razorpay_signature']
}
try:
status = client.utility.verify_payment_signature(params_dict)
for p in products:
O = OrderItemss(customer=customer_object,
item=p,
quantity=cart.get(str(p.id)))
O.save()
OR = Orderss(customer=customer_object,address=address)
OR.save()
orders = OrderItemss.objects.filter(customer=customer_object, date__hour= str(dtt.hour))
for ordr in orders:
O = Orderss.objects.filter(customer=customer_object)
O = O[0]
O.items.add(ordr)
orders = OrderItemss.objects.filter(customer=customer_object, date__hour= str(dtt.hour))
request.session.flush()
request.session.modified = True
order = Orderss.objects.get(customer=customer_object, date__hour= str(dtt.hour))
context = {'userD':customer_object, 'address':address, 'order':orders, 'orders':order, 'status':'sucess'}
return render(request, 'order_summary.html', context)
except:
context = {'userD':customer_object, 'address':address, 'status':'failed'}
return render(request, 'order_summary.html', context)
so l have pulled the data from a movie website and l saved it into variables for example title but now I'm struggling to send this data to MySQL DB
def index(request):
response = requests.get(
'https://fmovies.to/api/list_movies.json',
params={'limit':'20'},
)
json_response = response.json()
movies = json_response['data']['movies']
#title = movies[0]['title']
#movie_url = movies[0]['url']
#description = movies[0]['description_full']
#movie_torrent_link = movies[0]['torrents'][0]['url']
#cover_image = movies[0]['medium_cover_image']
for value in movies:
title = value['title']
movie_url = value['url']
description = value['description_full']
movie_torrent_link = value['torrents'][0]['url']
image = value['medium_cover_image']
rating = value['rating']
genre = value['genres']
runtime = value['runtime']
year_of_production = value['year']
slug = value['slug']
print(image)
print(rating)
print(runtime)
print(year_of_production)
print(slug)
return render(request, 'index.html',{'title':title})
managed to save direct without going the long way l was going
def index(request):
response = requests.get(
'https://fmovies.to/api/list_movies.json',
params={'limit':'20'},
)
json_response = response.json()
movies = json_response['data']['movies']
for value in movies:
save_to_db = Movie.objects.create(
title=value['title'],
description = value['description_full'],
image = value['medium_cover_image'],
category = value['genres'],
year_of_production = value['year'],
movie_url = value['url'],
movie_torrent_link = value['torrents'][0]['url'],
rating = value['rating'],
runtime = value['runtime'],
)
save_to_db.save()
return render(request, 'index.html',)
i have an query_name field in database. i want that every value should be unique so i changed it constraint and add unique= true.
now i want that if user enter the duplicate value then error duplicate value show to the user. currently error is showing only in backend
here is my code in python
def save_report(request):
if request.method == 'POST':
print(request.POST.dict())
data_dict = request.POST.dict()
query_json = {}
#query json data
query_json['data_src_name'] = data_dict['data_src_name']
query_json['fields'] = data_dict['fields']
query_json['group_by'] = data_dict['group_by']
query_json['order_by'] = data_dict['order_by']
query_json['where'] = data_dict['where']
query_json['limit'] = data_dict['limit']
query_json = json.dumps(query_json)
report_creation_obj = ReportCreationData.objects.create(
query_json = query_json,
data_source_name = data_dict['data_src_name'],
query_name = data_dict['query_name'],
mail_body = data_dict['mail_body'])
report_creation_obj.save()
return HttpResponse('success')
else:
return render(request, 'home/report_creation.html', context = None)
database :
query_name = models.CharField(max_length=100,unique= True, default= True)
code 2 :
def save_report(request):
if request.method == 'POST':
print(request.POST.dict())
querydata = ReportCreationData.objects.all()
querydata_list = []
querydata_dict = {'query_name':''}
for data in querydata:
querydata_dict['query_name'] = data.query_name
print ('querydata_dict', querydata_dict)
data_dict = request.POST.dict()
query_name = data_dict['query_name'],
print ('query_name', query_name)
query_json = {}
#query json data
query_json['data_src_name'] = data_dict['data_src_name']
query_json['fields'] = data_dict['fields']
query_json['group_by'] = data_dict['group_by']
query_json['order_by'] = data_dict['order_by']
query_json['where'] = data_dict['where']
query_json['limit'] = data_dict['limit']
query_json = json.dumps(query_json)
report_creation_obj = ReportCreationData.objects.create(
query_json = query_json,
data_source_name = data_dict['data_src_name'],
query_name = data_dict['query_name'],
mail_body = data_dict['mail_body'])
if (query_name == querydata_dict).exists():
raise ('already exists')
else:
report_creation_obj.save()
return HttpResponse('success')
else:
return render(request, 'home/report_creation.html')
with code 2 getting error:
AttributeError: 'bool' object has no attribute 'exists'
Please help
Thanks
You can try before inserting the data,run a select query from database and apply where clause on your query_name with your current value.So by this you can get duplicate records.
Here are my lines dealing with the two forms :
user = request.user
user_liked = user_liked_form.save(commit = False)
user_liked.user = user
user_liked.save()
user_disliked = user_disliked_form.save(commit = False)
user_disliked.user = user
user_disliked.save()
The data submitted in second form is being saved in both liked and disliked.
I have used User foreignkey in both the liked and disliked models.
Here is the complete function :
def collect(request):
context = RequestContext(request)
submitted = False
if request.method == 'POST':
data = request.POST
user_liked_form = UserLikedForm(data = request.POST)
user_disliked_form = UserDislikedForm(data = request.POST)
# user_id = data["user_id"]
user = request.user
if user_liked_form.is_valid() and user_disliked_form.is_valid():
# user_liked_form.save(commit = True)
# user_disliked_form.save(commit = True)
user_liked = user_liked_form.save(commit = False)
user_liked.user = user
user_liked.save()
user_disliked = user_disliked_form.save(commit = False)
user_disliked.user = user
user_disliked.save()
submitted = True
else:
print user_liked_form.errors, user_disliked_form.errors
else:
user_liked_form = UserLikedForm()
user_disliked_form = UserDislikedForm()
return render_to_response(
'collect.html',
{'user_liked_form': user_liked_form, 'user_disliked_form': user_disliked_form, 'submitted': submitted},
context)
It sounds like your UserLikedForm and UserDislikedForm have the same field names and when the form is submitted, only the second value comes through in request.POST. To fix this, you will need to add a prefix to the forms:
user_liked_form = UserLikedForm(prefix='liked')
user_disliked_form = UserDislikedForm(prefix='disliked')
That way when the forms are rendered, each form will have unique field names.
I'm working on a inventory control in Django and i want a form to control the action that will be made. If a record for the product already exist, it should update the quantity. If it doesn't exist, it should create the record for it. Besides that, one form field will have three choices. One will add the form value to que product quantity, other will subtract and another one will change to the value in the form.
The model is quite big, because i set some choices for the form fields. There it is:
from django.db import models
from django import forms
from django.forms import ModelForm
class Produto(models.Model):
CAMISA = "CM"
QUADRO = "QD"
CANECA = 'CN'
ESCOLHAS_PRODUTO = (
(CAMISA, 'Camisa'),
(QUADRO, 'Quadro'),
(CANECA, 'Caneca'),
)
tipo = models.CharField(max_length = 40,
choices=ESCOLHAS_PRODUTO,
default=CAMISA)
class Camisa(Produto):
MASCULINA = 'MA'
FEMININA_BASICA = 'FB'
FEMININA_GOLA_V = 'FV'
INFANTIL = 'IN'
MODELO_CAMISA = (
(MASCULINA, 'Masculina'),
(FEMININA_BASICA, 'Feminina Basica'),
(FEMININA_GOLA_V, 'Feminina Gola V'),
(INFANTIL, 'Infantil'),
)
modelo = models.CharField(max_length = 50,
choices=MODELO_CAMISA,
)
AMARELA = 'AM'
AZUL_CLARO = 'AC'
AZUL_ESCURO = 'AE'
BRANCA = 'BR'
CINZA = 'CI'
LARANJA = 'LA'
MARFIM = 'MA'
ROSA = 'RO'
PRETA = 'PR'
VERDE_MUSGO = 'VM'
VERMELHA = 'VR'
CORES_CAMISA = (
(AMARELA, 'Amarela'),
(AZUL_CLARO, 'Azul Claro'),
(AZUL_ESCURO, 'Azul Escuro'),
(BRANCA, 'Branca'),
(CINZA, 'Cinza'),
(LARANJA, 'Laranja'),
(MARFIM, 'Marfim'),
(ROSA, 'Rosa'),
(PRETA, 'Preta'),
(VERDE_MUSGO, 'Verde Musgo'),
(VERMELHA, 'Vermelha'),
)
cor = models.CharField(max_length = 40,
choices=CORES_CAMISA,
)
TAMANHO_P = 'TP'
TAMANHO_M = 'TM'
TAMANHO_G = 'TG'
TAMANHO_GG = 'GG'
TAMANHO_XG = 'XG'
TAMANHO_02_ANOS = '02'
TAMANHO_04_ANOS = '04'
TAMANHO_06_ANOS = '06'
TAMANHO_08_ANOS = '08'
TAMANHO_10_ANOS = '10'
TAMANHO_12_ANOS = '12'
TAMANHO_14_ANOS = '14'
TAMANHO_CAMISA = (
(TAMANHO_P, 'P'),
(TAMANHO_M, 'M'),
(TAMANHO_G, 'G'),
(TAMANHO_GG, 'GG'),
(TAMANHO_XG, 'XGG'),
(TAMANHO_02_ANOS, '2 Anos'),
(TAMANHO_04_ANOS, '4 Anos'),
(TAMANHO_06_ANOS, '6 Anos'),
(TAMANHO_08_ANOS, '8 Anos'),
(TAMANHO_10_ANOS, '10 Anos'),
(TAMANHO_12_ANOS, '12 Anos'),
(TAMANHO_14_ANOS, '14 Anos'),
)
tamanho= models.CharField(max_length = 50,
choices=TAMANHO_CAMISA,
)
quantidade = models.IntegerField()
def __unicode__(self):
return self.modelo
class CamisaForm(ModelForm):
ADICIONAR = 'ADC'
REDUZIR = 'RED'
ALTERAR = 'ALT'
ACOES = (
(ADICIONAR, 'Adicionar Quantidade'),
(REDUZIR, 'Reduzir Quantidade'),
(ALTERAR, 'Alterar para Quantidade'),
)
acoes = forms.ChoiceField(
choices=ACOES,
)
class Meta:
model = Camisa
And the following view:
def index(request):
produtos_estoque = Camisa.objects.all()
template = 'estoque/index.html'
modelos_camisa = {'MA' : 'Masculina Basica','FB' : 'Feminina Basica','FV' : 'Feminina Gola V','IN' : 'Infantil' }
if request.method == 'POST':
form = CamisaForm(request.POST)
if form.is_valid():
try:
produto_atualizar = Camisa.objects.get(modelo = request.POST['modelo'], cor = request.POST['cor'], tamanho = request.POST['tamanho'])
if request.POST['acoes'] == 'ADC':
produto_atualizar.quantidade = produto_atualizar.quantidade + request.POST['quantidade']
elif request.POST['acoes'] == 'RED':
produto_atualizar.quantidade = produto_atualizar.quantidade - request.POST['quantidade']
elif request.POST['acoes'] == 'ALT':
produto_atualizar.quantidade = request.POST['quantidade']
produto_atualizar.save()
except:
produto_atualizar = form.save()
return HttpResponseRedirect('')
else:
form = CamisaForm()
return render_to_response(template, { 'form': form, 'produtos_estoque': produtos_estoque,
'modelos_camisa' : modelos_camisa.iteritems(), }, context_instance=RequestContext(request))
But what is happening is that the form is just creating another record for the product, even if it already exists. Not sure if the rest of the model is important for this question, will post it if necessary. Can somebody help me on this one? Thanks
Please post the Model this is acting on - it will have some useful information, like constraints or lack thereof etc. OK cool, no unique constraints in there causing insert violations.
First thing I would recommend is using the forms cleaned_data to access form values instead of the raw POST data, form.is_valid() does a lot of work to process the raw data into acceptable inputs for Model data.
Second thing is that except clause will catch ANY exception which I suspect is your problem... Something else is going wrong which is creating the new record in the except clause. Be specific, like except Camisa.DoesNotExist:
Third thing is to put those constants on the Model so you can reference them from the Form and View instead of literal strings. This is just a cleanliness / code style recommendation.
A little cleanup might look like:
MODELOS_CAMISA = {'MA' : 'Masculina Basica','FB' : 'Feminina Basica','FV' : 'Feminina Gola V','IN' : 'Infantil' }
def index(request):
produtos_estoque = Camisa.objects.all()
if request.method == 'POST':
form = CamisaForm(request.POST)
if form.is_valid():
try:
produto_atualizar = Camisa.objects.get(modelo=form.cleaned_data.get('modelo'), cor=form.cleaned_data.get('cor'), tamanho=form.cleaned_data.get('tamanho'))
quantidade = form.cleaned_data.get('quantidade')
acoes = form.cleaned_data.get('acoes')
if acoes == Camisa.ADC:
produto_atualizar.quantidade = produto_atualizar.quantidade + quantidade
elif acoes == Camisa.RED:
produto_atualizar.quantidade = produto_atualizar.quantidade - quantidade
elif acoes == Camisa.ALT:
produto_atualizar.quantidade = quantidade
produto_atualizar.save()
except Camisa.DoesNotExist:
produto_atualizar = form.save()
return HttpResponseRedirect('')
else:
form = CamisaForm()
return render_to_response('estoque/index.html', { 'form': form, 'produtos_estoque': produtos_estoque,
'modelos_camisa' : MODELOS_CAMISA.iteritems(), }, context_instance=RequestContext(request))
(Sorry for any grammatical errors, my Portuguese is not great)
That should be enough to get you started, if you add more information I can edit and elaborate my answer. Good luck!