Object created in view isn't rendering in template - django

I'm creating a new object in a view through an external function. This is the code:
def index(request):
sousei = suii_scratch(SOUSEI_URL)
s_jikan = sousei[0]
s_suii = sousei[1]
sousei_obj = Sousei.objects.create(jikan=s_jikan, suii=s_suii)
#print(sousei_obj)
context = {
sousei_obj : 'sousei',
}
return render(request, 'index.html', context)
The external function is returning two values, that are being catched in s_jikan and s_suii variables. These variables are then used to create a new object (the model has only this two fields).
If I uncomment the print statement, I get printed the __str__ method of the model with the newly obtained data from the external function. Also, if I check the admin, the new record in the database is beign saved correctly. Until here seems everything is working fine, but when passing the created object to the template I can't get it rendered. This is template code:
{% if sousei %}
<p>{{sousei.jikan}}</p>
<p>{{sousei.suii}}</p>
{% else %}
<p>No data.</p>
{% endif %}
But I keep getting there is no data. What am I missing?

In a dictionary the key comes before the value, you were using the created object as the key and a string as the value in your context
def index(request):
...
context = {
'sousei': sousei_obj
}
return render(request, 'index.html', context)

Related

Display query set object in django template

I have a model Post that I'm trying to display all the posts onto a template. I'm including the post.html onto the home.html....
I found a similar problem to my question but the objects still are not getting displayed link
I firt tried the to use python manage.py shell to create an object. So first I did this.
Post.objects.all()
<QuerySet [<Post: test>, <Post: admin>]>
then I tried to create a new posts.
Post.objects.create(user="test", content="New comment")
but got this error:
ValueError: Cannot assign "'test'": "Post.user" must be a "User" instance.
Tried to troubleshoot and couldn't resolve it. So I just decided to write the code in the posts/views.py and it didn't work as well. I figure this is the root of my problem why the objects aren't showing up in the templates.
This is my posts/posts.views
def posts_list(request):
# if request.user.is_authenticated():
queryset = Post.objects.all()
context = {
"object_list": queryset,
"user": "username"
}
return render(request, "posts.html", context)
This is my templates/post.html
<!DOCTYPE html>
<html lang="en">
<body>
<h1>What's on your mind, {{ user }}</h1>
{ % for obj in object_list %}
{{obj.user}}<br/>
{{obj.content}}<br/>
{{obj.timestamp}}<br/>
{% endfor %}
</body>
</html>
You have asked two questions here. I'll answer both of them below:
Displaying your posts
First, you need to make sure that you are passing a user object to your template. Assuming that user info is stored in request.user, you can do so as follows:
views.py:
def posts_list(request):
if request.user.is_authenticated:
user = request.user
queryset = Post.objects.all()
context = {
"object_list": queryset,
"user": user
}
return render(request, "home.html", context)
home.html:
<html>
<h1>Homepage</h1>
{% if user.is_authenticated %}
<h1>What's on your mind, {{ user }}</h1>
{ % for obj in object_list %}
{{obj.user}}<br/>
{{obj.content}}<br/>
{{obj.timestamp}}<br/>
{% endfor %}
Logout
{% endif %}
</html>
Adding a post for a user
You need to get a user object to pass to your creation method, rather than using the string "test". The reason your attempt is failing is because you are passing the function a string ("test") where it is expecting a user object.
This line gets a user (arbitrarily grabs the first one in your list):
u = User.objects.all()[0]
This line imports the datetime module, which you'll need to generate date and datetime objects for your create method:
import datetime
And this line creates a post for that user:
Post.objects.create(user=u, content="New comment", publish=datetime.date.today(), updated=datetime.datetime.now(), timestamp=datetime.datetime.now())
Normally in request, django automatically add requested user. If that user has related permission to add new Post then following code should work
Post.objects.create(user=request.user, content="New comment")
When you are creating a foreign key, you are referring a model.
suppose there are two models A and B. B has following fields - x, y, z. Now, x field is a foreign key, which is referring model A.
Now whenever you want to create an object of B, then the value of x field should be an object of A. Little bit like this -
post1 = Post(user = an object of User Model, content = "your value")
so create an object of User first. Then write it there. otherwise it will give error.

render multiple template from a single view in django

I want to send context data to one html and want to render different html.
After login user is redirected to this dashboard view. Here I want to render two html file, the context value will be sent to one html let say temp1.html file, but user can see temp2.html file. In temp2.html and other html file, I will include temp1.html file. Is there any way to do so?
views.py
def dashboard(request):
print('in dashboard view')
object = UserSelection.objects.get(user=request.user)
if object.user_type == 'candidate':
val_cand = CandidateDetail.objects.filter(candidate_username=request.user)
if val_cand:
print('Candidate filled data') #Already filled data
data = CandidateDetail.objects.get(candidate_username=request.user)
return render(request, 'dashboard.html',{'obj':object.user_type, 'data':data})
else:
print('new user') #Registered but not filled data
return render(request, 'dashboard.html', {'obj':object.user_type})
else:
val_emp = EmployerDetail.objects.filter(name=request.user)
if val_emp:
print('Employer filled data') #Already filled data
data = EmployerDetail.objects.get(name=request.user)
return render(request, 'dashboard.html',{'obj':object.user_type, 'data':data})
else:
print('new user') #Registered but not filled data
return render(request, 'dashboard.html', {'obj':object.user_type})
You can't render two html file in single view. Please use the Django template language for the desired behaivour.
i.e) If your passing obj to dashboard.html and inside html files can also access obj.
dashboard.html
{{ obj }}
{% include 'test1.html' %}
{% include 'test2.html' %}
You can pass additional context to the template using keyword arguments:
{% include 'test1.html' with obj=obj additional_context='blah' %}
test1.html
{{ obj }}

How to access render_to_response context (data) in template as array object?

I have below code in my view which is sending data to the template as follow -
#page_template("app/Discover.html")
def Discover(request, template="app/Discover.html", extra_context=None):
context = {}
context['to_loc']=loc_both
context['to_av']=av_both
context['to_ql']=ql_both
if extra_context is not None:
context.update(extra_context)
return render_to_response(template, context, context_instance=RequestContext(request))
In my template, I am able to access context items as below -
{% if to_loc %}
js_loc = {{ to_loc|safe }};
{% endif %}
alert('Location is : '+JSON.stringify(js_loc,null,2));
{% if to_av %}
js_av = {{ to_av|safe }};
{% endif %}
alert('AV is : '+JSON.stringify(js_av,null,2));
This way am able to access individual items from context.
But, is there any way I can do something as below -
Assign context object to a javascript array object and this javascript array contains the list of context objects -> which I can access like below -
jsonList = [];
jsonList = contextJSON; // contextJSON holds the context objects that are sent by my view above
print(JSON.stringify(jsonList.to_loc)); // this should give me the data of locations from respective context object
print(JSON.stringify(jsonList.to_av)); // this is for for AV
How to assign entire context object into my javascript object contextJSON in js file as array?
You could just put your context as JSON object into itself:
#page_template("app/Discover.html")
def Discover(request, template="app/Discover.html", extra_context=None):
context = {}
context['to_loc']=loc_both
context['to_av']=av_both
context['to_ql']=ql_both
if extra_context is not None:
context.update(extra_context)
ctx_copy = context.copy()
context['context_json'] = simplejson.dumps(ctx_copy)
return render_to_response(template, context, context_instance=RequestContext(request))
And just render it into your template as JavaScript variable:
jsonList = [];
jsonList = {{ context_json|safe }}; // contextJSON holds the context objects that are sent by my view above
print(JSON.stringify(jsonList.to_loc)); // this should give me the data of locations from respective context object
print(JSON.stringify(jsonList.to_av)); // this is for for AV

How to pass two or more objects from views for render it in template

Im working on Django, i need pass two or more objects to a view, for render it in the template. I mean,
i have one object, and this object can has two or more objects from other model, in the view i have:
def infoUsuario(request,id_usuario):
user = info_productor_cultivador.objects.get(id=id_usuario)
familiar = grupo_familiar.objects.filter(familiar_de_id=user)
ctx = {'usuario':user,'familiar':familiar}
return render_to_response('usuarios.html',ctx,context_instance=RequestContext(request))
in the template:
{% for familiares in familiar %}
<p>{{familiar.primer_nombre}}</p>
{% endfor %}
The models:
class grupo_familiar(models.Model):
familiar_de = models.ForeignKey(info_productor_cultivador)
primer_nombre = models.CharField(max_length=50)
class info_productor_cultivador(models.Model):
primer_nombre = models.CharField(max_length=50)
First, instead "filter" in familiar object i has "get" but said me: "get() returned more than one grupo_familiar -- it returned 2!" looking for a solution i found it that i have to pass the "filter" query, this time i dont have errors from Django, but the "familiar" object does not render it in the template.
In other words, i think that i need is how to pass a foreign key in the view and render it in the template.
Thanks
views
from django.shortcuts import render
def info_usuario(request, id_usuario):
user = info_productor_cultivador.objects.get(id=id_usuario)
familiar = grupo_familiar.objects.filter(familiar_de_id=user)
ctx = { 'usuario': user, 'familiar': familiar }
return render(request, 'usuarios.html', ctx }
template
{% for familiares in familiar %}
<p>{{ familiar.primer_nombre }}</p>
{% endfor %}

How to use the querylist object in Django template

Initially i had this code
(r'^list/fixed/$', list_detail.object_list, fixedList)
In template i use
{% for val in object_list %}
It worked fine as i used Generic list
But now i want to write my own view which does same
object_list = model.objects.all()
return render_to_response('lists.html', object_list)
But its not working.
how can pass the same object list to template as in Generic View
render_to_response() takes a dictionary of variables to use.
return render_to_response('lists.html', {'object_list': object_list})