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 %}
Related
I am a student who wants to be good at Django. The button does not work. If you press the button in detail.html, I want to save the product in DB as if I purchased it. My goal is to get the buyer, date, and product code as written on views.py. However, even if you press the button now, you can't save it in DB. What's the problem?
model.py
class Join(models.Model):
join_code = models.AutoField(primary_key=True)
username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username')
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
part_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.join_code)
class Meta:
ordering = ['join_code']
Join/views
from datetime import timezone
from django.shortcuts import render
from zeronine.models import *
def join_detail(request):
product = Product.objects.all()
if request.method == "POST":
join = Join()
join.product_code = product
join.username = request.user
join.part_date = timezone.now()
join.save()
return render(request, 'zeronine/detail.html', {'product': product})
detail.html
{% extends 'base.html' %}
{% block title %} 상품 상세보기 {% endblock %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-4">
<img src="{{product.image.url}}" width="190%" style="margin-top: 35px;">
</div>
<div class="text-center col" style="margin-top:150px; margin-left:200px;">
<b><h4 class="content" style="margin-bottom: -5px;"><b>{{product.name}}</b></h4></b>
<br>
<div>
<!-- <span>주최자 : <b>{{ product.username }}</b></span><br>-->
<span style="color: #111111">모집기간 : <b>{{ product.start_date }} ~ {{ product.due_date }}</b></span>
</div>
<hr style="margin-top: 30px; margin-bottom: 30px;">
<p><span class="badge badge-dark">가격</span>
{% load humanize %}
{% for designated in designated_object %}
{% if designated.product_code.product_code == product.product_code %}
{{designated.price | floatformat:'0' | intcomma }}원
{% endif %}
{% endfor %}</p>
<span class="badge badge-dark">목표금액</span> {{ product.target_price | floatformat:'0' | intcomma }}원 <br><br>
<p class="badge badge-dark">공동구매 취지
{{product.benefit|linebreaks}}</p>
<p class="badge badge-dark">상세설명
{{product.detail|linebreaks}}</p>
<br>
<form action="" method="post">
{% csrf_token %}
<a onclick="alert('{{ product.name }} 공동구매 참여가 완료되었습니다.');" style="cursor:pointer;">
<form method="POST" action ="{% url 'zeronine:join_detail' %}">
{% csrf_token %}
<div class="form-group">
<button type="submit" action="{% url 'zeronine:join_detail' %}" class="btn btn-primary" style="float: right; background: #637B46; border: white">업로드</button>
</div>
</form>
</a>
</form>
</div>
</div>
</div>
{% endblock %}
I am not sure but you have a form inside a form in your template. maybe that is causing the problem.
also
in the POST section. it is best practice to use
join = Join.objects.create(product_code=product, ....)```
I am following a django tutorial series, the music website contains the ListView which contains Albums(this is showing) but the DetailView Containing the list of songs in each Album is not showing.
I have tried changing the iteration name in the for loop but it still not working, the list shows when i am not using the generic method i.e using index and detail function instead of the IndexView and DetailView classes.
MY music.views Code
class IndexView(generic.ListView):
template_name='music/index.html'
def get_queryset(self):
return Albums.objects.all()
class DetailView(generic.DetailView):
model = Albums
template_name = 'music/detail.html'
My detail.html code which is supposed to show the list of songs but not working
{% extends 'music/base.html' %}
{% block title %} Album Details {% endblock %}
{% block body %}
<img src ="{{ all_album.alb_logo }}">
<h1>{{ all_album.alb_title }}</h1>
<ul>
{% for song in all_album.song_set.all %}
<li>{{ song.song_title }} </li>
{% endfor %}
</ul>
<br>
{% endblock %}
My index.html which shows the list of albums, this is working
{% extends 'music/base.html' %}
{% block body %}
<h2>List of Current albums available</h2>
<div class='container-fluid'>
<div class='row'>
{% for album in object_list %}
<div class='col-lg-4'>
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="{{ album.alb_logo }}" >
<div class="card-body">
<h5 class="card-title">{{ album.alb_title }}</h5>
<p class="card-text">{{ album.alb_artist }}</p>
<a href="{% url 'music:detail' album.id %}" class="btn
btn-primary btn-sm">View details</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
My urls.py code#
urlpatterns = [
path('',views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
]
The detail.html page is expected to show the list of songs in a selected album that is already in the database when clicked, but it is not showing.
You were using the wrong context variable name(all_album) inside the template, it should be object.
#detail.html
{% extends 'music/base.html' %}
{% block title %} Album Details {% endblock %}
{% block body %}
<img src="{{ object.alb_logo }}">
<h1>{{ object.alb_title }}</h1>
<ul>
{% for song in object.song_set.all %}
<li>{{ song.song_title }} </li>
{% endfor %}
</ul>
<br>
{% endblock %}
Reference: DetailView get_context_data() method--Django Doc
I have installed sorl.thumbnail and added it to my installed_apps.
In my view:
{% extends 'base.html' %}
{%block title%}{{user.get_full_name}}{% endblock %}
{%block content%}
{%load thumbnail %}
<h1>{{user.get_full_name}}</h1>
<div class="profile-info">
{% thumbnail user.profile.photo "180x180" crop="100%" as im %}
<img src="{{im.url}}" class="user-detail">
{% endthumbnail %}
</div>
{% with total_followers=user.followers.count %}
<span class="count">
{{total_followers}}
</span>
follower{{total_followers|pluralize}}
<a href="#" data-id="user.id" data-action="{%if request.user in user.followers.all %}un{%endif%}follow" class="follow button">
{%if request.user not in user.followers.all %}Follow{%else%}Unfollow{%endif%}
</a>
<div id="image-list">
{%include 'images/image/list_ajax.html' with images=user.images_created.all %}
</div>
{% endwith %}
{%endblock%}
However, the thumbnail tag creates nothing in view. am I missing anything?
You're probably missing a border-radius attribute in your css. If you already have that and it's still not working, clear your browser cache.
views.py
from django.shortcuts import render, get_object_or_404
from library.models import Game
from .models import Post
from django.views.generic import (
ListView
)
from django.template import context
# Create your views here.
def home(request):
context = {
'recent': Game.objects.all().order_by('post__date_posted')[:5],
'posts': Post.objects.all()
}
return render(request, 'main/home.html', context)
class TitlePostListView(ListView):
model = Post
template_name = 'main/title_posts.html'
context_object_name = 'posts'
def get_queryset(self):
title = get_object_or_404(Game, title=self.kwargs.get('title'))
return Post.objects.filter(game=title).order_by('-date_posted')[:5]
title_posts.html
{% extends "main/base.html" %}
{% load static %}
{% block styles %}
<link rel="stylesheet" type="text/css" href="{% static 'main/title_posts.css' %}">
{% endblock styles %}
{% block content %}
<style>
body {
background-image: url("{{ game.cover_display.url }}");
background-repeat: no-repeat;
background-size: 100% 1000px;
background-color: #171717;
}
</style>
<div class="container margin-top-300">
<div class="row justify-content-center">
<div class="col-3 text-center">
<img src="{{ game.cover.url }}">
</div>
<div class="col">
<p>{{ game.description| safe }}</p>
</div>
</div>
<hr>
{% for post in posts %}
<div class="row">
<div class="col-4 article-column-height text-center">
<img class="article-image-height" src="{{ post.article_image.url }}">
</div>
<div class="col-8 article-column-height">
<h2><a class="article-title" href="#">{{ post.article_title }}</a></h2>
</div>
</div>
<hr>
</div>
{% endfor %}
{% endblock content %}
models.py
class Post(models.Model):
article_title = models.CharField(max_length=60, default="Article Title Place Holder")
content = HTMLField(default="Article Content Pace Holder")
date_posted = models.DateTimeField(default=timezone.now)
game = models.ForeignKey('library.Game', on_delete=models.CASCADE)
article_image = models.ImageField(default='/media/default.png')
class Game(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
cover = models.ImageField()
cover_display = models.ImageField(default='default.png')
developer = models.CharField(max_length=100)
Edit: I have a page that displays posts/articles for a certain video game. Currently my query returns the posts from the Post model for that video game. However, I am unsure of how to also display the video games description and images on that same page. The {{game.cover.url}}, ((game.description}}, and {{game.cover_display.url}} do not show up when I load the page because I am unsure how to also get that specific games objects from the Game model.
{% for post in posts %}
{% with post.game.set.all|first as game %}
<style>
body {
background-image: url("{{ game.cover_display.url }}");
background-repeat: no-repeat;
background-size: 100% 1000px;
background-color: #171717;
}
</style>
<div class="container margin-top-300 black">
<div class="row justify-content-center">
<div class="col-3 text-center">
<img src="{{ game.cover.url }}">
</div>
<div class="col">
<p>{{ game.description| safe }}</p>
</div>
</div>
{% endwith %}
<hr>
<div class="row">
<div class="col-4 article-column-height text-center">
<img class="article-image-height" src="{{ post.article_image.url }}">
</div>
<div class="col-8 article-column-height">
<h2><a class="article-title" href="#">{{ post.article_title }}</a></h2>
</div>
</div>
<hr>
</div>
{% endfor %}
You are using ForeignKey. So use like this in loop
{% with post.game_set.all|first as game %}
<img src="{{ game.url }}" />
{% endwith %}
As you are already filtering by game then only add the game in your get_context_data() method
def get_context_data(self, **kwargs):
context = super(TitlePostListView, self).get_context_data(**kwargs)
context['game'] = get_object_or_404(Game, title=self.kwargs.get('title'))
return context
I want to be able to change some settings from django admin, for example: site title or footer. I want to have app with model which includes this settings, but this settings should be in single copy. What the best way to do it?
You can create a view with #staff_member_required decorator, which renders/saves a form:
from django.contrib.admin.views.decorators import staff_member_required
...
#staff_member_required
def edit_config(request, ):
saved = False
if request.method == "POST":
form = ConfigForm(request.POST)
if form.is_valid():
...
# Do saving here
saved = True
else:
form = ConfigForm()
...
context = {
'form': form,
'saved': saved,
}
return render_to_response('staff/edit_config.html', context, context_instance=RequestContext(request))
Use django forms in the view, and pass it to the template.
then, in the template extend 'admin/base_site.html' so your form has a admin look and feel. Here's a sample template:
{% extends 'admin/base_site.html' %}
{% load i18n adminmedia %}
{% block title %}Edit Configuration {{ block.super }} {% endblock %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% admin_media_prefix %}css/forms.css" />{% endblock %}
{% block breadcrumbs %}
<div class="breadcrumbs">
{% trans "Home" %} > Edit Configuration
</div>
{% endblock %}
{% block content %}
<h1>Edit Configuration</h1>
{% if saved %}
<p class="success" style="background-color:#9F9; padding: 10px; border: 1px dotted #999;">
Settings were saved successfully!
</p>
{% endif %}
<form method="POST" action="">
{% csrf_token %}
<fieldset class="module aligned">
<h2>Configuration</h2>
<div class="description"></div>
{% for field in form %}
<div class="form-row {% if field.errors %}errors{% endif %}">
{{ field.errors }}
<div class="field-box">
{{ field.label }} : {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
</div>
{% endfor %}
</fieldset>
<div class="submit-row">
<input type="submit" value="{% trans 'Save' %}" class="default" name="_save"/>
</div>
</form>
{% endblock %}
You can use database, ini files, redis, ... for storing your configuration. You may define some general backend, and inherit your custom backends from it so it's flexible.
Sounds like django-constance would be a good fit.
Though django-flatblocks might be sufficient.
django-flatblocks is a simple application for handling small
text-blocks on websites. Think about it like django.contrib.flatpages
just not for a whole page but for only parts of it, like an
information text describing what you can do on a site.