AI-Powered App Development Guide
AI-Powered App Development Guide
11 Prompt Checklist . . . . . . . . . . . . . . . . . . . . . . . 80
1 AI templates to build
your entire application
The world of software development has completely changed. Arti-
ficial Intelligence (AI) makes it easy to create entire applications,
chatbots, and websites. OpenAI’s ChatGPT, Google Bard, Mi-
crosoft Bing, and GitHub Copilot can all write and debug code in
almost any programming language.
This book contains step by step prompt templates you can use to
generate your application code using AI services. The approach
detailed here follows a proven system design and development
methodology. The difference with this approach vs. traditional
software development is that the coding portion is accelerated from
months to days using AI.
You design your application largely by defining the requirements.
The design is comprised of natural language descriptions of the data
your application manages and what users can do with it in your
system. Software development methodologies have already been
doing this. The difference with an AI-assissted approach is that
you need to be precise in terms of the details.
Traditional software development leaves room to elaborate on the
requirements through each iteration. While this is still true, when
it comes time to prompt the AI to generate code, you need to give it
all of the relevant information about how your application should
work.
The term prompt engineering is commonly used to reference the
activity of constructing prompts that create the desired output. This
is a fancy term for a simple concept, but an important one. Simply
put, you need to be able to define and capture your thoughts in
clear, English text that can be used in a prompt.
AI templates to build your entire application 2
—Charles Kettering
This book walks you through the entire process, step by step. The
secret to effectively using AI is to break up the process into smaller
steps. This allows the AI to create your software a few components
or functions at a time, an amount of code that fits within its context
limits.
Following a step-by-step process is beneficial for both you and your
AI assistant. It helps you to think through the details of each use
case. You start with a high-level business idea. Then you model the
data for the application. Then you define the use cases that each
actor in the system can perform. Each step along the way requires
detailed information in the prompts so that AI can generate the code
that meets your requirements. Breaking down the development
into a step by step process forces you to think through how you
want each step to work.
A little bit of design goes a long way in terms of code generation.
So once you have the vision in mind for your app, you are ready to
get started.
Run the setup file and be sure to enable any checkbox for adding
Python to your path. Click “Install Now” and follow the steps to
install Python. You can verify that Python is installed using the
following command. Depending on your system, you may need to
specify python3. We use a virtual environment that is set up by
PyCharm (more info on that in a moment).
Run the installation file and create a new project in the desired di-
rectory. PyCharm will automatically create a virtual environment
for your project. After creating your project, go to the terminal to
install the required libraries. The icon to open the terminal is in the
lower-left corner of the IDE.
Pip, the Python package manager, was also installed when you
installed Python. However, it is a good practice to update it first.
Run the following command in the terminal window.
Using the python -m prefix ensures you are running the install
within your virtual environment.
Now install the OpenAI client library using the following com-
mand.
The python-dotenv library will be used so that you can safely store
your OpenAI API key, without having to insert it directly into your
code. The code will read your API key from an environment file.
The gradio library is an exceptionally useful library that quickly
makes web interfaces based on Python functions. This allows you
to visually interact with your applications quickly. You can easily
create an MVP using this library.
Click on “Create new secret key” and copy the API key. It is
important to note that you can’t view the full API key later. Save it
in a safe place immediately. If something happens, you can always
come back and create a new API key or remove old ones.
Your key, the character string, will be used in your code that calls
ChatGPT, as well as in the configuration of the CodeGPT plugin.
As noted earlier, avoid putting your key in the actual code.
To configure your key in an environment settings file, right-click
on your project in PyCharm and select the menu item New | File.
Name the file .env
In this file, define an environment variable that contains your key.
This will be referenced in the code at runtime.
Setup your environment 12
1 import openai
2 import os
3
4 # Set the OpenAI key
5 from dotenv import load_dotenv
6 load_dotenv()
7 openai.api_key = [Link]("OPENAI_API_KEY")
8
9 # Define the function to call the API
10 # The temperature is the amount of randomness and creativ\
11 ity,
12 # a value between 0 and 2. Higher values make the output \
13 more random,
14 # while lower values are more focused and deterministic.
15 def generate_code(prompt, temperature = 0.5, max_tokens =\
16 256):
17 response = [Link](
18 engine="text-davinci-003",
19 prompt=prompt,
20 max_tokens=max_tokens,
21 temperature=temperature
22 )
23
24 # Extract the response text
Setup your environment 13
25 return [Link][0].[Link]()
26
27 # Lets write some code
28 prompt = (
29 "Write a python function that takes a String "
30 "as input and returns a counts of the number "
31 "of vowels in the string"
32 )
33
34 code = generate_code(prompt)
35 print(code)
1 def countVowels(string):
2 vowels = 'aeiou'
3 count = 0
4 for char in string:
5 if char in vowels:
6 count += 1
7 return count
8
9 print(countVowels('Hello World')) #3
This function doesn’t look for uppercase vowels, but it does work
for lowercase letters. As you can see already, coding with ChatGPT
can be incredibly productive, but it will also require an iterative
process. We can improve upon this implementation. We will learn
all about iterative development with ChatGPT starting in the next
chapter.
plugin is available for both PyCharm and Visual Studio Code. Let’s
install this plugin and see how it is used.
Go to the PyCharm File | Settings, or Preferences on Mac OS. Select
Plugins from the list on the left and make sure you are on the
Marketplace tab. Search for CodeGPT and once you find it, click
the Install button. PyCharm will be restarted for the plugin to take
effect.
Now you need to configure the CodeGPT plugin, minimally with
your API key so it can make calls to ChatGPT. In the same
settings interface, search for CodeGPT. Enter your API key in the
appropriate field and click OK. You shouldn’t need to change any
other configuration options at this time.
Now you can right click in the editor, and see the CodeGPT |
Ask ChatGPT option. This allows you to make general queries
to ChatGPT, as if you were on the web interface. However, you
can also select portions of code and right-click for context-sensitive
calls to ChatGPT. We will leverage these features throughout the
Setup your environment 16
book.
Change the location folder at the top to the directory you just
created. Select the option to create a [Link] script at the bottom.
Your project will look something like this.
If you are not familiar with PyCharm, take a minute to get used to
it. By default, the green arrow icon near the upper right corner will
run the main welcome script that was generated. Clicking that will
open a shell window at the bottom of the screen and you will see
the Hi, PyCharm printed to the terminal.
Setup your environment 18
You will need to use the terminal window to install a few Python
packages before we get into building our application. Pip, the
Python package manager, was installed when you installed Python.
Open a terminal as shown in the image below and run the com-
mand:
Prompt template
Write Python code for a name type class
Example prompt
Write Python code for a Quiz model class.
Test prompt
Write a Python unittest for the Quiz model class.
Prompt Template
Create a small example to say hello world using the web_-
framework framework
Example Prompt
Create a small example to say hello world using the Django
framework
You will get the complete instructions to setup the environment and
run a Hello World example. For example, ChatGPT provided the
following instructions.
Install Django: If you haven’t already, you can install Django by
running the following command in your terminal.
1 [Link]
Prompt One: Start your web project (with Django) 21
Now if you login, you see the tables that are created.
Prompt One: Start your web project (with Django) 23
The model classes are stored in the [Link] file. The views,
likewise, are stored in the [Link] file. Create a templates
directory in the helloworldapp folder. This directory will store your
html templates.
You will be using prompts to generate code, and then pasting that
code into the appropriate location. Be sure to familiarize yourself
with the project structure so you can be efficient at integrating code
generated by your AI helper.
One recommendation to simplify project organization is having a
having a [Link] file to store reusable functions. This is not
required by Django. However, it is a common construct that has
been helpful for designing applications for many years.
At the end of the day, it is up to you how you want to organize
the code within your project. As long as you know where different
types of components are stored and it makes sense to you, then you
are in good shape.
4 Prompt Two: Create
your models
The best place to start building an application is by modeling your
data. If you have a good understanding of your data model, you
will also have a solid foundation for designing the rest of your
application.
Model classes are a great place to start when building Django
web applications. Once you have model classes, you can create
the corresponding database tables as well. Model classes typically
provide the building blocks for everything else you build in the
application.
You can also break this up into multiple prompts. This becomes
more important if you have a large number of requirements and
model entities.
Prompt template
You are a software designer building a project_name appli-
cation. Define the model classes needed to implement the fol-
lowing requirements. 1. Requirement_1 2. Requirement_2
3. Requirement_3
Example prompt
You are a software designer building an online quiz appli-
cation. Define the model classes needed to implement the
following requirements. 1. Each quiz has a given name and
topic. 2. Each quiz can have many questions. 3. Store the
results for each quiz taken by a participant.
Test prompt
None. Review the AI output.
Prompt template
Write the Python code for these model classes based on the
framework_name framework
Example prompt
Write the Python code for these model classes based on the
Django framework
Prompt Two: Create your models 30
Test prompt
Write Django test cases for these models
Anytime you have new or updated model classes, you will want to
create migrations and apply them to your database. To do this, you
first need to let Django know to look in your applications.
Open the helloworld/[Link] file in PyCharm, and add the
HelloworldappConfig line to the INSTALLED_APPS section:
Prompt Two: Create your models 31
1 # Application definition
2
3 INSTALLED_APPS = [
4 '[Link]',
5 '[Link]',
6 '[Link]',
7 '[Link]',
8 '[Link]',
9 '[Link]',
10 '[Link]',
11 ]
The first command created the migration files which define the
database tables using a Django DSL, or Domain-Specific Language.
The second command runs the file against the database to actually
create the tables. You can now login to the sqlite database and see
the tables.
Prompt Two: Create your models 32
Prompt template
Create a diagram that shows the relationships between the
model classes.
1 'django_extensions',
You can now run the following command from the helloworld
directory. This will create a model diagram with the name you
specify. In this example, the diagram will be created with the
filename myapp_models.png.
Prompt Two: Create your models 33
If you want to see more options for the model diagram generation,
use the following command.
Note that the last token uses whatever name you gave your Django
app. Within that app, the tests token that follows refers to the
[Link] file.
Be in the habit of always using the test prompts and running these
tests after each iteration or step in the process. It is significantly
easier to identify a problem right away. If the issue doesn’t pop up
until a few steps later, it will be more challenging to narrow down
where the problem was introduced.
5 Prompt Three:
Implement your first use
case
With the models in place, you are in a position to build user
interfaces and services that leverage those model entities.
What user interfaces and services do we need? The answer to that
question is driven by your application use cases. The first step in
this phase is to identify the user personas.
• The quiz creator, the user who creates quizzes and can view
aggregate results and metrics.
• The quiz participant, the user who takes the quiz and re-
ceives their score.
If we decide that any user can create quizzes, then all users can play
both roles.
Given that aggregate quiz results are typically not sensitive data,
we can also allow any user to see the overall results for any quiz.
Prompt Three: Implement your first use case 37
The only restriction then, is that participants are the only user who
can see their own individual quiz results. Scores are available to
other users only in an aggregated or anonymized form.
All of this happens in the Create a Quiz use case. This use case
covers the creation of 3 of the 5 model entities in the system (Quiz,
Question, Answer). The creation of Participant occurs in the Create
Account use case. The creation of Results occurs as a part of the Take
a Quiz use case.
After thinking through all of this, list the actions that each user
persona can perform in your application. The following table lists
the actions, or use cases, for the quiz application.
We can now map out the flow each user takes through these use
cases.
After a user has created their account, the start point for any
workflow is to view the list of quizzes. Let’s implement that use
case first.
First, ask yourself, does this use case require any underlying
business services? Should we break it down into multiple prompts?
In this case, view the list of quizzes is a fairly simple use case. We
Prompt Three: Implement your first use case 39
can go straight into the basic use case prompt shown below.
Prompt template
Write the Python Django code to use_case_description.
Create a custom view in Django with description_of_-
page_contents. Create the corresponding HTML template
in Django to display_details.
Example prompt
Write the Python Django code to display a list of Quizzes.
Create a custom view in Django with the list of quizzes from
the database. Create the corresponding HTML template in
Django to display each quiz name and topic.
Test prompt
Write a Django test case for this view
Copy the view code and add it to your [Link] file. Create a new
HTML file in the templates directory called quiz_list.html and
copy the template code into that file.
ChatGPT will usually remind you to put an entry in the [Link]
file. You can also prompt it to give you code. For this case, the only
new url entry is as shown below.
Prompt Three: Implement your first use case 41
That test should pass. Now let’s create an actual quiz so we can see
Prompt Three: Implement your first use case 42
1. Create a form for the user to enter the name of the quiz and
the topic
2. Create some number of quiz questions. For our application,
we decide to use generative AI to create the questions for us.
Thus, this is a candidate for a business service.
3. Store the quiz, the list of questions, and the answers in the
database.
4. Confirm to the user the quiz was created.
You can see what type of component will be needed for each step,
as shown in the table below.
Prompt Four: Implement a business service 44
1 import openai
2 import os
3 from dotenv import load_dotenv
4 load_dotenv()
5
6 def call_chatgpt(prompt, temperature = 0.7, max_tokens = \
7 1024):
8 # Set up OpenAI API key
9 openai.api_key = [Link]("OPENAI_API_KEY")
10
11 response = [Link](
12 engine="text-davinci-003",
13 prompt=prompt,
Prompt Four: Implement a business service 45
14 max_tokens=max_tokens,
15 temperature=temperature,
16 )
17
18 return [Link][0].text
1 def call_bard(query):
2 bard = Bard()
3 answer = bard.get_answer(query)
4 print(answer)
5
6 # Only return response text within the delimeter,
7 # typically triple backticks
8 response_text = ""
9 lines = answer['content'].split('\n')
10 inside_delimeter = False
11 for line in lines:
12 if [Link]("```"):
13 inside_delimeter = not inside_delimeter
14 elif inside_delimeter:
15 if len(line) > 0:
16 response_text = response_text + line + '\\
17 n'
18
19 return (response_text)
Bard tends to always respond with a first line that says, “Sure, I
can do that”. The information specifically requested in a prompt is
Prompt Four: Implement a business service 46
This makes it easy for the application software to parse and use
response data. In general, we have found that using XML is the
most effective format. If you were writing code by hand, you likely
would not use XML. Json would be a more logical choice these days.
However, in our testing, XML has been found to be more reliable
for AI code generators, both in terms of creating the data and then
also parsing it. Bard had trouble correctly creating JSON data as it
mixed up quotes and double quotes within the json content. Thus,
we specify XML as the response format in the code example below.
Prompt Four: Implement a business service 47
1 def generate_question(topic):
2
3 # Define the prompt to generate trivia questions on t\
4 he given topic
5 prompt = f'''Generate one trivia question on the topi\
6 c of {topic}.
7 Provide four possible answers and then indicate the lette\
8 r of the correct answer.
9 Format your response using the following XML template.
10
11 <response>
12 <question>[QUESTION_TEXT]</question>
13 <a>A) [ANSWER_1]</a>
14 <b>B) [ANSWER_2]</b>
15 <c>C) [ANSWER_3]</c>
16 <d>D) [ANSWER_4]</d>
17 <correct_answer>[CORRECT_ANSWER_LETTER]</correct_answer>
18 </response>
19 '''
20
21 return call_chatgpt(prompt)
Prompt template
Write a Python function to parse text data and create model_-
objects. The representative format of the text is as follows:
example_data_format
Example prompt
Write a Python function to parse text data and create a corre-
sponding Question model instance as well as corresponding
Answer model instances. The correct answer should set the
boolean flag on the corresponding Answer instance. The
representative format of the text is as follows:<correct_an-
swer>B</correct_answer>
Test prompt
Write a Django test case for the generated_function_name
function.
The first code that AI generated had a subtle error which caused
our test to fail.
If you get an error of this form, you can simply tell the AI in a
follow up prompt that you got this error. In our case, it was able to
rewrite the code to fix the problem. The Question instance in this
function has to be created with the reference to the related existing
quiz.
This issue highlights the importance of always generating test code
using the test prompt from the template, and then running the tests.
For the code generated above, the test prompt is shown below.
Test Prompt
Write a Django test case for the create_question_with_an-
swers_from_xml function.
You can then run the tests using the following command.
Prompt Four: Implement a business service 50
It is much easier to identify and resolve issues with the code when
you can isolate the cause and ask the AI to rewrite the code while
all of the information is in context.
You can always rewrite code later on in the development process.
You may need to provide the code in question in the prompt.
However, if you bundle a series of generated code changes at one
time, diagnosing which code caused the problem can become more
challenging and time-consuming.
Now that we have the business service needed for the Create a Quiz
use case, we can generate the rest of the code.
What you read was a sample of the book. If you like what you read
so far, please support the author by purchasing the book.
7 Prompt Five:
Implement a complex
use case
The same use case prompt template can be used to implement the
Create a Quiz capability. The templation is to write the prompt as
shown below.
This prompt will generate code that implements half of the steps in
this use case. It will create an HTML form and save a Quiz instance
to the database. However, it will not use the business service we
just generated. The quiz will not have any questions or answers.
We need to be specific in the requirements provided in the prompt.
Here is a prompt that incorporates the missing steps.
Prompt template
Write the Python Django code to use_case_description.
Create a custom view in Django with description_of_-
page_contents. Create the corresponding HTML template
in Django to display_details.
Example prompt
Write the Python Django code to create a quiz. Create a
Prompt Five: Implement a complex use case 52
The AI output generates three different pieces of code that you need
in your application.
Here is the generated view code which does exactly what we asked
it to do. It does only create one quiz question at this point, but we
can modify that later after the basic capability is working.
Prompt Five: Implement a complex use case 53
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <link rel="stylesheet" href="[Link]">
5 <title>{% block title %}My amazing site{% endblock %}\
6 </title>
7 </head>
8
9 <body>
10 <div id="content">
11 {% block content %}{% endblock %}
12 </div>
13 </body>
14 </html>
Running the server and testing in the browser shows that the code
is working.
Prompt Five: Implement a complex use case 55
We can see the quiz we created in the quiz list now. We can also
see the question and answer data in the database.
Prompt template
Modify the component_name component_type to
change_description. The existing code is as follows:
existing_code
Example prompt
Modify the create_quiz view to create five quiz questions
instead of just one.
Test prompt
Modify the Django test case for the create_quiz view
This code change worked great, with one caveat. Using Bard as
the generative AI service, this is the data it created. As you can
see, it used the same question multiple times. Obviously, we want
original questions every time.
Prompt Five: Implement a complex use case 58
The ChatGPT API has the temperature setting which controls the
creativity. A high temperature setting would likely prevent us from
ever seeing the exact same question twice. As expected, ChatGPT
does a better job with this parameter setting in generating unique
question.
Example prompt
Modify the [Link] template to have nicer looking CSS
styles. Also, it should have a header section at the top, and a
sidebar with links to go back to the list of quizzes and also to
create a quiz. Use bootstrap as the CSS framework.
Any templates that do not already extend the base template should
be modified to do so. We can also make the quiz list be the default
page by modifying the [Link] file accordingly, as shown below.
1 urlpatterns = [
2 path('', quiz_list, name='quiz_list'),
3 path('quiz-list/', quiz_list, name='quiz_list'),
4 path('create-quiz/', create_quiz, name='create_quiz'),
5 path('quiz-created/', quiz_created, name='quiz_create\
6 d'),
7 path('admin/', [Link]),
8 ]
When you browse to the root URL, you now see the quiz list with
the improved look and feel.
Prompt template
Modify the component_name component_type to
change_description. The existing code is as follows:
existing_code
Example prompt
Modify the quiz_list view to make each quiz name a link to a
new view called take_quiz.
Test prompt
Modify the Django test case for the quiz_list view
The view doesn’t need to change. It only retrieves the quiz data
from the database. However, the AI does add a placeholder for the
new take_quiz view. The template is modifed to create a link for
each quiz name.
If the AI did not generate the [Link] entry, you can prompt for it
as follows.
Prompt Six: Implement a use case that uses generated data 61
Example prompt
Write the [Link] entry for take_quiz
In this case, the view and template code to perform steps 1-3 are
all intertwined. It would be difficult to break them up into discrete
prompts. Step 4 can be treated as a follow-up prompt. It will have
its own view and display characteristics.
Prompt Six: Implement a use case that uses generated data 62
Prompt template
Write the Python Django view and HTML template for the
use_case_description. description_of_use_case_steps.
Example prompt
Write the Python Django view and HTML template for the
take_quiz view. It should display one question at a time
along with the answers and prompt the user for their chosen
answer. It should keep track of how many correct answers
the users gets. On the the name of the quiz and the current
question number near the top of the form. At the end of the
questions, it should go to a quiz_result view.
Test prompt
Write a Django test case for the take_quiz view
The generated code all seems to work well. Here is a screen capture
from the math quiz generated earlier.
Prompt Six: Implement a use case that uses generated data 63
13 if user_answer:
14 current_question = questions[current_question\
15 _index]
16 answer = get_object_or_404(Answer, pk=user_an\
17 swer)
18
19 if answer.is_correct:
20 correct_answers += 1
21
22 current_question_index += 1
23 [Link]['current_question_index'] = curre\
24 nt_question_index
25 [Link]['correct_answers'] = correct_answ\
26 ers
27
28 if current_question_index >= total_questions:
29 del [Link]['current_question_index']
30 del [Link]['correct_answers']
31 return redirect('quiz_result', quiz_id=quiz_i\
32 d)
33
34 else:
35 if 'current_question_index' in [Link]:
36 del [Link]['current_question_index']
37 if 'correct_answers' in [Link]:
38 del [Link]['correct_answers']
39
40 current_question = questions[current_question_index]
41
42 context = {
43 'quiz': quiz,
44 'question': current_question,
45 'current_question_index': current_question_index \
46 + 1,
47 'total_questions': total_questions,
Prompt Six: Implement a use case that uses generated data 65
48 }
49
50 return render(request, 'take_quiz.html', context)
1 {% extends '[Link]' %}
2
3 {% block content %}
4 <h2>{{ [Link] }}</h2>
5 <h3>Question {{ current_question_index }} of {{ total\
6 _questions }}</h3>
7
8 <form method="POST" action="{% url 'take_quiz' quiz.i\
9 d %}">
10 {% csrf_token %}
11
12 <h4>{{ [Link] }}</h4>
13
14 {% for answer in [Link] %}
15 <div>
16 <input type="radio" id="answer_{{ answer.\
17 id }}" name="answer" value="{{ [Link] }}">
18 <label for="answer_{{ [Link] }}">{{ an\
19 [Link] }}</label>
20 </div>
21 {% endfor %}
22
23 <button type="submit">Next</button>
24 </form>
25 {% endblock %}
Prompt template
Write the Django code for the view_name view and template.
Example prompt
Write the Django code for the quiz_result view and template.
Test prompt
Write a Django test case for the quiz_result view
Here is the generated code for the quiz_result. Note that AI did not
remember it already had the correct answers stored in the session.
In the future, we will store this information in the database, but
for now we can modify the code to simply get the value from the
session.
23 }
24
25 return render(request, 'quiz_result.html', context)
Our application now displays the results after you finish the quiz.
Looks like I didn’t do so well. Need to practice up on my mathe-
matics.
1 class Result([Link]):
2 quiz = [Link](Quiz, on_delete=[Link]\
3 DE, related_name='results')
4 user = [Link](User, on_delete=[Link]\
5 DE, related_name='results', null=True)
6 correct_answers = [Link](null=True)
7 score = [Link]()
Example prompt
Write the code to authenticate the user to a Django Python
Prompt Seven: User authentication 69
You may get code with the Django built-in LoginView. A follow up
prompt provided this code, which allowed us to easily change the
redirect.
1 def login_view(request):
2 if [Link] == 'POST':
3 username = [Link]['username']
4 password = [Link]['password']
5 user = authenticate(request, username=username, p\
6 assword=password)
7 if user is not None:
8 login(request, user)
9 # Redirect to the desired page after successf\
10 ul login
11 return redirect('quiz_list')
12 else:
13 # Authentication failed
14 return render(request, '[Link]', {'error'\
15 : 'Invalid credentials'})
16 else:
17 return render(request, '[Link]')
1 {% extends '[Link]' %}
2
3 {% block content %}
4 <h2>Login</h2>
5 <form method="POST" action="/login/">
6 {% csrf_token %}
7 <input type="text" name="username" placeholder="U\
8 sername"><br/>
9 <input type="password" name="password" placeholde\
10 r="Password"><br/>
11 <input type="submit" value="Login">
12 </form>
13 {% endblock %}
Example prompt
Write the code to create a Django user, including the view
and the corresponding HTML template.
11 return redirect('login')
12 else:
13 form = UserCreationForm()
14 return render(request, '[Link]', {'form': form\
15 })
1 {% extends '[Link]' %}
2
3 {% block content %}
4 <h2>Welcome to the Quiz App!</h2>
5 Please register below to get started.<br/><br/>
6 <form method="post">
7 {% csrf_token %}
8 {{ form.as_p }}
9 <button type="submit">Register</button>
10 </form>
11 {% endblock %}
1 def quiz_list(request):
2 if not [Link].is_authenticated:
3 return register(request)
Now, when you start the server and browse to the app, you will see
the following screen (assuming you have not yet logged in).
Prompt Seven: User authentication 72
A successful login attempt redirects you to the quiz list and now
we have the user identify, so we can persist the results after they
complete a quiz.
Prompt Seven: User authentication 73
10 Prompt Eight:
Reporting use case
The quiz_result view already displays the results to the user. Now,
we want to modify that code to also persist the results to a database
for reporting purposes. The code addition is fairly simply, but we
can prompt AI to write it for us.
Prompt template
Modify the component_name component_type to
change_description. The existing code is as follows:
existing_code
Example prompt
Modify the quiz_result view to save the data to the database
using a Result model.
Test prompt
Modify the Django test case for the quiz_result view
Prompt template
Write the Python Django code to use_case_description.
Create a custom view in Django with description_of_-
page_contents. Create the corresponding HTML template
in Django to display_details.
Example prompt
Write the Python Django code to create a graph of quiz results
for a given quiz. Create a custom view in Django with a bar
chart of quiz results by letter grade, where an A is a score of 90
or above, a B is a score of 80-89, etc. Create the corresponding
HTML template in Django to display the graph for a given
quiz.
Test prompt
Write a Django test case for this view
1 INSTALLED_APPS = [
2 '[Link]',
3 . . .
4 'chartjs'
5 ]
The AI generated some interesting view code that derives the letter
grades from the scores. However, it didn’t use it at the end. The
view method was simply generated as follows.
1 urlpatterns = [
2 path('quiz/<int:quiz_id>/results/chart/', quiz_result\
3 s_chart, name='quiz_results_chart'),
4 ]
Finally, the template has the logic to create the bar chart.
Prompt Eight: Reporting use case 78
1 {% extends '[Link]' %}
2
3 {% block content %}
4 <h2>Quiz Results Chart</h2>
5 <div class="container">
6 <canvas id="quizResultsChart"></canvas>
7 </div>
8
9 <script src="[Link]
10 /script>
11 <script>
12 [Link]('DOMContentLoaded', fun\
13 ction() {
14 var chartData = {
15 labels: {{ labels|safe }},
16 datasets: [{
17 label: 'Quiz Results',
18 data: {{ data|safe }},
19 backgroundColor: 'rgba(54, 162, 235, \
20 0.5)',
21 borderColor: 'rgba(54, 162, 235, 1)',
22 borderWidth: 1
23 }]
24 };
25
26 var chartOptions = {
27 responsive: true,
28 scales: {
29 y: {
30 beginAtZero: true,
31 stepSize: 1
32 }
33 }
34 };
35
Prompt Eight: Reporting use case 79
With all of this code integrated into our application, the graph is
now working. We can add links in the quiz list for reports, and
here is the result.
11 Prompt Checklist
We have written an entire quiz application now using eight prompt
templates. The first few prompts were used to design and generate
the model classes upon which the rest of the application was based.
We used the use case prompt template for each use case. When
needed, we used the modify use case template as well. There were
also some follow up prompts that were needed.
Let’s review each of the prompt templates that we used. This will
also serve as a handy checklist for you to use when generating your
applications.
Project setup
Create a small example to say hello world using the frame-
work_name framework
Models
You are a software designer building a project_name appli-
cation. Define the model classes needed to implement the fol-
lowing requirements. 1. Requirement_1 2. Requirement_2
3. Requirement_3
Write the Python code for these model classes based on the
framework_name framework
NOTE: After each model update, you need to run the following
Django commands:
Business Services
(Generative AI) Generate output_requirements. Format
your response using the following XML template. example_-
xml_structure
Write a Python function to parse text data and create model_-
objects. The representative format of the text is as follows:
example_xml_structure
Use Cases
Write the Python Django code to use_case_description.
Create a custom view in Django with description_of_-
page_contents. Create the corresponding HTML template
in Django to display_details.
(Alternate form) Write the Python Django view and HTML
template for the use_case_description. description_of_-
use_case_steps.
Modify the component_name component_type to
change_description. The existing code is as follows:
existing_code
Authentication
Write the code to authenticate the user to a Django Python
application and the corresponding login view
Note that you can use the use case templates to prompt AI for login
and logout code.
You now have the basic tools to generate almost any application
using AI.
Prompt Checklist 82
The rest of this book will apply this process and the associated
templates to building other types of applications. We will see
how the same methodology can be used to build many types of
applications much faster than was previously possible.