User interface in python django - python

I new to Python and Django, i am trying to create a user interface using django for the calculation of the speed (speed= distance/time). I have created a project using django in that i have created a weapp called speed. The below are my files
Webapp
speed
-Templates
-views.py
-forms.py
-urls.py
webapp
-settings.py
-urls.py
-init.py
-wsgi.py
My codes:
forms.py
from django import forms
class Calculatespeed(forms.Form):
distance=forms.CharField(
required=True,max_length=10,
widget=forms.TextInput(attrs={"placeholder":"0.0",
"style":"width:100px"}))
time=forms.CharField(
required=True,max_length=10,
widget=forms.TextInput(attrs={"placeholder":"0.0",
"style":"width:100px"}))
views.py
# Create your views here.
from django.shortcuts import render
from django import template
from speed.forms import Calculatespeed
def speed(Speed):
distance=float(raw_input("Please Give the disance"))
Time=float(raw_input("Please Give the Time"))
Speed=distance/Time
return Speed
def Main(request):
if request.GET:
form = speed_form.SpeedForm(request.GET)
if form.is_valid():
Distance = form.cleaned_data["distance"]
Time = form.cleaned_data["time"]
return shortcuts.render_response(
"speed.html",
page_context,
context_instance=template.RequestContext(request)
)
Templates:
<html>
<head>
<title>WebApp1</title>
</head>
<h1>Speed Calculator</h1>
<form action="/contact/" method="post">
<br>
Distance:
<input type="interger" distance="Distance" />
<br>
Time:
<input type="interger" Time="Time" />
<input type="submit" value="Submit" />
urls.py
from django.conf.urls import *
from speed.views import speed
urlpatterns = patterns('',
url(r'^$', speed),
)
The problem is when i am trying run server i am getting an error i am unable to get the user interface of speed can any one help me on this.
Is the templates files and all the other files which i gave are correct or not ??
Thanks in advance

There are a lot of things wrong with your code, so it seems to me like a very basic misunderstanding of working with django, and maybe with python in general. there are a lot of pythonic errors in your code (you have wrong indentation, you did a 'return' without a function, and so on), and a lot of django-ic errors too (you can't use raw_input in django it doesn't work that way, you created a form but then wrote the entire html yourself).
I suggest that before you write it in django, write this as a python program and see if it works. When you feel like you understand the language enough and want to web-app your program, go over the django docs and take some time to learn how it works.

You're using raw_input in your view to ask data wanted. I think you didn't understand what a web app is :-) (Or the speed function is just for tests, so in that case it would be placed in the tests.py of the application)
In your view main(request), you should init a form and if a request POST (can be check with request.method) is sent, check if the form is valid.
Here some code which might working (I replace the render_to_response by render to not confusing you with the context that you misused)
from django.shortcuts import render
def speed(distance, time_): # don't like to name a var time because of the module with the same name...
return distance/ time_
def compute_speed(request):
if request.method == 'POST':
form = Calculatespeed(request.POST)
if form.is_valid():
distance = form.cleaned_data["distance"]
time_ = form.cleaned_data["time"]
speed = speed(distance, time_)
# Do your stuff here
else:
form = Calculatespeed()
return render(request, "speed.html", {'form': form})
And in the urls.py:
urlpatterns = patterns('',
url(r'^$', compute_speed, name="compute_speed"),
)
You have also some typos in your HTML:
The inte r ger input type doesn't exists
Why action="/contact/" instead of {% url 'compute_speed' %} ?
Your form isn't closed

Related

How to redirect to another url after sending a POST request to admin:auth_user_password_change in Django?

I'm using the built in django admin site for the application's admin site in a sense that POST requests are built identically to its equivalent admin site, and sent to the same urls. So it's like the application admin site is just a wrapper for the admin site.
My problem is, I don't know how to redirect back to url where it was originally posted. Currently it redirects to the Change User admin page. I'd like it to redirect back to the page.
Here's my change-password-template.html:
<div>
<form action="{% url 'admin:auth_user_password_change' user.pk %}" method="post" id="change-password-form">
{% csrf_token %}
# ... here goes the password fields
<input type="submit" value="Change password">
</div>
<input type="hidden" name="next" value="{% url 'change_password' id=user.pk%}"> # my attempt at trying to redirect back to the original webpage
</div>
</form>
</div>
So, it does correctly post to admin/auth/user/{{user.pk}}/password/ but instead of redirecting back to the that page it instead redirects to: admin/auth/user/{{user.pk}}/change/. How can I make it do so?
The wrong way to do it...
You would need to overwrite the user_change_password method in your User admin, since that is where the redirect happens:
# contrib.auth.admin.py
def user_change_password(self, request, id, form_url=''):
...
if request.method == 'POST':
form = self.change_password_form(user, request.POST)
if form.is_valid():
...
return HttpResponseRedirect(
reverse(
'%s:%s_%s_change' % (
self.admin_site.name,
user._meta.app_label,
user._meta.model_name,
),
args=(user.pk,),
)
)
Since this ModelAdmin is registered in the auth app, you will need to unregister that, add your own custom UserAdmin. There are clear instructions on how to do this in the django docs. Once you have done that simply overwrite the method above and edit the redirect.
This would be much more effort than it's worth however, and more importantly it would also be a nasty hack. It's not what the admin interface is intended for. (It would also have the unintended side-effect that when you actually do use the admin app, it will now redirect to wherever you now have told it to - this would be very unusual behaviour).
A better solution...
If you want to add an end-point where a user can change their password it's not difficult to do it yourself, and that would be the best solution in this case.
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.urls import reverse
def change_password(request, user_id):
new_password = request.POST["password"]
user = User.objects.get(id=user_id)
user.set_password(new_password)
user.save()
return HttpResponseRedirect(reverse('your_url_here))
You'll need to add some additional checks (e.g. make sure the user has the appropriate permissions, make sure the request is a POST etc.).
Probably better still...
Django actually has a built in view for doing this, that you can subclass to customise.
# views.py
from django.contrib.auth.views import PasswordChangeView
class MyPasswordChangeView(PasswordChangeView):
success_url = reverse("url_to_redirect_to")
# urls.py
urlpatters = [
path('change_password', MyPasswordChangeViews.as_view())
]
You can read more about these built in views here.

How to execute script python when i click button in form html?

hello how can i run script that i build on python when i click button on form html
i saw examples like this but i dont get it:
Html code: index.html
<form action="{% url my_view %}" method="post">
<input type="submit" value="Ok">
</form>
views.py
import django.shortcuts import render
def my_view(request):
if request.method == 'POST':
import set_gpio
#my url is "templates/load.py"
return #How can i return?
You need to return an HttpResponse object from your view. You can return one response inside your if statement, and another outside of it (so anything but a POST). Usually the render shortcut is used to render a response from a template. So your view would be something like:
import django.shortcuts import render
def my_view(request):
if request.method == 'POST':
# The user clicked the button (POST)
return render(request, "load.html")
# The user is just loading the view for the first time (GET)
return render(request, "index.html")
I highly suggest going through the django tutorial.
You have to realise that Django is a HTTP based framework meaning that when an HTTP request is sent to a url, Django will be allowed to perform an action. So, every function is actually a reaction to the HTTP requests that the user sends to your urls.
Also, if you are using Django template system, the html file should be rendered by Django in the first place. So, you cannot have a standalone html file with {% url my_view %} in it.
First, you have to configure the main urls.py which is in a folder with the same name as your project.
Second, in your app, create an urls.py file and configure it.
At the end, you connect your my_view to a specific or set of urls and will be triggered when a request is sent to that url, whether GET or POST.
These are somewhat large (and easy) topics for which you have to watch a tutorial or read the Django documentations.

I want something to be executed through django

I know this question was asked before, but none worked for me. I have this code that I want it to be executed when a button is clicked and a message is passed
import time
from sinchsms import SinchSMS
number = '+yourmobilenumber'
message = 'I love SMS!'
client = SinchSMS(your_app_key, your_app_secret)
print("Sending '%s' to %s" % (message, number))
response = client.send_message(number, message)
message_id = response['messageId']
response = client.check_status(message_id)
while response['status'] != 'Successful':
print(response['status'])
time.sleep(1)
response = client.check_status(message_id)
print(response['status'])
Basically, what I need is to add an input in a template "HTML File", this input get passed to the message variable in the code above, same with the number. I can easily do that with instances, but how can the below get executed when a button is clicked from the form in the template?
I'm kinda newbie in Django and still finding my way
Here is the tutorial that explains how to make the python file, but execute it from the shell, not a django application.
I hope I was clear describing my problem and any help would be appreciated!
All you need is a form with a message field. In a view, you want to show that form and when the user press submit, you want to execute your script.
Here is some pseudo-code:
urls.py
url('^my-page/' my_views.my_view, name='my-page'),
forms.py
SmsForm(forms.Form):
message = fields.CharField(...)
my_views.py
def my_view(request):
form = SmsForm(data=request.POST or None)
if request.method == 'POST':
if form.is_valid():
send_sms(form.cleaned_data['message']) # do this last
messages.success(request, "Success")
return HttpResponseRedirect(request.path)
else:
messages.warning(request, "Failure")
return render(request, 'my_template.html', {'form': form})
Check the Django documentation about urls, views, forms and messages and proceed step by step:
get the page to load
get the form to load
get the form submission to work and simply show "Success" or "Failure"
finally, write the send_sms function (you've almost done it)
Lets start from the dust cloud.
What you are asking is mostly about how the web pages work. You need to know how to pass parameters using HTML. There are lots of ways to do it. But with django there is a pattern.
You need a url, and a view to catch any requests. Then you need to create a template and a form inside it. With this form you could create some requests to send data to your view.
To create you need to edit urls.py inside your project add an url:
urls.py
from django.conf.urls import url
from my_app.views import my_view
urlpatterns = [
...
url(r'^my_url$', my_view, name='my_view')
...
]
For more about urls please look at URL dispatcher page at documentation.
Then create your view inside your app which is my_app in my example. Edit my_app/views.py
my_app/views.py
from django.http import HttpResponse
def my_view(request):
return HttpResponse('IT WORKS!')
This way you get a working view which could be accessed with path /my_url. If you run ./manage.py runserver you could access your view from http://localhost:8000/my_url.
To create a form you need to create a template. By default django searches app directories for templates. Create a templates directory in your app, in our case my_app/templates and create an HTML file inside. For example my_app/templates/my_form.html. But i advice to create one more directory inside templates directory. my_app/templates/my_app/my_form.html. This will prevent template conflicts. You can check Templates page at documentation for more.
my_app/templates/my_app/my_form.html
<html>
<body>
<form action="/my_url" method="POST">
{% csrf_token %}
<input type="text" name="number">
<input type="text" name="message">
<input type="submit" value="Run My Code">
</form>
</body>
</html>
This is the one of the ways of creating your form. But I do not recommend it. I will make it prettier. But first lets "Make it work", edit your views.py:
csrf_token is a django builtin template tag, to put CSRF token into your form. By default django requires CSRF tokens at every post
request.
my_app/views.py
from django.http import HttpResponse
from django.shortcuts import render
def my_view(request):
if request.method == 'GET':
return render('my_app/my_form.html')
elif request.method == 'POST':
# get post parameters or None as default value
number = request.POST.get('number', None)
message = request.POST.get('message', None)
# check if parameters are None or not
if number is None or message is None:
return HttpResponse('Number and Message should be passed')
# your code goes here
...
return HttpResponse('Your code result')
Till this point the purpose of this answer was "Making it work". Lets convert it nice and clean. First of all we would create Form. Forms are like models, which helps you create forms as objects. It also handles form validations. Forms are saved inside forms directory generally. Create my_app/forms.py and edit it:
my_app/forms.py
from django import forms
class MyForm(forms.Form):
number = forms.CharField(max_length=15, required=True)
message = forms.CharField(max_length=160, required=True)
Put your form inside your template:
my_app/templates/my_app/my_form.html
<html>
<body>
<form action="{% url 'my_view' %}" method="POST">
{% csrf_token %}
{{ form }}
</form>
</body>
</html>
Besides the form, the action of the HTML form tag is also changed.
url template tag is used to get url form url name specified in urls.py.
Instead of url tag, {{ request.path }} could have been used.
Create a form instance and pass it to the template rendering:
my_app/views.py
from django.http import HttpResponse
from django.shortcuts import render
from .forms import MyForm
def my_view(request):
if request.method == 'GET':
form = MyForm()
return render('my_app/my_form.html', {'form': form})
elif request.method == 'POST':
form = MyForm(request.POST)
# check if for is not valid
if not form.is_valid():
# return same template with the form
# form will show errors on it.
return render('my_app/my_form.html', {'form': form})
# your code goes here
...
return HttpResponse('Your code result')
You can use class based vies to write your view, but it's not necessary. I hope it helps.
You can create a view that takes up query parameters from the url and use it for further implementation. Then you can create a link/button in the html template which can redirect you to that url. For example:
in urls.py:
url(r'^run_a/(?P<msg>\w{0,25})/(?P<num>\w{0,25})/$', yourcode, name='get_msg'),
in template:
submit
in views.py:
def get_msg(request,msg,num):
message=msg
number=num
#rest of the code
Hope this helps :)

How do I include a form into my Django file?

I have a form created in mysite/new_player.html. It accepts 3 fields, user_name, real_name, and site_played that correspond to the Player table in the database.
<h1> New Player </h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="/stakeme/new/" method="post">
{% csrf_token %}
User Name: <input type="text" name="user_name" id="user_name"/><br>
Real Name: <input type="text" name="real_name" id="real_name"/><br>
Site Played: <input type="text" name="site_played" id="site_played"/><br><br>
<input type="submit" value="New Player" />
</form>
I am stuck on how to add this to my mysite/views.py file. I have gone through the polls tutorial, but the only form that is used in the tutorial is a multiple choice "choice" of the "poll" and I can't seem to adapt that to text fields.
def new_player(request):
return render_to_response('stakeme/new_player.html',
context_instance=RequestContext(request))
So as I understand it, I would need to create something like def add(request): return render_to_response('stakeme/new/'.. etc and add the POST data in here, but that's where I am lost. I am not sure how to get the data into the database.
I am reading the Django docs, but I feel like I am just compounding something that I do not understand. If someone could point me in the right direction, I would really appreciate it.
Firstly, you don't need to define a new view to process the form data. Also, you are creating your form directly in HTML - it's possible to work this way (see later section of post) but it's better (easier) to use the Django Forms library.
Using Django Forms
The documentation (v1.3 forms documentation) from the start up to and including ''Displaying a form using a template'' explains the basics of using the forms library, so I'll copy & paste liberally from there. I'll also assume that you're familiar with basic python constructs & have Django 1.3 installed. Without further ado, here's my adhoc forms tutorial.
Start a new django project:
$ django.admin.py startproject mysite
Add a new app:
$ ./mysite/manage.py startapp myapp
Lets create our contact form (modified from example in Django forms doc). Create a file in side the myapp/ directory called called forms.py and put the following in it:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField(max_length=100)
Next, since you mentioned storing data from received contact forms in a database, we'll add a model, Feedback, to track received contact forms. In your models.py file, add the following:
class Feedback(models.Model):
subject = models.CharField(max_length=100)
message = models.TextField()
sender = models.CharField(max_length=100)
def __unicode__(self):
return "Subject:{subject}\nSender:{sender}\n{msg}".format(subject=self.subject,
sender=self.sender,
msg=self.message)
(You may notice this is very similar to the form we defined earlier; normally in a scenario like this, one would use Django model forms to create a form directly from a model, but we are building our forms by hand as a learning experience)
We also need to get Django to create the required table in our database for this Feedback model, so at the top of your settings.py insert the following useful code:
import os
PROJECT_DIR = os.path.dirname(__file__)
And change the DATABASES setting in settings.py to the following to use a sqlite database:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(PROJECT_DIR, "sqlite.db").replace('\\', '/'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
Finally, change the INSTALLED_APPS setting to the following to include our recently created application myapp in the list of installed applications for mysite:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
Now run the syncdb command to get Django to create the tables in your sqlite database (which, since it's sqlite, will be created if it doesn't exist yet):
$ ./mysite/manage.py syncdb
(Django will prompt you to create a superuser as well: you don't have to create a superuser now since we don't need it and you can use django-admin.py createsuperuser to create one when you need it, but you can create now now if you like)
Now we need a view to display the contact form, and a view to thank people for submitting it. In your views.py file, add the following (modified slightly from Django forms docs):
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from myapp.forms import ContactForm
from myapp.models import Feedback
def thanks(request):
return render_to_response('thanks.html')
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
feedback = Feedback(subject=subject, message=message, sender=sender)
feedback.save()
return HttpResponseRedirect(reverse('thanks')) # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
}, context_instance=RequestContext(request))
Now we need to map URLs to views. Open mysite/urls.py and make it look like the following
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^thanks/$', 'myapp.views.thanks', name='thanks'),
url(r'^$', 'myapp.views.contact', name='contact'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
Now we need some templates to display the contact form & the thankyou page. Create a directory mysite/templates/, create a file contact.html inside it, and put the following in it:
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<p>Please fill out the following information and click submit:</p>
<form action="{% url contact %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
</body>
</html>
Also create a thanks.html page for the thank you page, and put the following in it:
<html>
<head>
<title>Thanks</title>
</head>
<body>
<p>Thank you. Your feedback is important to us</p>
<p>Please leave some more feedback at the Contact page</p>
</body>
</html>
Next, we need to make sure Django can find our templates, so modify the TEMPLATE_DIRS in mysite/settings.py setting to the following:
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_DIR, "templates").replace('\\', '/'),
)
Now, (finally!), you can run the debug server and test that everything works:
$ ./mysite/manage.py runserver 8080
Go to http://localhost:8080/ and try to enter some feedback. When you click Submit, it should put your entered details into the database & show the thank you page. You can check the details are entered into the database:
$ ./mysite/manage.py shell
Into the shell, type:
>>> from myapp.models import Feedback
>>> for f in Feedback.objects.all(): print f
(note that you need to press enter twice after entering the last line)
You should see the feedback entries you have created.
Creating forms manually in HTML
If you insist on doing this, you can access the form's request variables directly in your view using the request.POST dictionary, and then instantiating a model of your object manually & calling save (like in the contact() view function above).
I would not recommend doing this, because you lose a whole bunch of nice features that Django Forms provides (CSRF protection, validation, etc).
Other Tutorials
Since the original form of this question asked for some tutorials: the official Django wiki has a page listing some tutorials, some of which deal with forms. Be aware that a lot of those tutorials are quite old (mostly from 2007-2009).
Sounds like you want to have a good and thorough look at the
Getting started guide https://docs.djangoproject.com/en/dev/intro/
Forms documentation https://docs.djangoproject.com/en/dev/topics/forms/
After which you may come up with something along these lines. Untested and quickly scribbled together, likely to be riddled with bugs.
models.py
from django.db import models
class Person(models.Model):
user_name = models.CharField(max_length=30)
real_name = models.CharField(max_length=30)
site_played = models.CharField(max_length=30)
forms.py
from django import forms
class PlayerForm(forms.Form):
user_name = forms.CharField(max_length=30)
real_name = forms.CharField(max_length=30)
site_played = forms.CharField(max_length=30)
views.py
def player_form(request):
if request.method == 'POST':
form = PlayerForm(request.POST)
if form.is_valid():
user_name = form.cleaned_data['user_name']
real_name = form.cleaned_data['real_name']
site_played = form.cleaned_data['site_played']
player = Player(user_name=user_name,
real_name=real_name,
site_played=site_played)
player.save()
# Redirect to a thanks page maybe?
else:
form = ContactForm()
return render_to_response('contact.html', { 'form': form,})
contact.html
... lots of fancy html ...
{{ form }}
... more fancy html
You need something like this (read about form fields validation yourself):
models.py:
from django.db import models
class Player(models.Model):
user_name = models.CharField()
real_name = models.CharField()
site_played = models.CharField()
forms.py:
from django import forms
MyForm(forms.Form):
user_name = forms.CharField()
real_name = forms.CharField()
site_played = forms.CharField()
views.py:
from forms import MyForm
from models import Player
def new_player(request):
#...
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
player = Player()
player.user_name = form.cleaned_data.get('user_name')
player.real_name = form.cleaned_data.get('real_name')
player.site_played = form.cleaned_data.get('site_played')
player.save()
#...
return render_to_response('stakeme/new_player.html',
context_instance=RequestContext(request))
UPDATE:
After you get the idea, you might want to have a look at WTForms library.

Django forms question

I don't have an example because I'm not working on anything relevant right now, but am still curious, after reading the docs about formsets:
What is a best practice for having a single view with multiple different model forms that post at the same time (rather 1 combined form, since you can't post multiple forms at the same time, but for lack of a better explanation...), some being single model forms, and others being 1-or-more formsets (e.g. Person, his 1 Address, and his 1 or more Pet objects), like Django does with TabularInline. Inlines have been in Django for some times, so my suspicion is that there are better practices than what I may find by simply copy/pasting what's in admin/options.py, no?
Thanks in advance
You should:
Make sure you're using transactions (so, make sure they're turned on, and that you're using something other than MySQL with MyISAM tables). This is true all the time, really, but it's even more true now. :)
Use multiple forms.Form/forms.ModelForm objects, which are grouped together in a single HTML <form> element, such as...
Python:
from django import forms
class FormA(forms.ModelForm):
[...]
class FormB(forms.ModelForm):
[...]
HTML:
<form method="post" action="/path/to/view/">
{% csrf_token %}
{{ form_a }}
{{ form_b }}
<input type="submit" value="Submit Form" />
</form>
Then, when you're processing your forms, simply process them both and make sure that you're requiring both to be valid to actually complete the view in a success case.
from django.db import transaction
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from myapp.forms import FormA, FormB
#transaction.commit_on_success
def present_forms_to_user(request):
if request.method == 'POST':
form_a = FormA(request.POST)
form_b = FormB(request.POST)
if form_a.is_valid() and form_b.is_valid():
# processing code
return HttpResponseRedirect('/path/to/thank/you/page/')
else:
form_a = FormA()
form_b = FormB()
return TemplateResponse(request, 'templates/eggs.html', {
'form_a': form_a,
'form_b': form_b,
})
As a disclaimer, remember that this is a basic example stub, and not meant to be copied blindly. Your ultimate use case for this may be slightly different, and that's fine.

Categories