I have a get_context_data in my view
def get_context_data(self, **kwargs):
context = super(MyView,self).get_context_data(**kwargs)
humans = Human.objects.all()
context['humans'] = [{'fname': i.first_name, 'lname':i.last_name} for i in humans]
return context
When I have this:
{% for human in humans %}
<tr>
<td>{{human.fname}} {{human.lname}}</td>
</tr>
{% endfor %}
It works fine. I get
John Doe
Michael Smith
etc...
but, when I've tried put this values to angulary by:
{%verbatim%}
...
<button ng-controller="MyCtrl" type="submit" ng-click="
{%endverbatim%}
myFunc({{human.fname}},{{human.lname}})
{%verbatim%}">
Send
</button>
...
{%endverbatim%}
I've got only undefined:
#in my controller:
#...
$scope.myFunc = function(fname, lname){
$log.log(fname, lname); // <- this returns 2x undefined
}
Guys, any ideas?
The Django verbatim looks like this:
{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}
https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#verbatim
You have the {% endverbatim %} tag before {% verbatim %} in your snippet.
<button ng-controller="MyCtrl" type="submit" ng-click="
{%endverbatim%}
myFunc({{human.fname}},{{human.lname}})
{%verbatim%}">
Send
</button>
I've solved it
myFunc("{{human.fname}}","{{human.lname}}")
instead
myFunc({{human.fname}},{{human.lname}})
Related
I'm about to finish a Django based project, and the last step of this project is to build a followers/following feature. I can unfollow someone I've followed manually from the admin, but I can't follow someone from my html view. It misses me just one tiny thing to add into my html code but I'm really stuck. My code
My Model:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
CREATOR = "CREATOR"
SUBSCRIBER = "SUBSCRIBER"
ROLE_CHOICES = (
(CREATOR, "Créateur"),
(SUBSCRIBER, "Abonné"),
)
profile_photo = models.ImageField(upload_to='profile_photos/', default='profile_photos/default.png', blank=True, null=True)
role = models.CharField(max_length=10, choices=ROLE_CHOICES, default=SUBSCRIBER)
follows = models.ManyToManyField('self', related_name='followers', symmetrical=False)
My Views:
#login_required
def abonnements(request):
user = request.user
followers = user.followers.all()
follows = user.follows.all()
if request.method == 'POST':
if request.POST.get('follow'):
if request.POST.get('follow') == user.username:
return render(request, 'blog/abonnements.html', {'followers': followers, 'follows': follows, "error": "You can't follow yourself!"})
try:
followed_user = User.objects.get(request.POST.get('follow'))
except User.DoesNotExist:
return render(request, 'blog/abonnements.html', {'followers': followers, 'follows': follows, "error": "User does not exist"})
else:
print(followed_user)
elif request.POST.get('unfollow'):
user.follows.remove(User.objects.get(pk=request.POST.get('unfollow')))
return render(request, 'blog/abonnements.html', {'followers': followers, 'follows': follows, "success": "You are no longer following " + request.POST.get('unfollow')})
return render(request, 'blog/abonnements.html', {'followers': followers, 'follows': follows})
My HTML
{% extends 'base.html' %}
<title>{% block title %}Abonnements{% endblock %}</title>
{% block content %} {% include 'partials/_navbar.html' %}
<main class="corps_abonnements">
<section class="suivre">
<p class="suivre_utilisateurs_titre">Suivre d'autres utilisateurs</p>
<form method="post">
{% csrf_token %}
<input type="text" name="follow" value="">
<input type="submit" value="Envoyer">
</form>
</section>
<section class="abonnements">
<p color="red">{{ error }}</p>
{% if success %}<p color="green">{{ success }}</p>{% endif %}
<p class="abonnements_titre">Abonnements</p>
{% for user in follows %}
<div class="utilisateur_desabonner_container">
<p class="nom_utilisateur_desabonner">{{ user.username }}</p>
<form method="post">
{% csrf_token %}
{% if user in follows %}
<input type="hidden" name="unfollow" value="{{ user.id }}">
<button style="background-color:red;" type="submit" class="creer_critique_demande">
Se désabonner
</button>
{% endif %}
</form>
</div>
{% endfor %}
</section>
<section class="abonnes">
<p class="abonnes_titre">Abonnés</p>
{% for user in followers %}
<div class="utilisateur_abonne_container">
<p class="nom_utilisateur_abonne">{{ user.username }}</p>
</div>
{% endfor %}
</section>
</main>
{% endblock %}
So when I put the connected user name in the input, it returns me the error "you can't follow yourself", it means that my code is good
the message
but If I try to put the username of another user I want to follow, it raises me an error. Can someone help me please ?
ValueError at /abonnements/
too many values to unpack (expected 2)
Request Method: POST
Request URL: http://127.0.0.1:8000/abonnements/
views.py, line 155, in abonnements
followed_user = User.objects.get(request.POST.get('follow'))
I need to do one page with topic and all entries about this topic. And for each entries I need all comments shown up below each entry. Comments should be for exact entry. Cant find it solution and decided ask. Thank you.
models.py
--snip--
class Comment(models.Model):
date_added = models.DateTimeField(auto_now_add=True)
text = models.TextField()
owner = models.ForeignKey(User, on_delete=models.CASCADE)
entry = models.ForeignKey(Entry, on_delete=models.CASCADE)
def __str__(self):
return f"{self.text[:50]}..."
views.py
--snip--
def topic(request, topic_id):
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.all()
comments = []
for entry in entries:
c = entry.comment_set.all()
comments.append(c)
context = {'topic': topic, 'entries': entries,
'comments': comments}
return render(request, 'learning_logs/topic.html'
,context)
topic.html
{% extends 'learning_logs/base.html' %}
{% block content %}
<p>{{ topic.title }}</p>
<p>{{ topic.description }}</p><br>
<p>Entries:</p><br>
<ul>
{% for entry in entries %}
<li>{{ entry.text }}</li>
<ul>
<p>Comments:</p>
{% for comment in comments %}
<li>{{ comment.text }}</li>
{% endfor %}<br>
</ul>
{% empty %}
<li>Not entries</li>
{% endfor %}
</ul>
{% endblock content %}
You can do this with just topic. No need to get entries and comments:
{% extends 'learning_logs/base.html' %}
{% block content %}
<p>{{ topic.title }}</p>
<p>{{ topic.description }}</p><br>
<p>Entries:</p><br>
<ul>
{% for entry in topic.entry_set.all %}
<li>{{ entry.text }}</li>
<ul>
<p>Comments:</p>
{% for comment in entry.comment_set.all %}
<li>{{ comment.text }}</li>
{% endfor %}<br>
</ul>
{% empty %}
<li>Not entries</li>
{% endfor %}
</ul>
{% endblock content %}
You will also want to optimise the query using prefetch_related so you don't hit the db per entry per comment:
topic = Topic.objects.prefetch_related('entry_set__comment_set').get(id=topic_id))
context = {'topic': topic}
return render(request, 'learning_logs/topic.html', context)
Get all the employee profile table id and check the id with employee process,if id matches show edit button in templates else show assign button.
Views.py
def Employee(request):
emp = Emp_Profile.objects.filter(is_active=True)
emptable = Emp_Profile.objects.values_list('id')
print(emptable)
empprocess = Emp_Process.objects.values_list('username_id').distinct()
print(empprocess)
obj = {}
for i in range(len(empprocess)):
obj[i] = empprocess[i]
return render(request, 'employee.html',{'list' : emp,'empprocess':empprocess,'obj':obj})
templates
{% for list in list %}
{% if obj != list.id %}
<td>
<a href="/view_client_process/{{ list.id }}"><button
class="btn btn-info">Edit</button></a>
</td>
{% else %}
<h6>welcome</h6>
<td>
<a href="/view_client_process/{{ list.id }}"><button
class="btn btn-info">Assign</button></a>
</td>
{% endif %}
{% endfor %}
You can construct a set of username_ids and pass this to your template:
def Employee(request):
empS = Emp_Profile.objects.filter(is_active=True)
empprocess = set(Emp_Process.objects.values_list('username_id', flat=True).distinct())
return render(request, 'employee.html', {'emps' : emps, 'empprocess': empprocess })
In the template, we can then make a membership check of the set:
{% for emp in emps %}
<td>
{% if emp.id not in empprocess %}
<button class="btn btn-info">Edit</button>
{% else %}
<button class="btn btn-info">Assign</button>
{% endif %}
</td>
{% endfor %}
Note: you might want to rename your field username to user since a ForeignKey to a user is not the same as a username.
Note: please use {% url ... %} template tags [Django-doc] instead of performing URL processing yourself.
I need to create a 100-cell table, and in each cell if the corresponding entity exists, display it's information, otherwise, display "Empty". How do I do that? The python program (Item has properties of "seqNumber" and "name"):
query = db.Query(Item)
items = query.fetch(100)
render(..., {'range100':range(100), 'items':items}, ...)
HTML:
<table>
<tr>
{% for i in range100 %} <!-- for item in items (how?) -->
<td>
{% if item.seqNumber == forloop.counter (how?) %}
{{item.name}}
{% else %}
Empty
{% endif %}
{% endfor %}
</tr>
</table>
query = db.Query(Item)
items = query.fetch(100)
l = []
for i in enumerate(range(99)):
try:
l.append((i,items[i].name))
except:
l.append((i,None))
render(stuff = l)
This is all untested and the try/except is no doubt not ideal, just easier to write code then in a comment to give you the general idea of how I'd approach this.
<table>
<tr>
{% for i in stuff %}
<td>
{{ i.0 }}<!-- ID -->
{% if i.1 %}
{{ i.1 }}<!-- value -->
{% else %}<!-- if the value is none -->
"VALUE NEEDED"
{% endif %}
{% endfor %}
</tr>
</table>
Ok I have a base.html and I try to use that for my header menu and footer. In my other template I loop over items and display them on the page. My problem is the the other template is repeating my base.html like it's in the loop. I hope someone can show me the error in My ways.
Here is my base.html code:
<div class="menu">
<ul class="nav">
<li>Home</li>
<li>New Entry</li>
<li>Sign-up</li>
{% if user %}
<li>{{user.name}}</li>
<li>Log-Out</li>
{% else %}
<li>Log-In</li>
{% endif %}
</ul>
This is in the base.html also but didn't paste correctly.
<div id="content">
{% block content %}
{% endblock %}
</div>
And here is the sub template code:
{% extends "base.html" %}
{% block content %}
{% for p in posts %}
{{ p.render() | safe }}
<br><br>
{% endfor %}
<div>
{{text}}
</div>
{% endblock %}
Please help
Edit:
edit2: removed link and found my problem I was calling the wrong html file in render()
Be kind Newbie here
Looks ok. Are you sure you don't have a loop in the python code that renders the template?