Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: valueerror on optional field
This is my first django project, I'm not sure why I'm getting an error 'The 'image2' attribute has no file associated with it.' when those fields are optional. How can I fix this? model class LinksContent(models.Model): author = models.ForeignKey(Author, on_delete=models.DO_NOTHING, default= True) title = models.CharField(max_length=100) somecontent = HTMLField(blank = True) image = models.ImageField(upload_to = 'images/%Y/%m/%d/') image2 = models.ImageField(upload_to = 'images/%Y/%m/%d/', blank = True) image3 = models.ImageField(upload_to = 'images/%Y/%m/%d/', blank = True) image4 = models.ImageField(upload_to = 'images/%Y/%m/%d/', blank = True) links = ( ('faculties', 'faculties'), ('admission', 'admission'), ('resources', 'resources'), ('staff', 'staff'), ('research', 'research'), ) file1 = models.FileField(upload_to = 'files/%Y/%m/%d/', blank = True) section = models.CharField(max_length=13, choices=links) is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) html> {% if content %} {% for item in content %} <div class="theHeader"> <img class = 'header-img' src = "{{ item.image.url }}"> <div class = 'author-info'> <img class = 'admin-img' src = "{{ item.author.image.url}}"> <p>&nbsp;{{ item.author}} &nbsp;</p> <p>&nbsp;{{ item.publish_date | naturaltime}}</p> </div> </div> <div id="content"> <h1>{{ item.title }}</h1> <p>{{ item.somecontent | safe }}</p> <div class = 'data'> <img class = 'images' src = "{{ item.image2.url }}"> <img class = 'images' src = "{{ item.image3.url }}"> <img class = 'images' src = "{{ … -
How to properly secure API login credentials with environment variables using React and Django
I have a project using React (frontend) and Django Rest Framework (backend), and it is currently deployed on PythonAnywhere. I'm using axios to connect to my API and load data from my database onto the React frontend. During development, I hardcoded the username and password for accessing the database into my index.js file (credentials are obscured below): import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App.js'; import axios from 'axios'; import 'semantic-ui-css/semantic.min.css'; import 'lightgallery.js/dist/css/lightgallery.css'; import './styles.css'; import * as serviceWorker from './serviceWorker'; axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; axios.post('/login/', { username: [HARD_CODED_USERNAME], password: [HARD_CODED_PASSWORD] }).then(rv => { console.log('Login', rv) }).catch(err => { console.log('Login error', err.response) }); const updatePhoto = () => { axios.patch('https://[WEBSITEADDRESS.COM]/api/photos/').then(resp => { console.log('Update response', resp) }).catch(error => { console.log("Update error", error) }) } ReactDOM.render( <App />, document.getElementById('root') ); serviceWorker.unregister(); This works, however the username and password are viewable upon inspection in the browser. Not only that, but the Django admin as well as the API is accessible to anyone, because it automatically logs them in using my username and password! I then tried using an .env file located at the root of my create-react-app project (same level with my package.json file): … -
ModuleNotFoundError at /blog/post/comment/update/18/ No module named 'test-post-ecomon'
I have a blog section of my website and I made an CommentUpdateView and after submiting the form it gives me this error ModuleNotFoundError at /blog/post/comment/update/18/ No module named 'test-post-ecomon' but I don't undersant why because this post exists and I implemented get_absolute_url in my Contact models and It should work right? When I create a new commment it works. view class CommentUpdateView(LoginRequiredMixin, UpdateView): model = Comment form_class = CommentUpdateForm template_name = 'blog/update_comment.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(author=self.request.user) model class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') reply = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='replies') content = models.TextField(_('Content')) posted_date = models.DateTimeField(_('Posted Date/Time'), auto_now_add=True) updated_date = models.DateTimeField(_('Updated Date/Time'), auto_now=True) def __str__(self): return f'{self.author.username} - {self.post.title}' def get_absolute_url(self): return reverse('post', self.post.slug) urls path('post/<slug:slug>/', PostDetailView.as_view(), name='post'), path('post/comment/update/<int:pk>/', CommentUpdateView.as_view(), name='update-comment'), -
getting critical error while install mysqclient for django on ubuntu/ plesk
i create django project. when i add mysql database configuration on settings.py with migrate everything was created on mysql database. i'm using plesk . when i creating superuser it's added to auth_users database. but when i want to enter django admin with any users i'm getting user_auth error and django still looking information in sqlite database. this is on plesk server / ubuntu. when i created same django project and use freedbhosting and did same things i didnt get any errors and i enter to adminpanel with mysql.. i search and found that mabe i need mysqlclient on plesk/ubuntu server so i want try install it but when i want to install mysqclient i'm getting this error. Using cached mysqlclient-2.0.3.tar.gz (88 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip- install-r9g0_kiz/mysqlclient_1e646ce6b9aa48bbb86f7b3a5092790f/setup.py'"'"'; __file__='"'"'/tmp/pip- install-r9g0_kiz/mysqlclient_1e646ce6b9aa48bbb86f7b3a5092790f/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip- wheel- zeq33vj3 cwd: /tmp/pip-install-r9g0_kiz/mysqlclient_1e646ce6b9aa48bbb86f7b3a5092790f/ Complete output (41 lines): mysql_config --version ['5.7.32'] mysql_config --libs ['-L/usr/lib/x86_64-linux-gnu', '-lmysqlclient', '-lpthread', '-lz', '-lm', '-lrt', '-latomic', '- lssl', '-lcrypto', '-ldl'] mysql_config --cflags ['-I/usr/include/mysql'] ext_options: library_dirs: ['/usr/lib/x86_64-linux-gnu'] libraries: ['mysqlclient', 'pthread', 'm', 'rt', … -
Following a tutorial using Django/Python: ModuleNotFoundError: No module named 'pages'
I'm new to Django and am trying to create a very simple app off of a tutorial I found online. Working on a mac Django Version 2.0.7 Python 3.7.0 My file structure: helloworld ......venv ..........(other files) ......helloworld_project ..........(other files) ......manage.py ......pages .........._ pycache _ ..............otherfiles ..........admin.py ..........apps.py ..........migrations ..............(other files) ..........models.py ..........tests.py ..........urls.py ..........views.py The problem: when I run my urls.py file, I get the following message: Traceback (most recent call last): File "/Users/Bethany/Desktop/helloworld/pages/urls.py", line 3, in <module> from pages import views ModuleNotFoundError: No module named 'pages' My urls.py file: # pages/urls.py from django.urls import path from pages import views urlpatterns = [ path('', views.homePageView, name='home') ] I've tried replacing "from pages import views" with "from . import views" and get the same message. I've looked through a few similar questions on stack overflow, but haven't had success with finding a solution to fix my issue. does anyone have any suggestions? Thanks! If needed, this is the tutorial I'm following: https://djangoforbeginners.com/hello-world/ -
How To Create A Photo Gallery In Django?
Can someone perhaps provide some guidance as to how I would go about creating a photo gallery in Django? Currently I am able to upload one, and only one, photo. I would like to be able to upload multiple photos and query them in the template. I have scoured a lot of old posts on StackOverflow for an answer but everything either doesn't work (out of date) or is a half-answer. Thanks for any guidance you can provide. -
Scrapy error when run with Celery and Django Channels is installed: OSError: [Errno 9] Bad file descriptor
When I run this script with Django shell it will run without error, but when I run with celery worker it get this error: OSError: [Errno 9] Bad file descriptor. If I remove channels from INSTALLED_APPS the problem will be solved and task runs with celery worker without error. Running the same script with python Process (due to ReactorNotRestartable exception) in django shell get the same error which celery worker had: OSError: [Errno 9] Bad file descriptor. I think there's a conflict between Django Channels & Scrapy when spider is executed in another process. from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings def run_spider(spider) settings = get_project_settings() crawler_process = CrawlerProcess(settings=settings) crawler_process.crawl(spider) crawler_process.start() exception stack trace when run with celery worker: Task run spider raised unexpected: OSError(9, 'Bad file descriptor') Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/selector_events.py", line 256, in _add_reader key = self._selector.get_key(fd) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/selectors.py", line 192, in get_key raise KeyError("{!r} is not registered".format(fileobj)) from None KeyError: '9 is not registered' exception stack trace when run with python Process in Django shell: /usr/local/lib/python3.7/site-packages/billiard/pool.py in apply(self, func, args, kwds) 1387 ''' 1388 if self._state == RUN: -> 1389 return self.apply_async(func, args, kwds).get() 1390 1391 def starmap(self, func, iterable, chunksize=None): /usr/local/lib/python3.7/site-packages/billiard/pool.py in … -
How do I get self.request.user in DRF from a request in vue.js?
how do I get self.request.user in DRF from a request in vue.js? My request from .vue: async LoadCase() { this.case = await fetch( `${this.$store.getters.getServerUrl}/casedetail/${this.slug}` ).then(response => response.json()) } My class in views.py: class DetailCase(RetrieveAPIView): queryset = Case.objects.all() serializer_class = CaseDetalSerializers lookup_field = "slug" My class in serializers.py: class CaseDetalSerializers(serializers.ModelSerializer): possible_open = serializers.SerializerMethodField() class Meta: model = Case exclude = ("id","slug") def get_possible_open(self,case): request = self.context.get('request') print(request) print(request.user) What I get from print: <rest_framework.request.Request: GET '/api/v1/casedetail/rofl'> AnonymousUser Right now I'm getting the AnonymousUser for some reason, and I should be getting admin. What do I have to do to get it? -
how can I create a Like button with generic relations?
*class Like(model.Models) object_content_type = models.ForeignKey( ContentType, blank=True, null=True, related_name='object_notifications', on_delete=models.CASCADE,) object_id = models.CharField(max_length=50, blank=True, null=True) action_object = GenericForeignKey('object_content_type', 'object_id')* this is my class that i saw in django documentions but i need a full code explain for views.py and templates, =) -
Django Migration Error With MSSQL Database With Schemas
I just start to create the settings for Django backend (All in Python). I use MS SQL and I run my django in Linux to connect to MSSQL. After setting the databases specifications, I run into the following error. Given that my database has more than schemas, I assume i have to tell django which schema to use in the database, but i fail to find the right place. Any ideas ? My settings: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'MyDB', 'HOST': '********', 'PASSWORD': '**************', 'AUTOCOMMIT': True, 'USER': 'root', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, }``` Error: ```django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Hello there. It looks like you're trying to create an object without specifying a schema name. Please create in a named schema, eg schemaname.tablename\r\n\t (50000) (SQLExecDirectW)"))``` -
Javascript file incorrect? Django
I am writing a Django website. I am trying to use a JavaScript file to move a mobile nav bar into the page when clicking on the burger icon. I have successfully loaded a JavaScript file from the static folder. (I checked with the alert function.) However, once I write more code in the JavaScript file, the JavaScript file doesn't work and I don't get the alert "Hello, javascript file loaded" upon refreshing the website page. Is my javascript incorrect? Is the format incorrect for use in Django? Any help would be much appreciated, thanks for reading. App.js alert("Hello, javascript file loaded"); const navSlide = () => { const burger = document.querySelector('.burger'); const nav = document.querySelector('.nav-links'); burger.addEventListener('click', () = > { nav.classList.toggle('nav-active'); }); } navSlide(); Base.html {% load static %} <html> <head> <title>Pep Genie</title> <link rel="stylesheet" type="text/css" href="{% static 'genie/style.css' %}"> </head> <body> {% block content %}{% endblock %} <script src="{% static 'genie/app.js' type="text/javascript" %}"></script> </body> </html> Index.html {% extends 'genie/base.html' %} {% block content %} <nav> <div class="logo"> <h4>The Logo</h4> </div> <ul class="nav-links"> <li> <a href="#">Home</a> </li> <li> <a href="#">About</a> </li> <li> <a href="#">Work</a> </li> <li> <a href="#">Our Projects</a> </li> </ul> <div class="burger"> <div class="line1"></div> <div class="line2"></div> <div class="line3"></div> … -
Django FileField Multiple data uploading is not working
i want to upload multiple files from Django FileField. The code below upload single file instead of multiple files. i also define attr for multiple files in forms.py. The form is only save single file in database when i try to add multiple item in FileField. I would be grateful for any help. models.py class Article(models.Model): title = models.CharField(max_length=300) file_data = models.FileField(upload_to='stories', blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) forms.py class ArticleForm(forms.ModelForm): file_data = forms.FileField(required=False, widget=forms.FileInput( attrs={'accept': 'image/*,video/*', 'multiple': True})) class Meta: model = Article fields = [ 'title', 'file_data', ] views.py class NewsCreateView(CreateView): form_class = ArticleForm template_name = 'create.html' success_url = '/' def form_valid(self, form): # check author validation form.instance.author = self.request.user return super().form_valid(form) -
(internal error) Ngnix + uwsgi +django : no module named django
So im trying to deploy a django app with nginx and uwsgi , ngnix is running well and the django app is working well with manage.py runserver , but when i try to deploy it with uwsgi it said Internal Server Error , and when i check my uwsgi logs that what i get (No module named django) the virtualenv python version is 3.6.9 ,i'dont know if this error is caused because of imcompatibilty with python version of virtual environement and the Uwsgi one or just because i missed somethings , my uwsgi specs are this is my uwsgi ini file : [uwsgi] vhost = true plugins = python socket = /tmp/mainsock master = true enable-threads = true processes = 4 wsgi-file = /var/www/PTapp-launch/ptapp/wsgi.py virtualenv = /var/www/venv/site chdir = /var/www/PTapp-launch touch-reload = /var/www/PTapp-launch/reload env = DJANGO_ENV=production env = DATABASE_NAME=personal_trainer env = DATABASE_USER=postgres env = DATABASE_PASSWORD=teemo1313 env = DATABASE_HOST=localhost env = DATABASE_PORT=5432 env = ALLOWED_HOSTS=141.136.36.27 -
django Datefield is taken as UTC even though I have set it to 'Asia/Kolkata' in postgresql but in DateTimeField is taken time 'Asia/Kolkata' why
My Models saleDate = models.DateField(auto_now_add=True) #this field taken UTC saleTime = models.DateTimeField(auto_now_add=True) #this field taken 'Asia/Kolkata Settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Calcutta' USE_I18N = True USE_L10N = True USE_TZ = True using AWS Mumbai Region -
NestedSimpleRouter without using lookup in router
I am using drf-nested-router something like the following in my url.py router = SimpleRouter() profile_router = routers.NestedSimpleRouter(router, r'profile', lookup='user') profile_router.register(r'comments', UserCommentViewSet, basename='profile-comments') The viewset is class UserCommentViewSet(CommentViewSet): def get_queryset(self): return Comment.objects.filter(owner=self.request.user) So the URL is something like, mydomain.com/profile/{profile_id}/comments/ it gives me right results. But the following URL is also giving me right results, mydomain.com/profile/{anything}/comments/ because I am using the session user info to filter the data. Is it possible to make the URL like mydomain.com/profile/comments/ Thanks in Advance. -
Looking for suggestions... Which language/framework should I use for my project?
For a project in my mind -and to learn while doing- I have to choose a language / framework and start learning. My goal is to quickly create a mvp that looks good and has basic functions. I have good command of basic programming concepts. I know html and css, but I'm not very dominant, but I can reveal what I want by looking at the documentation. I know basic sql queries. I don't have any experience in js or php. I have been building many websites with wordpress for a long time, but of course it is not useful for this project. Hosting part is not an issue for me, I can host the project on my home server or on the AWS. There will be simple crud operations in the project; Create product / service / user profiles Listing and filtering within these profiles Matching between profiles Send requests to matching services (all or selected) (can be via email) As a result of my rapid research, django one came out, but I am not sure if the learning process will take a long time. I learned php in college years ago, I am not thinking whether to try … -
Django: tinymce HTML format
I just installed django-tinymce however when I display the content I'm getting HTML format. How can I fix this? Something <p>Some <strong>random </strong>text 123 123 123 <strong><br /></strong></p> admin -
Django ManyToManyField Persistence Fails
I have a simple Django 3.1.0 app I need to create in order to assign Tasks with Tags (or assign tags into tasks). My Model class Task(models.Model): user = models.CharField(max_length=33) time = models.DateTimeField(auto_now_add=True) task = models.CharField(max_length=500) tags = models.ForeignKey('Tag', on_delete=models.SET_NULL, null=True) class Tag(models.Model): tag = models.CharField(max_length=30, default="No Tag") members = models.ManyToManyField('Task') class Meta: verbose_name = "tag" verbose_name_plural = "tags" My Form class TaskForm(ModelForm): class Meta: model = Task fields = ['user', 'task', 'tags'] template_name = 'tasks.html' tags = ModelMultipleChoiceField( queryset=Tag.objects.values().all(), widget=CheckboxSelectMultiple() ) My View def main(request): model = Task.objects.values().all() form = TaskForm() con = {'context': list(model), 'form': form} if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): obj = form.save(commit=False) form.save_m2m() return redirect('/') else: form = TaskForm() return render(request, "tasks.html", con) The migrations are successfull, and with the above code, the view shows a checkbox list with the fetched tags, but the problem is that when I hit Submit on the form, the values are not saved/written on the database but the page reloads successfully. However, if I turn the following: obj = form.save(commit=False) form.save_m2m() into form.save(commit=True) #form.save_m2m() the values are written only from the fields 'user', 'task' - without the 'tags' It's also funny that what fetches back on … -
Django html Check form type
I'm trying to build an html page in Django, where depending on the form passed the page will render different things. How can I know in the HTML the type of form passed? I want to do something like this: {% block content %} <div class="content-section container" > {% if form.type == 'ModelAForm' %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.driver_color }} </form> </div> {% endif %} {% if form.type == 'ModelBForm' %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.driver_name}} </form> </div> {% endif %} </div> {% endblock content %} On the {% if form.type == 'ModelAForm' %} how can I know the form type? -
Class 'Post' has no 'objects' memberpylint(no-member)
I am new in django and was following a tutorial to learn. This is the tutorial https://tutorial.djangogirls.org/en/django_templates/. #This is the views.py #enter image description here from django.shortcuts import render from django.utils import timezone from .models import Post def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) -
What happens when only 1 product available and 2 user clicks buy now
I am doing an online shopping site. I need to know that if only 1 stock available for a product and 2 user clicks buy now at same time. How to deal such a scenario -
Django ORM QuerySet with Aggregation Max function
I tried to Convert the SQL command: SELECT fname,lname FROM customer WHERE id > (SELECT max(id) FROM customer WHERE state = 'TX'); to an ORM (Django) QuerySet. At my first try I use: Customer.objects.filter(id__gt=Customer.objects.filter(state='TX').values('id')).values('fname','lname') But it gave me the wrong output (I compare with the raw sql query) So, I learn more and achieve the following: Customer.objects.filter(id__gt=Customer.objects.filter(state='TX').values('id').aggregate(Max('id'))['id__max']).values('fname','lname') I'm a junior so think to address SO for the following two questions: I have two questions: What happens in the first QuerySet, that output the wrong results ? (It doesnt crash) The QuerySet with the correct result, is long and complex in comparison to the SQL raw query. Is it the correct QuerySet ? Can I achieve the same result with a more simple QuerySet ? Thanks ! -
tinymce form doesn't show in Django
I have a form which I want one field to be a tinymce field and after I add {{form.media}} to the template it doesn't show the form. forms.py: from tinymce.widgets import TinyMCE class ArticleCreationForm(forms.ModelForm): class Meta: model = Article fields = ('title','description', 'text') exclude = ['votes', 'author'] widgets = { 'text' : TinyMCE(attrs={'cols': 80, 'rows': 10,'class': 'form-control'}), } I use django-tinymce and I do exactly as it says in the docs. -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 460: invalid continuation byte
i've got a problem with the command "loaddata" of my django app. when i run this command, this UnicodeDecodeError appears because of the "é" that are in my database table. i've try with many type of database on pgAdmin with different encode type like "UTF-8", "latin-1" or "win1252" or different "character type" or "collation" settings like "C" or "french_switzerland.1252" but everytime there is this error. i give you few more informations about my work space. say it to me if you need more informations, i don't give you too much, i don't want to give useless one. thank you i am on windows 10 i'm using pycharm 2020.3.2 pgadmin v4 the complete error : `` (venv) C:\Users\Mathias\PycharmProjects\yufindProject>python manage.py loaddata ask/dumps/ask.json Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management_init_.py", line 395, in execut self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management\commands\loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management\commands\loaddata.py", line 114, in loaddata self.load_label(fixture_label) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management\commands\loaddata.py", line 172, in load_label for obj in objects: File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\serializers\json.py", line 67, in Deserializer … -
how to send a message and wait for a reply in python, twilio in whatsapp
i want to take the details of a person on whatsapp and store it but it seems its not working as i want it. its not waiting for the user to input the first data before the second one coming. this is my #models.py class student_Account(models.Model): name = models.CharField(max_length = 30) place_of_stay = models.CharField(max_length = 30) def __str__(self): return self.name and this is my views.py @csrf_exempt def sms(request): incoming_msg = request.POST.get('Body', '').lower() resp = MessagingResponse() msg = resp.message() msg1 = resp.message() if 'hi' in incoming_msg: reply = ("Hello and welcome to kkk banking system WhatsApp bot!\n\n" "What would you like to do\n" "1. Create an accout?\n" "2. Check your account balance\n") msg.body(reply) if incoming_msg == '1': reply = ("Enter your name") a = incoming_msg student.name = a reply = ("Enter your place of stay") b = incoming_msg student.place_of_stay = b msg.body(reply) student.save() reply = ("Your details has been saved!!.") msg.body(reply)