Fetch Data From Form And Display In Template
Solution 1:
The code you have so far in forms.py
and views.py
is good. However, to display userc
in the post_detail.html
and post_list.html
templates, you'll need to save the field to the database when the form is submitted.
One way to do this is add a userc
field to the Post
model:
- Add
userc = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userc', default=1)
to thePost
class inposts/models.py
- Run
python manage.py makemigrations posts
and thenpython manage.py migrate
on the command line (making sure you're in thesrc
directory first)
Now, in the post_detail.html
template, you can add {{ instance.userc }}
to display the selected user.
note: related_name='userc'
is required as Post
already has a foreign key to the user model.
Solution 2:
Pass the instance as a context variable.
context = {
"form": form,
"instance": instance
}
Set instance = None
before to make it work if request.method
is not POST. Templates can access only the variables that are passed as context in the view. So passing instance in the context will let you use {{instance.userc}}
.
CodingforEntrepenuers is an excellent tutorial, but I would recommend to follow along more closely and get your fundamentals right.
Post a Comment for "Fetch Data From Form And Display In Template"