- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
In this tutorial, we will learn how to manage databases and flash messages in Django without any errors.
Steps :
1.Name the input boxes in HTML with the name tag2.Add form attributes:
<form method="post" action="/contact">
3.Add
{%csrf_token%}
at the start of the form.4.Making a Database: Go to models.py and create a model like this:
class TableName(models.Model):
name = models.CharField(maxlength=100)
email=models.CharField(maxlength=100)#You can use models.EmailField, models.TextField models. IntegerField, models.DateField also
Go to admin.py and register your model like this
admin.site.register(TableName):
'appname.apps.AppConfig'
"python mange.py make migrations"
. This creates the file consisting all the changes made to your database.9.Run the command "
python mange.py migrate
". This command applies all the changes made to your database.10.Import your model in views.py like this
from app.models import Table_Name
def contact():
if request.method == "POST"
name = request.POST.get('name')
email = request.POST.get('email') # Fetches all the data from the
request.
contact = Table_Name(name=name, email=email) # Create an instance of the
model in models.py.
contact.save() # Saves the Data.
return render(request, contact.html)
By now your database should be working. But let's see how to customize and improve it by flashing messages.
To customize the database, to show the name of the users sending messages we have to define a function like this:
def __str__ (self):
return self.name
Note: It is not required to run "python manage.py make migrations", "python mange.py migrate" commands after this step.
Flashing messages:
To flash messages we have to import a module in settings.py called constants like this:
from django.contrib.messages import constants as messages
Also, import it in views.py like this:
from django.contrib import messages
To flash a "success" message use messages.success(request, "MESSAGE")
Go to base.html(Base Template of all the HTML pages) and then define a message like this:
{% if messages %}
{%for message in message %}
<b>{message.tags} :<b> {% message %}
{% endfor %}
{% endif %}
Thanks for Reading.
- Get link
- X
- Other Apps
Comments
nice content and very helpful
ReplyDeleteSEGA digitale 2021 ▷ Latest Updates - Latest Version
ReplyDeleteProducts 카지노사이트 and Services gioco digitale · Gigade Entertainment · Entertainment ミスティーノ · Gaming · Entertainment