Reputation: 1
I have a Django application where most of my backend code is in views.py. In the frontend, I'm using an html template, but currently I have hardcoded options that the user can choose from a drop down menu. Those hardcoded options are all available in the sqlite3 database which is used extensively in views.py. Is there a way that I read those fields of database from the html file directly instead of hardcoding them?
Upvotes: 0
Views: 398
Reputation: 2182
Yes, if you have a model that will store the data from the fields you defined in your template then you can create a form that will store the data about that models fields, then you can just pass the form to the template, for example:
models.py
class Person(models.Model):
name = models.CharField(max_length=20)
age = models.IntegerField(default=1)
forms.py
from django import forms
from .models import Person
class PersonForm(forms.ModelForm)
class Meta:
model = Person
fields = '__all__' # or pass an iterable with your model field names as strings
views.py
from .models import Person
from .forms import PersonForm
def create_person(request):
if request.method == 'POST':
form = PersonForm(request.POST)
if form.is_valid():
person = form.save() # creates and saves a new Person instance
return redirect('person', pk=person.pk) # redirect to the view that displays the person
else:
form = PersonForm()
return render(request, 'create_person.html', {'form': form}) # pass the form to the view in a context dictionary
def person(request, pk): # pass the primary key of a person to the view
person = Person.objects.get(pk=pk)
return render(request, 'person.html', {'person': person})
create_person.html ( this is the view that will have the form )
<form method="post">
{% csrf_token %}
{{ form.as_p }} <!-- render form fields inside <p> tags ( you can also use table or list ) -->
<button type="submit" value="Save"></button>
</form>
person.html
<p>This is the page that belongs to the {{ person.name }}</p>
<p>The {{ person.name }} is {{ person.age }} years old.</p>
And finally set up the urls.py for your views:
from django.urls import path
from . import views
urlpatterns = [
path('create_person', views.create_person, name="create_person"),
path('person/<int:pk>/', views.person, name="person") # pass the pk argument into the url path here
]
Upvotes: 2