Skip to content Skip to sidebar Skip to footer

Fetch Data From Form And Display In Template

I'm trying to modify posts app from a django tutorial- https://github.com/codingforentrepreneurs/Advancing-the-Blog/tree/master/src/posts I'm creating a new field 'userc' in a for

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:

  1. Add userc = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userc', default=1) to the Post class in posts/models.py
  2. Run python manage.py makemigrations posts and then python manage.py migrate on the command line (making sure you're in the src 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"