Reputation: 47
I am a newbie with Django. I created a table using Django models and inserted an object using the python shell. When I access the object using object id on Django template, I get the result as "{{obj.id}}-{{obj.content}}" rather than the actual data values.
The views.py file
from django.shortcuts import render
from django.http import HttpResponse, Http404
from .models import Tweet
# Create your views here.
def home_view(request, *args, **kwargs):
return HttpResponse("<h1>Hello World!<h1>")
def tweet_detail_view(request, tweet_id, *args, **kwargs):
try:
obj = Tweet.objects.get(id = tweet_id)
except:
raise Http404
return HttpResponse("<h1>Hello {{obj.id}} - {{obj.content}}</h1>")
The models.py file
from django.db import models
# Create your models here.
class Tweet(models.Model):
content = models.TextField(blank=True, null=True)
image = models.FileField(upload_to='images/', blank=True, null=True)
The urls.py file
from django.contrib import admin
from django.urls import path
from tweets import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home_view),
path('tweet/<int:tweet_id>', views.tweet_detail_view),
]
The Shell
(base) ankita@ankita-HP-Laptop-15-bs0xx:~/dev/trydjango/tweetme$ ./manage.py shell
Python 3.7.4 (default, Aug 13 2019, 20:35:49)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from tweets.models import Tweet
In [2]: obj = Tweet.objects.get(id = 1)
In [3]: obj
Out[3]: <Tweet: Tweet object (1)>
In [4]: obj.content
Out[4]: 'Hello World!'
In [5]: obj.id
Out[5]: 1
The localhost page have only next text:
Hello {{obj.id}} - {{obj.content}}
Upvotes: 0
Views: 978
Reputation: 667
If you create template to render your page, this task is quite simple to achieve. So, why don/t you create template and render it using render?
hello_word.html
<html>
<body>
<h1>Hello {{obj.id}} - {{obj.content}}</h1>
</html>
</body>
views.py
instead of HttpResponse:
return render(request, 'hello_world.html', {'obj': obj})
I would say that this is a regular Django way to render templates.
Upvotes: 2