Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe payment do something when payment is successfull Django
I have an app about posting an advertises and by default i made an expiration date for every advertise (30 days) now i wanna use stripe to extend the expiration date. what i have so far is the checkout but i want when the payment i success i update the database. my checkout view : class StripeCheckoutView(APIView): def post(self, request, *args, **kwargs): adv_id = self.kwargs["pk"] adv = Advertise.objects.get(id = adv_id) try: adv = Advertise.objects.get(id = adv_id) checkout_session = stripe.checkout.Session.create( line_items=[ { 'price_data': { 'currency':'usd', 'unit_amount': 50 * 100, 'product_data':{ 'name':adv.description, } }, 'quantity': 1, }, ], metadata={ "product_id":adv.id }, mode='payment', success_url=settings.SITE_URL + '?success=true', cancel_url=settings.SITE_URL + '?canceled=true', ) return redirect(checkout_session.url) except Exception as e: return Response({'msg':'something went wrong while creating stripe session','error':str(e)}, status=500) Models: # Create your models here. class Advertise(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="advertise") category = models.CharField(max_length= 200, choices = CATEGORY) location = models.CharField(max_length= 200, choices = LOCATIONS) description = models.TextField(max_length=600) price = models.FloatField(max_length=100) expiration_date = models.DateField(default = Expire_date, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) #is_active class Meta: ordering = ['created_at'] def __str__(self): return self.category So what i want to do is check if the payment is successful nad if so i extend … -
how to connect to a sql server database remotely via internet in pythonConnect to a database not on the same network with python/django
I would like to connect to a server on a machine located on a different network from mine in order to connect to its database. How to do? Until now I only worked with databases located on the same local network but now I have to interact with those located on another server. I develop with django/python. The image I added below is the connection to several databases but on a local network, but as I said I want to interact with other databases located in another city. -
Django: How do I create a form of model A for each instance of model B
I am trying to create an app, where the user fills out forms (model B). The forms are based on variables (model A), which are defined by the admin. The form should save the input in model B (i.e. input values) and therefore show the name/label of model A (i.e. the variable name) for each instance of A and the corresponding fields of B (the input value). I am stuck with showing each input form separately. Technically this works, but creates a terrible user experience. How do I render all input forms for each variable on one page? I would appreciate any help greatly! Model A (variables): class Variable(models.Model): visit = models.ForeignKey(Visit, on_delete=models.CASCADE, default="") var_id = models.CharField(max_length=20, default="") var_label = models.CharField(max_length=20, default="") NUM = 'NUM' INT = 'INT' CHAR = 'CHA' DATE = 'DAT' BOOL = 'BOO' DATA_TYPES = [ (NUM, 'Numeric'), (INT, 'Integer'), (CHAR, 'Character'), (DATE, 'Date'), (BOOL, 'Boolean'), ] widget_type = models.CharField( max_length=3, choices=DATA_TYPES, default=CHAR, ) max = models.FloatField(max_length=20, default=0) min = models.FloatField(max_length=20, default=10) pub_date = models.DateTimeField('date published', default=timezone.now) description = models.CharField(max_length=200, default="") def __str__(self): return self.var_id Model B (input values): class InputValue(models.Model): submission = models.ForeignKey(Submission, on_delete=models.CASCADE, default="") variable = models.ForeignKey(Variable, on_delete=models.CASCADE, default="") value_char = models.CharField(max_length=128, default="NA") value_numeric … -
Updating the URLField of model with JavaScript
I have a page that displays some information about website admins such as username, skills, Instagram profile and bio. The admins are able to edit their profile information and the update is being saved using JavaScript fetch. When I click on the save button everything except the Instagram profile which is a URLField gets updated. For Instagram element to be updated I need to reload the page. How can I make it get updated without reloading the page? Everything is correct in the console log. about.js: document.addEventListener("DOMContentLoaded", function(){ const button = document.querySelectorAll("#edit_profile") button.forEach(function(button){ button.onclick = function(){ const username = document.getElementById(`username_${memberID}`); const skills = document.getElementById(`skills_${memberID}`); const bio = document.getElementById(`bio_${memberID}`); var instagram = document.getElementById(`instagram_${memberID}`).href; let edit_username = document.createElement("textarea"); edit_username.setAttribute("rows", "1"); edit_username.innerHTML = username.innerHTML edit_username.id = `edit_username_${memberID}`; edit_username.className = `form-control username ${usernameID}`; let edit_skills = document.createElement("textarea"); ... let edit_instagram = document.createElement("textarea"); edit_instagram.setAttribute("rows","1"); edit_instagram.innerHTML = instagram; edit_instagram.id = `edit_instagram_${memberID}`; edit_instagram.className = "form-control social-media"; const saveButton = document.createElement("button"); saveButton.innerHTML = "Save"; saveButton.id = `saveButton_${memberID}`; saveButton.className = "btn btn-success col-3"; saveButton.style.margin = "10px"; document.getElementById(`edit_${memberID}`).append(edit_username); ... document.getElementById(`edit_${memberID}`).append(edit_instagram); document.getElementById(`edit_${memberID}`).append(saveButton); // When the save button is clicked saveButton.addEventListener("click", function(){ edit_username = document.getElementById(`edit_username_${memberID}`); ... edit_instagram = document.getElementById(`edit_instagram_${memberID}`); fetch(`/edit_profile/${memberID}`,{ method: "POST", body: JSON.stringify({ username: edit_username.value, skills: edit_skills.value, instagram: edit_instagram.value, bio: edit_bio.value, … -
Django static and media files + DigitalOcean Spaces
Hy everyone! This is my first time trying to connect a Django project (which is in DigitalOcean App Platform) with DigitalOcean Spaces. I created 3 folders inside Spaces: static, media and staticfiles. I noticed however that when I run 'collectstatic', all static files are copied not to the 'staticfiles' folder but to the root-level. If I visit the domain name, the static files are visible: both the images and the css and javascript files. Conversely, media files are not displayed. Inspecting the code via google developer tools I noticed that the src attributes of the img tags try to find both static and media files at the root level. This is what I tried to do. I installed 'django-storages', included it in 'INSTALLED_APPS' and then put this code in settings.py: AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') # AWS_S3_CUSTOM_DOMAIN = os.getenv('AWS_S3_CUSTOM_DOMAIN') AWS_S3_REGION_NAME = '<REGION_NAME>' AWS_S3_ENDPOINT_URL = os.getenv('AWS_S3_ENDPOINT_URL') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_DIRS = [BASE_DIR / "static"] MEDIA_URL = 'https://<REGION_NAME>.digitaloceanspaces.com/<BUCKET_NAME>/media/' STATIC_URL = 'https://<REGION_NAME>.digitaloceanspaces.com/<BUCKET_NAME>/static/' MEDIA_ROOT = 's3://<REGION_NAME>.digitaloceanspaces.com/<BUCKET_NAME>/media' STATIC_ROOT = 's3://<REGION_NAME>.digitaloceanspaces.com/<BUCKET_NAME>/staticfiles' In 'django-storages' docs I saw that STATICFILES_STORAGE should be like this: STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' but this way the static files were not loaded (css, images, js ecc.) -
While adding my project to GitHub, do I also have to add the virtual environment folder and subsequently commit and push it or I can skip it?
I just finished with my project and was going to put it on GitHub but I have this doubt regarding the venv folder. Below is the screenshot of my folder-structure; Please guide me as this is my first time using GitHub and this is my first project too. -
Nginx with Django and Gunicorn working with IP but not with domain name
I have been trying to setup my Django backend since 2days but i can't get it to work with my domain name. I have the Next Frontend on Nginx(Port :80) too but it seems to work fine with domain name. But i did the same setup in backend with port 8000 i can't access it using the domain name but works fine with IP. I have tried everything found on the internet but nothing seems to work. Config for the frontend (Working with domain) server{ listen 80; listen [::]:80; listen 443 ssl; include snippets/snakeoil.conf; server_name {domainName}; location = /favicon.ico { access_log off; log_not_found off; } location / { # reverse proxy for next server proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_headers_hash_max_size 512; proxy_headers_hash_bucket_size 128; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } Config for backend (Not working with domain name) server { listen 8000; listen [::]:8000; server_name dev.liqd.fi ipaddress; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/backend/lithexBackEnd; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Allowed Hosts ALLOWED_HOSTS = ['localhost','127.0.0.1','ip address','*.domain.com','domain.com'] The Gunicorn has been setup and tested and seems to be working fine . The error log of … -
How to make forms which users can add | Django
I want to make something like google forms which users can make themselfs. I want just simple html string forms which can reveal answer and check is it right instantly. No matter how users will create forms, but only using webpage. Without additional connecton to DB. Using only one field in column in DB. Maybe forms can be like this using just html (best variation) -
Optimise django manytomany relation
I was wondering if there is a way to make this more optimised. class AppTopic(models.Model): topic = models.CharField(max_length=20) # lowercase (cookies) class UserTopic(models.Model): topic = models.CharField(max_length=20) # Any case (cOoKiEs) app_topic = models.ForeignKey(AppTopic) # related to (cookies -> lowercase version of cOoKiEs) class User(models.Model): topics = models.ManyToManyField(UserTopic) # AppTopic stored with any case The goal is to have all AppTopics be lowercase on the lowest level, but I want to allow users to chose what capitalisation they want. In doing so I still want to keep the relation with it's lowercase version. The topic on the lowest level could be cookies, the user might pick cOoKiEs which should still be related to the orignal cookies. My current solution works, but requires an entirely new table with almost no use. I will continue using this if there isn't really a smarter way to do it. -
django query: stuck trying to display only one instance of the model per id
I am writing a conversation module for a django app and I am failing desperately at buildin g a side menu that shows for each conversation: the name of the recipient the last message in the conversation the timestamp of that last message I am struggling to write an accurate query. conversations = ChatRoom.objects.filter(building=building.building_id, participants__in=[user]).prefetch_related( 'participants','chat_set').order_by('-chat__timestamp') the issue with this query is that it returns one chatroom object per message, and therefore in template the following code: <ul class="flex flex-col space-y-1 mt-4 -mx-2 overflow-y-auto" style="height:300px"> <h2 class="my-2 mb-2 ml-2 text-lg text-gray-600">Chats</h2> {% for convo in conversations %} <li> {% if convo.chat_set.last.content %} {% for participant in convo.participants.all %} {% if participant.id != request.user.id %} <a href="{% url 'room' room_id=convo.id %}" class="flex items-center px-3 py-2 text-sm transition duration-150 ease-in-out border-b border-gray-300 cursor-pointer hover:bg-gray-100 focus:outline-none"> <div class="w-10 h-10 rounded-full border-2 border-black flex justify-center items-center m-2"> <span> {{ participant.username|first|upper }}</span> </div> <div class="w-full pb-2"> <div class="flex justify-between"> <span class="block ml-2 font-semibold text-gray-600"> {{ participant.username }}</span> <span class="block ml-2 text-sm text-gray-600">{{ convo.chat_set.last.timestamp}}</span> </div> <span class="block ml-2 text-sm text-gray-600">{{ convo.chat_set.last.content }}</span> </div> </a> {% endif %} {% endfor %} </li> {% for %} {% endfor %} </ul> shows one line per message sent, instead of … -
Case sensitves django
I tried to put this code to deactivate the sensitivity of the characters when logging in, but it does not work. What is the problem with it? It still appears to me. Please consider the sensitivity of the characters I want to use this method. I do not want to use the backend method Please help me find the problem class CustomUserManager(UserManager): def get_by_natural_key(self, username): return self.get(username__iexact=username) class User(AbstractBaseUser): """ Decapolis main User model """ username = models.CharField(max_length=40, unique=True) email = models.CharField(max_length=40, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) company = models.ForeignKey(settings.COMPANY_MODEL, on_delete=models.CASCADE, related_name='user_company', null=True, blank=True) roles = models.ManyToManyField(Role, blank=True) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def has_role(self, role_name): """ Check user has role :param role_name: role name to check :type role_name: str :return: True or False :rtype: bool """ return True if role_name in self.roles else False def has_perm(self, perm, obj=None): """ Does the user have a specific permission? Not implemented yet :param perm: permission to check :type perm: str :param obj: object to check :type obj: :return: :rtype: """ # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): … -
I can't create another custom user model to override the one I had created before, when I do and perform migrations it is clashing with the new one
I had created a customer user model to override the already existing one Django provides, but I want to make a lot of changes on it including changing the name, like completely starting over in another app but in the same project but looks like I'm getting errors while trying to do migrations. Thought that if I changed the database and performed migrations it would work but it didn't, they say this: ERRORS: user.UserAccountModel.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'user.UserAccountModel.groups' clashes with reverse accessor for 'userAccount.UserModel.groups'. HINT: Add or change a related_name argument to the definition for 'user.UserAccountModel.groups' or 'userAccount.UserModel.groups'. user.UserAccountModel.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'user.UserAccountModel.user_permissions' clashes with reverse accessor for 'userAccount.UserModel.user_permissions'. HINT: Add or change a related_name argument to the definition for 'user.UserAccountModel.user_permissions' or 'userAccount.UserModel.user_permissions'. userAccount.UserModel.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'userAccount.UserModel.groups' clashes with reverse accessor for 'user.UserAccountModel.groups'. HINT: Add or change a related_name argument to the definition for 'userAccount.UserModel.groups' or 'user.UserAccountModel.groups'. userAccount.UserModel.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'userAccount.UserModel.user_permissions' clashes with reverse accessor for 'user.UserAccountModel.user_permissions'. HINT: Add or change a related_name argument to the definition for 'userAccount.UserModel.user_permissions' or 'user.UserAccountModel.user_permissions'. Hint: My first custom model was 'UserModel' in userAccount app and now i changed it to 'UserAccountModel' in user … -
Django Rest Framework fail on setting a new context to the serializer
Django time: I am facing an issue with providing a context to the serializer: class CommentSerializer(serializers.ModelSerializer): likes = CustomUserSerializer(many=True,source='likes.all') class Meta: fields = 'likes', model = models.Comment def get_user_like(self,obj): for i in obj.likes.all(): if self.context['user'] in i.values(): return self.context['user'] in the view: class CommentView(viewsets.ModelViewSet): serializer_class = serializer.CommentSerializer def get_serializer_context(self): #adding request.user as an extra context context = super(CommentView,self).get_serializer_context() context.update({'user':self.request.user}) return context as you can see, i have overridded get_serializer_context to add user as a context however, in the serializer side, i am getting KeyError:'user' means the key does not exist, any idea how to set a context? -
How can I change titles in action section in Django admin panel?
I want to change titles in action section in Django admin. How can I do that? -
Is it database level or related to programming
Hello all of my friends I was in a job interview and the interviewer asked me this question "Suppose we have to get all the members of a database table and not all of them fit in RAM, what would you do?" .I didn't know the exact answer and the only answer that came to my mind was to use a generator and I would like to know the answer of the people who worked in this field. So the following are my questions. 1)What is the answer to the interviewer's question (please explain a bit) 2)Is Generator in python use just for Put and Post Method or is used to for Get method in Django (i mean generator just use for write and change database or used for get a list of items too )(When I was reading about the topic of the generator, it was always said that instead of bringing the items to the RAM at once, the generator brings and changes the items one by one and stores them in the database and goes to the next item, and i thought that whenever we want change or update go to the generator) -
objects.last() or objects.latest('id') ? which one is faster ?(django)
i need to get the most recent data of a table in django but I want the fastest way to do this. which one is fastest? foo.objects.latest("id") foo.objects.last() or should i use get() with one of above methods ? -
Are there any libraries for Python to implement Audit Trail in MySQL?
I want to implement audit trail for FastAPI and Django applications but cannot find any updated packages for such task I tried searching on the web and found a package called django-audittrail but its last update was in 2020 -
Django validate fileds on form
I can`t understand how to return error in template I making check on valid in my from FORMS.py class UserForm(forms.Form): first_name= forms.CharField(max_length=20, label='Name') last_name= forms.CharField(max_length=20, label='Last_name') password= forms.CharField(label='Password') repassword= forms.CharField(label='Confirm password') def clean(self): cleaned_data = super().clean() self.password = cleaned_data('password') self.repassword = cleaned_data('repassword') if self.password != self.repassword: raise ValidationError('Password dont match') VIEW.py def index(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST or None) if form.is_valid(): firstname= form.cleaned_data.get("first_name") lastname= form.cleaned_data.get("last_name") password = form.cleaned_data.get('password') re_password = form.cleaned_data.get('repassword') form = UserForm() context = {'form': form, } return render(request, 'create_users/index.html', context) return render(request, 'create_users/index.html', {'form': form} As result i see this when update my template dict' object is not callable -
The "pip install django" command gets an error, how do I solve it?
pip install django Collecting django WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl ERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/2d/ac/9f013a51e6008ba94a282c15778a3ea51a0953f6711a77f9baa471fd1b1d/Django-4.1.5-py3-none-any.whl (Caused by ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")) I tried the following methods but it didn't work pip install --trusted-host=pypi.python.org --trusted-host=pypi.org --trusted-host=files.pythonhosted.org django pip install django --user (not working in venv) -
Using random generator in django
views.py class PostListView(ListView): model = Post template_name = 'feed/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: liked = [i for i in Post.objects.all() if Like.objects.filter( user=self.request.user, post=i)] context['liked_post'] = liked return context home.html <div> {% for post in posts %} <div> <a href="{{ post.user_name.profile.get_absolute_url }}"> <img src="{{ post.user_name.profile.image.url }}" class="rounded-circle" width="30" height="30" alt=""></a> <a href="{{ post.user_name.profile.get_absolute_url }}"><b>{{ post.user_name }}</b></a> <br><small >Posted on {{ post.date_posted }}</small> <br><br> <p >{{ post.description }}</p> </div> {% end for %} </div> i want to add carousel in the above template for that i want random object (with 4 objects ) so how can i use random objects and where? Help me in using random object generator in django ? -
Problem with separating images using Django
hi I am loading images using Django but I want to sperate images which end with jpg and png , how do I do that ? thank you . -
how to updata all changes on database as one block
I have this code for i in range(100): table2.objects.create(id = i, some_extra_fields) how to upload all database changes one time in one query -
Aggregate in model property result in extra queries
My example: class Product(models.Model): name = models.CharField(max_length=50) category = models.ManyToManyField("wms.ProductCategory", blank=True) @property def quantity_in(self): return self.intodocumentproduct_set.aggregate(total=Sum('quantity_in', default=0))['total'] class IntoDocumentProduct(models.Model): product = models.ForeignKey("wms.Product", on_delete=models.CASCADE) quantity_in = models.FloatField(blank=True, null=True) class ProductListAPIView(ListAPIView): # queryset = Product.objects.prefetch_related('category').annotate(sum_quantity_in=Sum('intodocumentproduct__quantity_in', default=0)).all() queryset = Product.objects.prefetch_related('category').all() serializer_class = ProductModelSerializer Commented queryset results in 4 queries while other query (using property) results in 6 queries. Probably n+ problem. I have to use properties like: quantity_ordered, quantity_reserved, quantity_out, quantity_in, quantity_stock, quantity_available, quantity_pending_release and more in many places in web app. Calculating them in every view will be time comsuming and error susceptible. This solution is not very handy when property is used in many views with many properties. Is there any other solution to remove extra queries? -
is it possible to add db_index = True to a field that is not unique (django)
I have a model that has some fields like: current_datetime = models.TimeField(auto_now_add=True) new_datetime = models.DateTimeField(null=True, db_index=True) and data would be like : currun_date_time = 2023-01-22T09:42:00+0330 new_datetime =2023-01-22T09:00:00+0330 currun_date_time = 2023-01-22T09:52:00+0330 new_datetime =2023-01-22T09:00:00+0330 currun_date_time = 2023-01-22T10:02:00+0330 new_datetime =2023-01-22T10:00:00+0330 is it possible new_datetime to have db_index = True ? the reason i want this index is there are many rows (more than a 200,000 and keep adding every day) and there is a place that user can choose datetime range and see the results(it's a statistical website). i want to send a query with that filtered datetime range so it should be done fast. by the way i am using postgresql also if you have tips for handling data or sth. like that for such websites i would be glad too hear thanks. -
HELLO CAN ANYONE HELP ME OUT , I AM EXHAUSTED NOW, PLEASE HELP ME
[settings.py ' gaierror: [Errno 11003] getaddrinfo failed' i am getting this error. ](https:/ /i.stack.imgur.com/OTCj4.png) i am trying this way but not enter image description heregetting accurate output.