Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form get_or_created with 3 different variable
I'm trying to created or update a django form. There's 3 unique identifier in that form, NRIC, MRN or Passport. User can fill any or all of them. the problem is how do I check with the database whether I need to create or update an existing one. so my code is like this: if request.method == 'POST': form = PatientForm(request.POST) if form.is_valid(): nric = form.cleaned_data['nric'] mrn = form.cleaned_data['mrn'] passport = form.cleaned_data['passport'] try: if nric: #if user filled in nric, check database by nric patient = Patient.objects.get(nric=nric) patient.nric = nric if mrn: patient = Patient.objects.get(mrn=mrn) patient.mrn=mrn if passport: patient = Patient.objects.get(passport=passport) patient.passport = passport patient.name = form.cleaned_data['name'] patient.save() except Patient.DoesNotExist(): form.save() The problem start when user filled another 1 of those 3 unique identifier, eg: there's already a record with Passport = 34234234, then user filled another MRN with new value..so 2 of 3 fields now have values, it will fail the check because of object.get(mrn=mrn). any ideas on how can I solve this? Thanks -
Multiplayer game using Django
I'm trying to know if it is possible or not to create an online multiplayer game using Django framework, python socket for TCP connection and Javascript for the animations. Is it possible to handle different server for each game launched? Write the functional script in python and using it with Javascript? I read a lot about Node.JS and this seems to be a much more suitable solution however I didn't use it yet. If this is the best solution, how many time do you think it will take to learn the basics of this framework? Thanks a lot for your help it is very appreciated. :) -
Extract image tag from content of database using django
I have this type of content stored in the database. This is saved via ckeditor. There are two ways to invoke the API: Sending HTTP requests and parsing the responses. Using........................................ What I want is to display the image only, in somewhere else in the same Django project. Is there any way to extract image only and display in my view file or what will be the best solution? Can I extract the path of image and display it ? So, how to extract the image tag from the content? It will be appreciated if someone helps. I am new to Django. -
Does fetch api in javascript send a get request if the post request fails
I was trying to build a Django app with javascript in the frontend. The POST request from the fetch API was failing if I did not add the CSRF token in the headers. However, it sent a GET request instead. When I added the CSRF token, it worked normally. But in the future, I want to avoid sending GET requests in case the POST fails. It is the default behavior? How do I prevent it? -
Django - Login required for specific user type
I extended the user login from Django with AbstractUser like this: class User(AbstractUser): pass class Seller(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) verified = models.BooleanField(default=False) money = models.IntegerField(default=0) def __str__(self): return str(self.user) I would like now to create a view and a form that can only be access by the "Seller" user, like this in views.py: @login_required def account(request): return render(request= request, template_name='main/account.html', context = {}) Any idea on how can I do it? Thank you -
Django. Language prefix in URL patterns
Language prefix in URL patterns I have done Translation of the website in 2 languages. It reads the language setting of the browser and automatically switches to the correct language. I want to add a language menu to the website and language prefix in URL patterns. Sorry, I have here difficulties and earnestly speaking do not understand what needs to be changed in the main urls.py. I am talking about this application only app_name = 'rsf' Please help. main urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('auswertung/', include('auswertung.urls')), path('rsf/', include('rsf.urls')), path('admin/', admin.site.urls), ] local urls.py from django.contrib import admin from django.urls import path from . import views app_name = 'rsf' urlpatterns = [ path('f_size_water/', views.f_size_water, name = 'f_size_water'), path('f_size_water_fin/', views.f_size_water_fin, name = 'f_size_water_fin'), ] Thank you -
error while installing virtual environment
I'm following official django tutorial on their webpage. When I run command "py -m pip install virtualenvwrapper-win", I get the the following errors. Please see the screenshot. I have Anaconda installed. The same error occurs on my other computer where I have only Python installed. What am I missing? Thanks -
i am using crispy for django and my success message works properly but my validation error messages show normal black text when it should be in red
so when i fill the login info correctly i get a message 'successfully added (username)' but when i fill in the wrong info i just shows plain black text but i want it to show error message in red color the tutorial .I followed a tutorial (by correy schafers) exactly the same but somehow i cant get the error message to show up in red color but my my success message shows up in green. register.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign In</a> </small> </div> </div> {% endblock content %} base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div … -
TWILIO API ERROR Credentials are required to create a TwilioClient django
I am trying to include TWILIO API to my project. It should send sms. I have finished tutorial, but then i get error Credentials are required to create a TwilioClient. I have credentials in .env file and then i try to import them to settings and then get this credentials from settings to views. This is when i get error. .env TWILIO_ACCOUNT_SID= 'xxxxxxxxxxxxxxxxxxxxxx' TWILIO_AUTH_TOKEN= 'xxxxxxxxxxxxxxxxxxxxxxx' TWILIO_NUMBER= 'xxxxxxxxxxxxxxxxxx' settings.py import os TWILIO_ACCOUNT_SID = os.getenv('TWILIO_ACCOUNT_SID') TWILIO_AUTH_TOKEN = os.getenv('TWILIO_AUTH_TOKEN') TWILIO_NUMBER = os.getenv('TWILIO_NUMBER') SMS_BROADCAST_TO_NUMBERS = [ '+111111111', ] views from django.conf import settings from django.http import HttpResponse from twilio.rest import Client def broadcast_sms(request): message_to_broadcast = ("Have you played the incredible TwilioQuest " "yet? Grab it here: https://www.twilio.com/quest") client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) for recipient in settings.SMS_BROADCAST_TO_NUMBERS: if recipient: client.messages.create(to=recipient, from_=settings.TWILIO_NUMBER, body=message_to_broadcast) return HttpResponse("messages sent!", 200) and here is when code work, but i want to import this from settings.. # def sms(request): # TWILIO_ACCOUNT_SID = "xxxxxxxxxxxxxxxxxxxxxxx" # TWILIO_AUTH_TOKEN = "xxxxxxxxxxxxxxxxx" # TWILIO_NUMBER = "xxxxxxxxxxxxx" # message_to_broadcast = ("Have you played the incredible TwilioQuest " # "yet? Grab it here: https://www.twilio.com/quest") # # client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) # for recipient in settings.SMS_BROADCAST_TO_NUMBERS: # if recipient: # client.messages.create(to=+xxxxxxxxx, # from_=+xxxxxxxxxx, # body=message_to_broadcast) # return HttpResponse("messages sent!", 200) … -
Python Django - HTML for REST API JSON data in Async
I am making a Django web app. So far I have used templates for creating HTML in response to a POST request. I use 'context' to pass data to the template and fill the HTML with that data. This does not require any client-side work. Now I added a REST API to the app to be used Async, and I want all data to be processed by the API and return only in JSON format. This creates a problem, I cant use the templates anymore since I can't use 'context' to fill in the data in the HTML, I have to use client-side JS to do the filling but now I am missing the HTML appropriate to the data received. What are the ways in Django for generating HTML for an API JSON response in Async architecture? Are there any solutions, frameworks, JS libraries? I do not want to return HTML via API to keep things client mobile app/browser independent. -
Why I can't pass categories to my template in Django
I have a header.html file in my partials under template directory. I have a section for categories which I need to fetch from database. Therefore, I've created a custom templatetag in my app folder. I have written the tag for the latest dropdown article and categories. Well, somehow the articles are being fetched from the database but categories are not. models.py from django.db import models from django.utils.text import slugify from django.urls import reverse from ckeditor_uploader.fields import RichTextUploadingField from datetime import datetime class Category(models.Model): label = models.CharField(max_length=15, unique=True) def __str__(self): return self.label class Article(models.Model): title = models.CharField(max_length=80, unique=True, help_text='Max Length: 80') category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) banner_image = models.ImageField(upload_to='photos/%Y/%m/%d/', help_text='Banner Image', default=None) description = models.TextField(max_length=200 ,help_text='Short descirption about the post') content = RichTextUploadingField(help_text='Site Content') published = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) views = models.BigIntegerField(default=0) featured = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('article', kwargs={'category': self.category, 'post': self.title}) my custom tempalte tag from django import template from articles.models import Article, Category register = template.Library() @register.inclusion_tag('partials/_header.html') def recent(): category = Category.objects.all() #not being fetched recents = Article.objects.filter(published=True).order_by('-date_created')[:9] trendings = Article.objects.filter(published=True).order_by('-views')[:9] return { 'recents': recents, 'trendings': trendings, 'category': category, } ** my header.html file ** <div id="asmCategoryContents" class="asm-Category_Contents"> {% for cat … -
Compare the new and old field values in django, then update the old value
In the data is being pulled from the URL. Which is being stored in the database. Now I would want to only update the data that is being changed. hostandservicelisturl = 'http://192.168.232.133/query=servicelist' userpwd = ('xxx', 'xxx') data7 = requests.get(hostandservicelisturl,auth = userpwd).json() data8 = data7['data']['servicelist'] mylistik1 = [] for ik1 in data8: print(ik1) mylistik1.append(ik1) for x in mylistik1: for y in data8[x]: print(y) z = data8[x][y] Data.objects.update_or_create(hostname=ik1,service=y,servicestatus=z) class Data(models.Model): hostname = models.CharField(max_length=200, null=True, editable=False) service = models.CharField(max_length=200, null=True, editable=False) servicestatus = models.IntegerField(null=True, editable=False) Value In URL: "linksys-srw224p": { "PING": 2, "Port 1 Bandwidth Usage": 8, "Port 1 Link Status": 16, "Uptime": 16 Note : the number like 2 8 16 changes accordingly from the api pull. As of now i have seen field tracker() with pre save but I am not able to figure out how too as the documentation is not clear. -
i want to download number of media like 10 or 20 downloads per request but dont know how?
posts = [] links = driver.find_elements_by_tag_name('a') for link in links: post = link.get_attribute('href') if '/p/' in post: posts.append(post) print(posts) download_url = '' for post in posts: driver.get(post) shortcode = driver.current_url.split("/")[-2] type = driver.find_element_by_xpath('//meta[@property="og:type"]').get_attribute("content") if type == 'video': download_url = driver.find_element_by_xpath('//meta[@property="og:video"]').get_attribute("content") urllib.urlretrieve(download_url, '{}.mp4'.format(shortcode)) else: download_url = driver.find_element_by_xpath( '//meta[@property="og:image"]').get_attribute("content") urllib.urlretrieve(download_url, '{}.jpg'.format(shortcode)) print(download_url) -
django-admin startproject doesn't do anything
I use command "django-admin startproject myapp" and it doesn't do anything When I use this command again it says "CommandError: 'C:\Users\User\Desktop\djangotest2\myapp' already exists" I tried disabling my antivirus and I tried using absolute path to django-admin.py and django-admin.exe file -
Python HTTP server for shell commands
I look for Python package to expose shell command from a linux server. At this moment I use Django and ThreadPoolExecutor to asynchronously launch submit execution. Clients receives job id and 202 Accepted as HttpResponse. It feels like i re-invent a wheel. Is there python3 framework which can help me to expose and orchestrate running commands on a server through HTTP? launch a shell command by triggering http endpoint (returns 202 and launch-id) commands must run asynchronously and will have own side-effects (e.g. write something to db) obtain status of running command by launch-id log stderr and stdout of subprocess so later i can find the output in logs -
Stripe Variable amount checkout & Django
I am trying to implement variable amount checkout using Stripe, so that users can donate a chosen amount. The donation should then link to a customer id created using dj stripe (set up for recurring donations). So far, I have got the follwoing, however currently clicking the donate button does not load the stripe checkout page Views.py: customer, created = djstripe.models.Customer.get_or_create(subscriber=user) @require_http_methods(['POST']) def create_singlesession(): #read request data data = json.loads(request.data) # create checkout session with API api_key=stripe_key, session = stripe.checkout.Session.create( customer=customer.id, success_url='charity_app/success?id={CHECKOUT_SESSION_ID}', cancel_url='charity_app/cancel?id={CHECKOUT_SESSION_ID}', payment_method_types = ['card'], submit_type = 'donate', line_items = [{ 'amount': data['amount'], 'currency': 'gbp', 'quantity': 1, 'name': 'Single Donation', 'images': [], }], payment_intent_data = { 'metadata': { 'Charity': data['Organisation'], }, }, metadata={ 'Charity': data.get('Organisation') } ) return JsonResponse(session) Session.sync_from_stripe_data(create_singlesession) urls: url(r'^create-singlesession/$',views.create_singlesession,name='create_singlesession'), Template: <button id="donate-button">Donate</button> <script src="https://js.stripe.com/v3/"></script> <script charset="utf-8"> var stripe = Stripe('pk_test_jcFUmV2P0IREALGYggK6w2tT007W8QUaqd'); var amount = document.getElementById('amount-input'); var charity = document.getElementById('charity'); var button = document.getElementById('donate-button'); button.addEventListener('click', function(e) { /*alert( "Handler for .click() called." );*/ e.preventDefault(); createSessionAndRedirect(); }); function createSessionAndRedirect() { // 1. Pass the amount and organisation to server to create session fetch('/charity_app/create-singlesession/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ amount: amount.value, cause: charity.value, }), }) .then((response) => response.json()) .then((session) => { // 2. Redirect to … -
How to correct repeating code in view-functions?
I looked at one Django course on a site that starts with the letter U and at the end I have such a code. There is a lot of duplication and I show just one of them. On each page, I publish the same type of information, it hurts to look at it. So while I thought about two solutions to fix this: Create Global Variables Define a function that will return all these duplicate variables main.view def home(request): ''' index.page ''' site, _ = Main.objects.get_or_create(pk=1) # (1) news = News.objects.all().order_by('-pk') # (2) subs = SubCat.objects.all() # (3) lastNews = News.objects.all().order_by('-pk')[:3] popNews = News.objects.all().order_by('-show') bottomPopNews = News.objects.all().order_by('-show')[:3] # (5) trends = Trending.objects.all().order_by('-pk') # (6) # group Subcategories in each Category tags = SubCat.objects.values('catid', 'catid__name').order_by('catid').annotate(count=Count('catid')) # (4) Tracker.objects.create_from_request(request, site) return render(request, 'front/home.html', {'site' : site, 'news' : news, 'tags' : tags, 'subs' : subs, 'lastNews':lastNews, 'popNews' : popNews, 'bottomPopNews':bottomPopNews, 'trends':trends}) def about(request): ''' About page ''' site, _ = Main.objects.get_or_create(pk=1) # (1) popNews = News.objects.all().order_by('-show')[:3] news = News.objects.all().order_by('-pk') # (2) subs = SubCat.objects.all() # (3) bottomPopNews = News.objects.all().order_by('-show')[:3] # (5) tags = SubCat.objects.values('catid', 'catid__name').order_by('catid').annotate(count=Count('catid')) # (4) trends = Trending.objects.all().order_by('-pk') return render(request, 'front/about.html', {'site' : site, 'popNews':popNews,'bottomPopNews':bottomPopNews,'tags':tags,'subs' : subs,'news' : news,'trends':trends,}) def … -
Update nested field if a path to it isn't constant
I'm working on Django which uses MongoDB. One of collections has the following structure: { "inspectionType" : { "id" : "59a79e44d12b52042104c1e8", "name" : "Example Name", "inspMngrsRole" : [ { "id" : "55937af6f3de6c004bc42862", "type" : "inspectorManager", "is_secret_shoper" : false } ], "scopes" : { "56fcf6736389b9007a114b10" : { "_cls" : "SomeClass", "id" : "56fcf6736389b9007a114b10", "name" : "Example Name", "category" : "Example Category" }, } } } I need to update field "_cls" ("inspectionType.scopes.._cls") for all documents in the collection. The problem is the scope_id is dynamic and unique for each scope. Is it possible to use db.collection.update for that? And how should the path to the field look like? -
Проблема с созданием миграций для Django 2.11 [closed]
Стартанул новый проект на Django 2.11. Из кастомных моделей ничего еще не успел сделать. Создал только первое приложение, прописал базовые настройки (http://joxi.ru/ZrJ9zN4CMN7pMA). Пробую накатить базовые миграции Django командой python manage.py migrate. Получаю ошибку: File "E:\DjangoEnv\api_for_django22_env\lib\site-packages\django\apps\registry.py", line 155, in get_app_config return self.app_configs[app_label] KeyError: 'accounts' "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.Accounts' that has not been installed -
How to implement Django Form Live Validation?
Are there any packages to perform client-side validation over django forms? I'm Not really experienced with AJAX and Javascript. -
Custom User Authentication using DRF
Want to create a Web RESTful API with Django. For that I'm using Django REST Framework. What are the necessary steps to get the authentication using a custom User model (subclassing AbstractBaseUser) exposing the endpoints to be used? -
How to pass input value to function in view.py
Objective: ** To pass input value itemnumbervalue to itemnumber() in views.py > Error occured: method object is not subscribable line 17 in view.py views.py: from .forms import InputForm def home_view(request): context1 ={} context1['form'] = InputForm(request.POST) return render(request, "input.html", context1) def itemnumber(request): *if (request.POST('submitted')): c = request.POST['ENTER_ITEM_NUMBER'] print("input valuegiven by user",c)* cursor = connection.cursor() try: itemnumbervalue = c C=cursor.execute(f"EXEC ValidateBusinessrule '0000000000{itemnumbervalue}'") result_set = cursor.fetchall() result_set1= [' {} '.format(x) for x in result_set] context = {"row": result_set1} return render(request, "home.html", context) finally: cursor.close() forms.py class InputForm(forms.Form): regex = re.compile('^([1-9]{8})$', re.UNICODE) ENTER_ITEM_NUMBER= forms.RegexField(max_length=8, regex=regex,help_text=("Required 8 digits between {0-9}.")) home.html <body> <table> <tr> <ul> <th>(column 1,column 2)</th> </ul> <tr> <ul > {% for row in row %} <td style= "text-align: center;"> {{ row }} </td> </ul> </tr> {% endfor %} </tr> </table> </body> input.html <body> <form action = "{% url 'item'%}" method = "POST"> {% csrf_token %} {{form}} <input type="submit" value=Submit" name="submitted"> </form> </body> problem details: To get input from user and give this input to itemnumbervalue in itemnumber() in view.py. I already validated by putting itemnumbervalue='12345678' (without input value from user) is working fine and getting resultant table. -
Django cannot assign variable to objects
when i'm trying to add data to uer in many to many as showen in views code below views.py def playList(request, name, language): playlist = { 'classic': Classic, } playlist2 = { 'classic': 'classic', } num = { 'ar': 1, 'en': 2, } if request.method == 'POST': form2 = FavoriteForm(request.POST) if form2.is_valid(): x = Profile.objects.get(user=request.user) x.playlist2[name].add(playlist[name].objects.get(id=request.POST.get(playlist2[name]))) form = playlist[name].objects.filter(lang=num[language]) context = {} for i in form: context[i] = i context = { 'form': form, 'playlist': playlist2[name], } return render(request, 'playlist.html', context) get this error that str object has no attr objects 'str' object has no attribute 'objects' when i'm change str to istance as showen in views code below views.py def playList(request, name, language): playlist = { 'classic': Classic, } playlist2 = { 'classic': Profile.classic, } num = { 'ar': 1, 'en': 2, } if request.method == 'POST': form2 = FavoriteForm(request.POST) if form2.is_valid(): x = Profile.objects.get(user=request.user) x.playlist2[name].add(playlist[name].objects.get(id=request.POST.get(playlist2[name]))) form = playlist[name].objects.filter(lang=num[language]) context = {} for i in form: context[i] = i context = { 'form': form, 'playlist': playlist2[name], } return render(request, 'playlist.html', context) i get this error that profile has no attr playlist2 'Profile' object has no attribute 'playlist2' and this is my model code modles.py class Classic(models.Model): name = models.CharField(max_length=50, … -
is there memory issue?
https://www.google.com/search?q=MemoryError+at+%2Fquery%2F+No+exception+message+supplied+Request+Method%3A+POST+Request+URL%3A+http%3A%2F%2F127.0.0.1%3A8000%2Fquery%2F+Django+Version%3A+2.2.5+Exception+Type%3A+MemoryError+Exception+Location%3A+ops.pyx+in+thinc.neural.ops.NumpyOps.allocate%2C+line+491+Python+Executable%3A+C%3A%5CUsers%5CTOSHIBA%5CAnaconda3%5Cpython.exe+Python+Version%3A+3.7.3+Python+Path%3A+%5B%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CDocuments%5C%5Cclinical%5C%5Cdemoproject%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Cpython37.zip%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5CDLLs%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%5C%5Cwin32%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%5C%5Cwin32%5C%5Clib%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%5C%5CPythonwin%27%5D+Server+time%3A+Mon%2C+23+Mar+2020+17%3A41%3A09+%2B0000&oq=me&aqs=chrome.1.69i59l2j0j69i57j69i61l3j69i60.2878j0j7&sourceid=chrome&ie=UTF-8 i received many times this error please help me -
How to pass input value to function in view.py
Objective: ** To pass input value itemnumbervalue to itemnumber() in views.py > Error occured: The view item.views.itemnumer didn't return a return a HTTP return response. It return none instead views.py: from .forms import InputForm def home_view(request): context1 ={} context1['form'] = InputForm(request.POST) return render(request, "input.html", context1) def itemnumber(request): *if (request.GET.get('submitted')): c = request.get['ENTER_ITEM_NUMBER'] print("input valuegiven by user",c)* cursor = connection.cursor() try: itemnumbervalue = c C=cursor.execute(f"EXEC ValidateBusinessrule '0000000000{itemnumbervalue}'") result_set = cursor.fetchall() result_set1= [' {} '.format(x) for x in result_set] context = {"row": result_set1} return render(request, "home.html", context) finally: cursor.close() forms.py class InputForm(forms.Form): regex = re.compile('^([1-9]{8})$', re.UNICODE) ENTER_ITEM_NUMBER= forms.RegexField(max_length=8, regex=regex,help_text=("Required 8 digits between {0-9}.")) home.html <body> <table> <tr> <ul> <th>(column 1,column 2)</th> </ul> <tr> <ul > {% for row in row %} <td style= "text-align: center;"> {{ row }} </td> </ul> </tr> {% endfor %} </tr> </table> </body> input.html <body> <form action = "{% url 'item'%}" method = "post"> {% csrf_token %} {{form}} <input type="submit" value=Submit" name="submitted"> </form> </body> problem details: To get input from user and give this input to itemnumbervalue in itemnumber() in view.py. I already validated by putting itemnumbervalue='12345678' (without input value from user) is working fine and getting resultant table.