Default image didn't change Django - django

I try to make avatar upload in Django project. I made changes in templates and in models, but the default image does not change to a new one. What could be the problem?
model.py
class Person(models.Model):
avatar = models.ImageField(upload_to="img", null=True, blank=True)
template.html
{% if person.avatar.url %}
<th scope="row"><img height="50" width="50" src="{{ person.avatar.url }}"
alt="no image" title="avatar">
{% else %}
<th scope="row"><img height="50" width="50" src="{% static "img/default_avatar.jpg" %}"
alt="no image" title="avatar">
{% endif %}

Giving a default image is easier. You don't need to write an if statement every time using an avatar pic anymore
models.py:
class Person(models.Model):
avatar = models.ImageField(default="img/default.png", upload_to="img", null=True, blank=True)
template.html:
<th scope="row><img height="50" width="50" src="{{ person.avatar.url }}" alt="no image" title="avatar">

Try
{% if person.avatar %}
<th scope="row"><img height="50" width="50" src="{{ person.avatar.url }}"
alt="no image" title="avatar">
{% else %}
<th scope="row"><img height="50" width="50" src="{% static "img/default_avatar.jpg" %}"
alt="no image" title="avatar">
{% endif %}

Related

How can i display count of each column in django

Display
I would like to count the number of students for each subjects but currently it only displays the number of students for one subject. it only counts the number of student for one subject but i would like to count the number of students in each subject
Added the models.py. Ps still new to django
views.py
class SubjectView(TemplateView):
template_name='subjects.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
username=self.request.user.id
#filter subject taught by lecturer
classdets=ClassDetail.objects.all().filter(teacher=username).values_list('subject_id')
print(classdets)
#filters all subjects from the class details
subj=Subject.objects.filter(id__in=classdets)
print(subj)
#counts number of students
subjID=Subject.objects.values('id')
num_student=ClassDetail.objects.filter(id__in=subjID).count
print(num_student)
context['subjects'] = subj
context['no_students'] = num_student
return context
template
{% extends "base.html" %}
{% load static %}
{% block title %}Subjects{% endblock title %}
{% block sidenavbar %}
{% include 'partials/sidenavbar.html' %}
{% endblock %}
{% block navbar %}
{% include 'partials/navbar.html' %}
{% endblock %}
{% block subject %}
<div class="container-fluid">
<div class="col">
<div class="card bg-transparent">
<!-- Card header -->
<div>
<div class="card-header bg-transparent border-0">
<h3 class="mb-0" style="text-transform: uppercase">Current Subjects</h3>
{% comment %} View Students {% endcomment %}
</div>
</div>
<!-- Translucent table -->
<div class="table-responsive">
<table class="table align-items-center table-flush" id="datatable-buttons">
<thead class="thead-light">
<tr>
<th>Subject Name</th>
<th>Subject Code</th>
<th>Number of Students</th>
{% comment %} <th>Generate Attendance Code</th> {% endcomment %}
</tr>
</thead>
{% if user.is_authenticated %}
{% for subject in subjects %}
<tbody class="list" style="text-transform: capitalize">
<tr>
<th scope="row">
<div class="media align-items-center">
<a href="#" class="avatar rounded-circle mr-3">
{% if subject.thumbnail %}
<img alt="Logo" src="{{subject.thumbnail.url}}" />
{% endif %}
</a>
<div class="media-body">
<span class="name mb-0 text-sm">{{subject}}</span>
</div>
</div>
</th>
<td class="budget">{{subject.code}}</td>
<td>
<div class="d-flex align-items-center">
<span class="completion mr-2">{{no_students}}</span>
</div>
</td>
<td>
{% comment %}
<div class="d-flex align-items-center">
<span class="completion mr-2">{{attendace_code}}</span>
</div>
{% endcomment %}
</td>
</tr>
</tbody>
{% endfor %}
{% endif %}
</table>
</div>
</div>
</div>
</div>
{% endblock %}
models
def get_thumbnail(instance, filename):
path = f"static/assets/img/custom/{filename}"
return path
class Subject(models.Model):
code=models.CharField(max_length=8,unique=True,default="")
name=models.CharField(max_length=100,unique=True)
thumbnail=models.ImageField(blank=True,null=True,upload_to=get_thumbnail)
def __str__(self):
return f'{self.name}'
class Meta:
unique_together = ('name', 'code')
class ClassDetail(models.Model):
teacher=models.ForeignKey(UserProfile,on_delete=models.PROTECT)
subject=models.ForeignKey(Subject, on_delete=models.PROTECT, default="")
student=models.ManyToManyField(UserProfile,related_name="student")
def __str__(self):
return f'{self.subject}'
class Meta:
unique_together = ('teacher', 'subject')
userprofile
class UserProfile(AbstractUser):
ROLE_LECTURER = 'lecturer'
ROLE_STUDENT = 'student'
ROLE_ADMIN = 'admin'
ROLE_CHOICES = (
(ROLE_LECTURER, _('Lecturer')),
(ROLE_STUDENT, _('Student')),
(ROLE_ADMIN, _('Admin')),
)
STATUS_ACTIVE = 'active'
STATUS_INACTIVE = 'inactive'
STATUS_SUSPENDED = 'suspended'
STATUS_EXPIRED = 'expired'
STATUS_CHOICES = (
(STATUS_ACTIVE, _('Active')),
(STATUS_INACTIVE, _('Inactive')),
(STATUS_SUSPENDED, _('Suspended')),
(STATUS_EXPIRED, _("Expired")),
)
username = models.CharField(max_length=11, unique=True, verbose_name="Relevant ID")
status = models.CharField(_('status'), max_length=50, choices=STATUS_CHOICES, default=STATUS_ACTIVE)
role = models.CharField(_('role'), max_length=50, choices=ROLE_CHOICES, default="")
def __str__(self):
return f'{self.username} ({self.first_name})'
USERNAME_FIELD = 'username'
num_student =subjID.classdetail_set.all().count()
print(num_student)

ValueError at / The 'pic' attribute has no file associated with it

I have a simple model with pic field having null and blank
class PostForNewsFeed(models.Model):
title = models.CharField(max_length=100, blank=True)
description = models.CharField(max_length=255, blank=True)
slug = models.SlugField(unique=True, max_length=100, blank=True)
pic = models.ImageField(upload_to='path/to/img', null=True, blank=True, default='')
{% if post.pic.url %}
<a href="{% url 'post-detail' post.id %}"
><img class="card-img-top" src="{{ post.pic.url }}" alt=""
/></a>
{% endif %}
When I submit without a pic I am getting the pic attribute not associated with a file.
My code seems fine in the template.
You should check if post.pic, not if post.pic.url:
{% if post.pic %}
<img class="card-img-top" src="{{ post.pic.url }}" alt=""/>
{% endif %}
Based on the discussion, in your template you use post.pic.url a lot of times when you work with template tags, etc. For example:
{% post_to_facebook post.pic.url "Post to Facebook" %}
you will need to make these conditional, since you can not fetch the .url of a post.pic if that post.pic is non existing.
You thus need to wrap this in an {% if … %} condition:
{% if post.pic %}
{% post_to_facebook post.pic.url "Post to Facebook" %}
{% endif %}

Django Default Image is showing

why i can't see default image here below are my model and profile.html file:
Model:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
image = models.ImageField(upload_to='profile_pics',default='default.jpg')
def __str__(self):
return f'{self.user.username} Profile'
Profile.html:
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{user.email}}</p>
</div>
</div>
<!-- FORM HERE -->
</div>
{% endblock content %}
Thank you in advance...
in templates you can check the image exists or not, if not can show a default image from static file as follows
{% if user.profile.image %}
<img src="{{ user.profile.image.url }}">
{% else %}
<img src="{% static 'img/default.png' %}">
{% endif %}

How can I print all the products attributes in product.html

This is my models.py
class Product(models.Model):
title = models.CharField(max_length=50)
description = models.TextField(blank=True, null=True)
price = models.FloatField()
summary = models.TextField(blank=False, null=False)
image = models.ImageField(blank=True, null=True)
This is my Django views.py
def products_view(request,*args, **kwargs):
print(Product.objects.values())
myDict = list()
for product in Product.objects.all():
my_product = {
"product_id": product.id,
"product_title":product.title,
"product_description":product.description,
"product_price":product.price,
"product_summary":product.summary,
"product_image":product.image
}
print(my_product)
return render(request, "products.html", my_product)
This my products.html
{% extends 'base.html' %}
{% block content %}
<h1>Products Page</h1>
<ul>
{% for product in my_product %}
<div class="card" style="width: 18rem;">
<img src="{{ product_image }}" class="card-img-top" alt="{{ product_id }}">
<div class="card-body">
<h5 class="card-title">{{ product_title }}</h5>
<p class="card-text">{{ product_description }}</p>
Add to Basket
</div>
</div>
{% endfor %}
</ul>
{% endblock %}
My Product.html page only show the "h1" tag, do not show the Products attributes. How can I achieve this problem?
Products.objects.all() gives me QuerySet and I tried to change into dict. but I cannot print the dict elements' attributes .
Your view should send products through context
def products_view(request,*args, **kwargs):
products = Product.objects.all()
context = {'products': products }
return render(request, "products.html", context)
also in template then you can use
{% for product in products %}
<div class="card" style="width: 18rem;">
<img src="{{ product.image.url}}" class="card-img-top" alt="{{ product.id}}">
<div class="card-body">
<h5 class="card-title">{{ product.title}}</h5>
<p class="card-text">{{ product.description}}</p>
Add to Basket
</div>
</div>
{% endfor %}
Drop the loop in your view function and try something like this below. There is no need to loop through each object in the view - your query has retrieved everything, and it's available to your template when you pass it through as context. Use the template language to access each object's attribute.
def products_view(request,*args, **kwargs):
products = Product.objects.all()
return render(request, "products.html", products)
And in your HTML, do something like:
{% for product in products %}
{{product.title}}
{{product.description}}
{{product.price}}
{{product.summary}}
{{product.image}}
{% endfor %}
This HTML will render weird in my example, but you can see what's going on.
The reason the for loop doesn't print out correctly is because my_product is not an iterable so the template cannot loop over it.
You will need to change this to be an iterable - like a list or queryset.
def products_view(request,*args, **kwargs):
print(Product.objects.values())
my_product = Product.objects.all()
print(my_product)
return render(request, "products.html", {'my_product': my_product})
Now, in the template, you will be able to access the product attributes using dot notation.
{% for product in my_product %}
<div class="card" style="width: 18rem;">
<img src="{{ product.image }}" class="card-img-top" alt="{{ product.id }}">
<div class="card-body">
<h5 class="card-title">{{ product.title }}</h5>
<p class="card-text">{{ product.description }}</p>
Add to Basket
</div>
</div>
{% endfor %}

Django admintemplates

I have a form which is like:
class Address_info_updateForm(forms.Form):
street = forms.CharField(label=_("Street"), required=True)
street2 = forms.CharField(label=_("Additional Address"), required=False, max_length=50)
zip = forms.CharField(label=_("Postcode"), required=True, max_length=50)
city = forms.CharField(label=_("City"), required=True, max_length=50)
state = forms.CharField(label=_("State"), required=False, max_length=50)
country = forms.ChoiceField(label=_("Country"), choices=countries, widget=forms.Select, required=True)
Now I have rendered to template which is like:
{% extends "base/base_page.html" %}
{% load i18n %}
{% load static %}
{% block html_title %}
{% trans "Update Profile" %}
{% endblock %}
{% block html_page_left_content %}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="stepcarousel.js">
stepcarousel.setup({
galleryid: 'mygallery2', //id of carousel DIV
beltclass: 'belt2', //class of inner "belt" DIV containing all the panel DIVs
panelclass: 'panel2', //class of panel DIVs each holding content
autostep: {enable:true, moveby:1, pause:3000},
panelbehavior: {speed:500, wraparound:false, wrapbehavior:'slide', persist:true},
defaultbuttons: {enable: true, moveby: 1, leftnav: ['{{ STATIC_PREFIX }}images/home/bigarrowleft.png', 5, 168], rightnav: ['{{ STATIC_PREFIX }}images/home/bigarrowright.png', -47, 163]},
statusvars: ['statusA', 'statusB', 'statusC'], //register 3 variables that contain current panel (start), current panel (last), and total panels
contenttype: ['inline'] //content setting ['inline'] or ['ajax', 'path_to_external_file']
})
</script>
<div style="height: 400px">
<div>
<p class="title">{% trans "BILLING ADDRESS" %}</p>
</div>
<form action="" method="POST" class="custom_form">{% csrf_token %}
<table style="color:black;text-align:left; margin-left: 20px;">
{% if form.errors %}
<span style="color:red;">{% trans "You have not filled in the form correctly. Please correct the errors"%}:</span>
{% endif %}
{% for field in form %}
{% if not field.is_hidden %}
<tr>
<td>
{{field.label}}
{% if field.field.required %}
<span style="color:red;">*</span>
{%endif%}
</td>
</tr>
{%else%}
{{field}}{{field.errors}}
{%endif%}
{% endfor %}
<tr>
<td colspan="2">
<input type="submit" value="{% trans "UPDATE" %}">
<input type="button" value="{% trans "CANCEL" %}" onclick="document.location.href='{{base_url}}MyProfile/'" class="custom_button">
</td>
</tr>
</table>
</form>
<script>
jQuery('select#id_country').wrap('<div class="select_div" />');
</script>
</div>
{% endblock %}
{% block html_page_right_sidebar_login %}
{% endblock %}
the problem is when i use {{form.as_table}} i see my textboxes along with my form fields in very descent manner.
But when i am using the stepcruousel to display the errors and * marked fields it is NOT SHOWING ME THE TEXTBOXES and it is only showing me the fields with aestrics * like this
Street * and so on
I want the fields to be aestrix along with the texboxes also.
Thanks in advance
To show the field label & textbox you are using:
{{field.label}}
{% if field.field.required %}
<span style="color:red;">*</span>
{%endif%}
but this will show only label {{field.label}} but not textbox because there is no {{ field }} which is the widget translated to html of the field (in your case its the text box). Add it:
{{field.label}}
{% if field.field.required %}
<span style="color:red;">*</span>
{%endif%}
{{ field }}