Getting Error while Import razorpay in django - django

I am integrating razorpay payment gateway in django project but i am getting error while importing razorpay as :- Import razorpay could not be resolved
from django.shortcuts import render
import razorpay # Here i am getting error
from .models import coffee
This is my full code
from django.shortcuts import render
import razorpay
from .models import coffee
# Create your views here.
def index(request):
if request.method=='POST':
Name = request.POST.get("Name")
Amount = int(request.POST.get("Amount")) * 100
client = razorpay.Client(auth= ("rzp_test_YhfEhfejrkkjdkfju","t5MRPkjfijdh23845kejkej"))
payment = client.order.create({'Amount':Amount, 'currency':'INR','payment_capture':'1'})
print(payment)
Coffee = coffee(Name=Name, Amount=Amount , payment_id = payment['id'] )
return render(request,'index.html',{'payment':payment})
return render(request,'index.html')
def success(request):
if request.method == 'POST':
a = request.POST
print(a)
return render(request,"success.html")
This is my terminal
File "D:\Project 3\payment\paymentapp\urls.py", line 18, in <module>
from .import views
File "D:\Project 3\payment\paymentapp\views.py", line 3, in <module>
import razorpay
ModuleNotFoundError: No module named 'razorpay'

There are few basic thing you have to know before using razorpay gateway in you project first is your amount is considered in paisa so you have to * 100 to converte it in to rupee as I can see you are multiplying * 10 to amount next if you want to use razorpay you must use
pip install razorpay
And I will also recommend you to read the full documentation for using becuase seems that you are missing lot of thing like you have to write JavaScript code handle etc.
https://razorpay.com/docs/payment-gateway/web-integration/standard/

Related

Save zip to FileField django

I have a view that create two csv and my goal is to zip them and add to a model.FileField
zip = zipfile.ZipFile('myzip.zip','w')
zip.writestr('file1.csv', file1.getvalue())
zip.writestr('file2.csv', file2.getvalue())
I have tried this, the zip is upload but when I download it I have the error 'the archive is damaged or unknown format'
Mymodel.objects.create(zip = File(open('myzip.zip','rb'))
This example just worked for me,
from django.core.files import File
from django.http import HttpResponse
from .models import ZipFile
import zipfile
from django.views import View
class ZipWriteView(View):
def get(self, request, *args, **kwargs):
with zipfile.ZipFile("myzip.zip", "w") as zip_obj:
zip_obj.write("polls/views.py") # add file 1
zip_obj.write("polls/admin.py") # add file 2
with open(zip_obj.filename, "rb") as f:
ZipFile.objects.create(file=File(f))
return HttpResponse("Done")

How to upload file on Django REST endpoint quickly?

I am using Django REST framework to upload a large csv file and extract the data from the file and save the data in the data. By large file I mean file of like 10 to 50mb but when I upload a file its taking way longer then expected like 10 to 15mins but the endpoint keeps on processing and does not returns the response here is how my views.py looks like:
from asyncore import read
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
import pandas as pd
from .models import ExtractedData
from .urls import urlpatterns
from django.urls import path
# Create your views here.
class FileUploadView(APIView):
parser_classes = ( MultiPartParser, FormParser)
def put(self, request, format=None):
file_obj = request.FILES['file']
df = pd.read_csv(file_obj)
dict_data = df.to_dict(orient='records')
for dict in dict_data:
ExtractedData.objects.get_or_create(data=dict)
return Response({'details':"File Saved Succesfully"}, status=204)

Flask AssertionError: View function mapping is overwriting an existing endpoint function: home

I'm trying to code a social network with flask on python anywhere
, everything was working fine before and without touching the imports I started to receive this error when I run routes.py
Traceback (most recent call last):
File "/home/OurHub/mysite/routes.py", line 13, in <module>
def home():
File "/usr/local/lib/python3.9/site-packages/flask/scaffold.py", line 433, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "/usr/local/lib/python3.9/site-packages/flask/scaffold.py", line 54, in wrapper_func
return f(self, *args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1084, in add_url_rule
raise AssertionError(
AssertionError: View function mapping is overwriting an existing endpoint function: home
I tried to put everything in a single file and I don't have two functions that have the same name
here is the start of my routes.py code
import os
import secrets
from PIL import Image
from flask import render_template, url_for, flash, redirect, request, abort
from __init__ import app, db, bcrypt
from forms import FormCreerCompte, FormConnecter, ModifierCompte, FormPoste
from modelsdb import Profil, Poste
from flask_login import login_user, current_user, logout_user, login_required
#app.route("/")
#app.route("/home")
def home():
page = request.args.get('page',1, type=int)
posts = Poste.query.paginate(page=page, per_page=5)
return render_template('page1.html', posts=posts)
and the code from the innit file:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = '6dfde280ba245'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://OurHub:ninjQ#OurHub.mysql.pythonanywhere-services.com/OurHub$default'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view= 'connecter'
login_manager.login_message_category = 'primary'
import routes
After a lot of research, I tried to delete a piece of code that I had commented in my html file and it worked! Maybe because the html comment "<!-->" doesn't work with python code inserts "{%%}". The error still appears when I run route, but the application works fine, I was looking for the error in the wrong place after all.

Attribute Error in Uploading Excel File to Django

I am having trouble uploading excel file to my django application. It is a very simple application that should allow a user to upload an excel file with 3 columns. The application will read the contents of this file and process it into bunch of calculations
here is my forms.py:
class InputForm(forms.Form):
FileLocation = forms.FileField(label='Import Data',required=True,widget=forms.FileInput(attrs={'accept': ".xlsx"}))
settings.py:
FILE_UPLOAD_HANDLERS = ["django_excel.ExcelMemoryFileUploadHandler",
"django_excel.TemporaryExcelFileUploadHandler"]
views.py:
import xlrd
from django.shortcuts import render_to_response, render
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.template.context_processors import csrf
from io import TextIOWrapper
from WebApp.forms import *
from django.core.mail import send_mail
from django.utils.safestring import mark_safe
from django.db import connection
import os
import csv
def analyze(request):
if request.method == 'POST':
form = InputForm(request.POST,request.FILES['FileLocation'])
if form.is_valid():
book = xlrd.open_workbook(request.FILES('FileLocation'))
for sheet in book.sheets():
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
print(number_of_rows)
I upload the file in the form and it gives me an error:
AttributeError at /app/analyze/
'ExcelInMemoryUploadedFile' object has no attribute 'get'
Request Method: POST
Request URL: http://127.0.0.1:8000/data/analyze/
Django Version: 1.11
Exception Type: AttributeError
Exception Value:
Exception Location: C:\Python36\lib\site-packages\django\forms\widgets.py in value_from_datadict, line 367
Python Executable: C:\Python36\python.exe
Python Version: 3.6.4
I am also able to upload a .csv file successfully using the following views.py code:
def analyze(request):
c={}
context = RequestContext(request)
c.update(csrf(request))
abc=['a','b','c']
if request.method == 'POST':
form = InputForm(request.POST,request.FILES)
dataType = request.POST.get("DataType")
print(dataType)
if form.is_valid():
cd = form.cleaned_data #print (cd)
a = TextIOWrapper(request.FILES['FileLocation'].file,encoding='ascii',errors='replace')
#print (request.FILES.keys())
data = csv.reader(a)
row1csv = next(data)
region = row1csv[0]
metric = row1csv[2]
I have tried django-excel with same error.
You're correctly initialising your form for the .CSV case but not in your Excel case:
form = InputForm(request.POST, request.FILES)
Don't initialise using request.FILES['FileLocation'] as that's passing the wrong type to the form. It's expecting a MultiValueDict of uploaded files, not a single uploaded file. That's why it fails when calling get on it.
Next, you can't pass an ExcelInMemoryUploadedFile to xlrd.get_workbook(). You need to save the file to disk first, then pass it's path to the get_workbook() method. The documentation of django-excel gives some easier methods:
book = request.FILES['FileLocation'].get_book() # note the square brackets!
or to directly access a sheet:
sheet = request.FILES['FileLocation'].get_sheet('sheet1')

AttributeError: type object 'DeleteAccount' has no attribute 'DAccount'

I'm using Python 2.7, webapp2 and GAE for developing a web app.
I'm facing a problem which i don't understand, since I know what it means but everything I did seems correct.
I get the error
AttributeError: type object 'DeleteAccount' has no attribute 'DAccount'
when i try to access the URL myappdomain/DeleteAccount/
I imported in the main file the python file DeleteAccount.py
import DeleteAccount
I linked the URL with the relative class DAccount of DeleteAccount
webapp2.Route(r'/DeleteAccount/',DeleteAccount.DAccount)
That's my DeleteAccount.py file
import logging
import webapp2
from webapp2_extras import sessions
import datastore
import FBLogin
class BaseHandler(webapp2.RequestHandler):
def dispatch(self):
self.session_store = sessions.get_store(request=self.request)
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response)
#webapp2.cached_property
def session(self):
return self.session_store.get_session()
class DAccount(BaseHandler):
def get(self):
w = self.response.write
logging.info("deleting account")
w('I've deleted the account')
What's wrong? I did what I've done with every other module and everything has worked well with them