I can't display extended values of my user model - django

On this case my problem arise displaying extended values of my user model in my index.html
here my models.py
from django.db import models
from django.contrib.auth.models import User
def url(self,filename):
ruta = "MultimediaData/Users/%s/%s"%(self.user.username,filename)
return ruta
class userProfile(models.Model):
user = models.OneToOneField(User)
photo = models.ImageField(upload_to=url)
telefono = models.CharField(max_length=30)
email = models.EmailField(max_length=75)
def __unicode__(self):
return self.user.username
my index.html:
{% extends 'base.html' %}
{% block title %} Inicio - Bienvenidos {% endblock %}
{% block content %}
<p>Dracoin, el portal que facilitará tu vida</p>
{% if user.is_authenticated %}
<p>Bienvenido {{ user.username }}</p>
{% if user.get_profile.photo %}
<img src="/media/{{user.get_profile.photo}}" width="100px" height="100px"/>
{% endif %}
{% if user.get_profile.telefono %}
<p>Numero Tel: {{user.get_profile.telefono}}</p>
{% endif %}
{% endif %}
{% endblock %}
I don't have problem managing that information in my admin panel but i cant view that information in my index. I believe the mistake is in {% if user.get_profile.xxxx %} calling but I cant solve it.
apologizeme in advance if I overlook something.
Thanks!!

get_profile() was deprecated in django 1.5, and removed in django 1.7.
Try {{ user.userprofile.xxxx }} instead.

Related

Django simple search with Class based views and forms.py

I have been trying to do a variation of what Williams Vincent did on this page: https://learndjango.com/tutorials/django-search-tutorial .
I am using Django 3.2 so if there are modifications, I need to make I have not identified them. I am having some troubles.
This what I made which worked just fine.
my_search.html:
{% extends "base.html" %}
{% block body %}
{% for city in object_list %}
<li>
{{city.name}}   {{city.city_no}}
</li>
{% endfor %}
{% endblock %}
views.py:
from django.views.generic import ListView
from .models import City
class SearchResutlsView(ListView): # test version
model = City
template_name = "search_results.html"
def get_queryset(self):
return City.objects.filter(name__icontains='Boston')
Now it is time to add forms.py, but when I made the below changes to the code it does not work. What am I missing? There are no errors displayed. I get a blank html.
{% extends "base.html" %}
{% block body %}
<form class="d-flex" method='get' action="{% url 'city:search_results' %}">
{{ form }}
<button class="btn btn-outline-success" type="submit" value="qu">Search Name</button>
</form>
{% for city in city_list %}
<li>
{{city.name}}   {{city.city_no}}
</li>
{% endfor %}
{% endblock %}
forms.py
from django import forms
class SearchForm(forms.Form):
q = forms.CharField(label='Search label', max_length=50, strip=True)
views.py
from django.views.generic import FormView, ListView
from .models import City
class SearchResutlsView(FormView):
model = City
form_class = SearchForm
template_name = "city/search_results.html"
def get_queryset(self):
query = self.request.Get.get("q")
if query:
city_list = City.objects.filter(name__icontains=query)
else:
city_list = City.objects.none()
return city_list
First, Your method should be POST not get.
Second, you need to add CSRF token.
something like that:
{% extends "base.html" %}
{% block body %}
<form class="d-flex" method='post' action="{% url 'city:search_results' %}">
{% csrf_token %}
{{ form }}
<button class="btn btn-outline-success" type="submit" value="qu">Search Name</button>
</form>
{% for city in city_list %}
<li>
{{city.name}}   {{city.city_no}}
</li>
{% endfor %}
{% endblock %}
and in views.py
query = self.request.POST.get("q")

Django - how to get all the users in team when using a costumised user model

I am new to django and have a question: I created a CustomUser model within a users app.
I tried
from users.models import CustomUser, Team
team1= Team.objects.first()
users_team1= team1.user.objects.all()
and it doesnt get me the list of users in this Team
class CustomUser(AbstractUser):
bio= models.CharField(max_length=300, null= True, blank=True)
class Team (models.Model):
title = models.CharField(max_length=200)
user= models.ManyToManyField(get_user_model())
date_created= models.DateTimeField(auto_now_add=True, blank=True, null=True)
date_updated= models.DateTimeField(auto_now=True,blank=True, null=True )
def __str__(self):
return self.title
def get_absolute_url(self): # new
return reverse('team_detail', args=[str(self.pk)])
I want created a HTML page
{% extends '_base.html' %}
{% block title %}{{ object.title }}{% endblock title %}
{% block content %}
<div class="team-detail">
<h2>{{ team.title }}</h2>
<p>Team tile : {{ team.title }}</p>
<p>user: {{ team.user }}</p>
</div>
{% endblock content %}
how can i show all the users in a specific Team?
Thanks in advance.
You should do:
from users.models import CustomUser, Team
team1= Team.objects.first()
# lets pass team1 to your template
return render(request, 'template/name.html', {'team': team1})
Your template should be sthg like:
{% extends '_base.html' %}
{% block title %}{{ object.title }}{% endblock title %}
{% block content %}
<div class="team-detail">
<h2>{{ team.title }}</h2>
<p>Team tile : {{ team.title }}</p>
{% for user in team.user.all %}
<p>user: {{ user }}</p>
{% endfor %}
</div>
{% endblock content %}

Conditions in IF Statements requires values to be specified explicitly

I have created a template that displays items from a loop, Within the loop there is a condition, but the condition does not work unless specified explicitly.
{% extends 'blog/base.html' %}
{% block content %}
<h3>{{ user.username }}</h3>
{% for project in projects %}
{% if user.username == 'testuser' %}
<h5>{{ project.title }}</h5>
<p>{{ project.description }}</p>
<p>{{ project.objectives }}</p>
<pre>{{ project.score }}</pre>
<pre>{{ project.student_id }}</pre>
{% endif %}
{% endfor %}
{% endblock content %}
The above code works perfectly and returns the records assigned to the user named testuser.
But if I write the code as below, it skips all records
{% extends 'blog/base.html' %}
{% block content %}
<h3>{{ user.username }}</h3>
{% for project in projects %}
{% if user.username == project.student_id %}
<h5>{{ project.title }}</h5>
<p>{{ project.description }}</p>
<p>{{ project.objectives }}</p>
<pre>{{ project.score }}</pre>
<pre>{{ project.student_id }}</pre>
{% endif %}
{% endfor %}
{% endblock content %}
I have added the code from the model
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Projects(models.Model):
title = models.CharField(max_length=150)
description = models.TextField()
objectives = models.TextField()
score = models.IntegerField()
#file = models.FileField()
date_posted = models.DateTimeField(default=timezone.now)
student_id = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
The student_id is a User object, not a string, so here you are comparing a string (the username) with a User object, and a User with username 'testuser', is not the same as a string 'testuser'.
The most elegant solution is probably to compare the user with the user, so:
{% if user == project.student_id %}
So we omit the .username, and compare a User object with a User object.
Note: enumeration (especially in a template, but also in the Django layer itself), is not efficient, you should make a query that
does the filtering for you.
You can filter a queryset with:
user_projects = Project.objects.filter(student_id=request.user)
in your view to obtain only projects for which the logged in user is
the student.
Note: A ForeignKey usually does not have an _id suffix. Django will automatically add an extra field named fieldname_id that
stores the primary key to which the foreign key refers. After all, a
ForeignKey in Django will lazy load the related object.

Django: How to show all images in images model

I am trying to show all images associated with the currently selected user
This is built off of this solved question: django upload to image model with foreign key to user
Model.py
class Images(models.Model):
image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png')
user = models.ForeignKey(User, on_delete=models.CASCADE)
Views.py
#login_required
def index_account(request):
args = {'user': request.user }
return render(request, 've/cp/index_account.html', args)
Template > index_account.html
<p>Edit your images</p>
# test to see if it worked w/o if
{{ user.images.image}}
# ideal solution
{% if user.images.images %}
{% for img in user.images %}
<img src="{{ user.images.image.url }}"><br>
{% endfor %}
{% else %}
<p>No images</p>
{% endif %}
<br>
<hr>
The code you have provided is not going to work for what you want. So here is an example of something that probably will:
Example
views.py
from app_name.models import Images
#login_required
def index_account(request):
images = Images.objects.filter(user=request.user)
return render(request, 've/cp/index_account.html', {"images": images})
index_account.html
<p>Edit your images</p>
# ideal solution
{% if images %}
{% for img in images %}
<img src="{{ img.url }}"><br>
{% endfor %}
{% else %}
<p>No images</p>
{% endif %}
<br>
<hr>
Hope this helps!

Django Reverse Query in Template

I have models like this
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def __unicode__(self):
return self.name
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
I want to list all blogs in a page. I have written a view such that
def listAllBlogs(request):
blogs= Blog.objects.all()
return object_list(
request,
blogs,
template_object_name = "blog",
allow_empty = True,
)
And I can display tagline of blog such that in view
{% extends "base.html" %}
{% block title %}{% endblock %}
{% block extrahead %}
{% endblock %}
{% block content %}
{% for blog in blog_list %}
{{ blog.tagline }}
{% endfor %}
{% endblock %}
But I would like to show, such thing blog__entry__name but I don't know how can I achive this in template.
Also, there may be no entry in a blog. How can I detect in template ?
Thanks
To access blog entries (Related Manager): blog.entry_set.all
To do other actions if blog have no entries, you have the {% empty %} tag that is executed when the set is empty.
{% block content %}
{% for blog in blog_list %}
{{ blog.tagline }}
{% for entry in blog.entry_set.all %}
{{entry.name}}
{% empty %}
<!-- no entries -->
{% endfor %}
{% endfor %}
{% endblock %}
based on your code you could do the following.
{% block content %}
{% for blog in blog_list %}
{{ blog.tagline }}
{% for entry in blog.entry_set.all %}
{{entry.name}}
{% endfor %}
{% endfor %}
{% endblock %}