Django: How to show all images in images model - django

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!

Related

can't upload image from database in django server

in my project i am trying to save image in database and next i want to get that image from database
in my dashborad everything working well, imgs where saved in db but when i am trying to get url from db and asign it to img src="" chrome says that 404 (Not Found)
this is my model
class Id(models.Model):
first_name = models.CharField(max_length=100, null=True)
image = models.ImageField(default='defaut.jpg', upload_to='document_pics')
def __str__(self):
return self.first_nam
img savinig in documents_pics folder then i am trying to in views.py get data from db and send it to home.html
def home(request):
context = {
'posts': Id.objects.all(),
'title': 'Home'
}
return render(request, 'blog/home.html', context)
home.html
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<article class="media content-section">
<img src="{{ post.image }} " width="200" height="200"
</article>
{% endfor %}
{% endblock content %}
and than i am getting 404 error
Try these path on your image jinja code in your html template
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<article class="media content-section">
<img src="{{ post.image.url }} " width="200" height="200"
</article>
{% endfor %}
{% endblock content %

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 template : {% if %} tag can't get it to work

I am looking for a way in order my templates can recognize an attribute from my extended userprofile, specifically if he is an affiliate and show different content in the templates whether he is an affiliate or not. Is there an other approach to this like to build an decorator?
i have worked with other {%if%} tags like this built-in auth request {% if request.user.is_authenticated %}
models.py project/useprofile/ , the book is in an other app project/book
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
affiliate = models.BooleanField(default=False)
add_book.html
{%extends 'base.html' %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block content1 %}
{% if userprofile.profile.affiliate = True %}
<h1>New post</h1>
<form method="POST" class="post-form">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="save btn btn-primary">Save</button>
</form>
{% endif %}
{% endblock %}
urls.py
url(r'^book/add/$', 'book.views.addbook', name='addbook'),
views.py
def addbook(request):
if request.method == "POST":
form = BookForm(request.POST)
if form.is_valid():
book = form.save(commit=False)
book.save()
return redirect('home')
else:
form = BookForm()
return render(request, 'add_book.html',
{'form':form,
})
UPDATE: i found a simple solution to my problem, just needed to put {% if user.profile.affiliate %} in my template since i have extended the django user profile and affiliate is boolean so i do not need do the equal == part since it passes if its True , but i am still looking for other options available

Django-endless-pagination twitter style pagination not working

I am using django-endless-pagination for my project. But its not working as it is supposed to. Neither is it showing the show more or neither does it work when I change the code to onscroll mode.
<script>$.endlessPaginate({paginateOnScroll: true});</script>
However the include tags are working as its showing the snaps in the template. And even both the scripts (i.e. the jquery and endless.js) are there. What am I missing? Your help and guidance will be very much appreciated. Thank you.
models.py:
class SnapGroup(models.Model):
name = models.CharField(max_length=150, blank=True, null=True)
date = models.DateField(default=date.today)
class Snap(models.Model):
date = models.ForeignKey(SnapGroup)
image = models.ImageField(upload_to=get_upload_file_name)
caption = models.CharField(max_length=150, blank=True, null=True)
views.py:
#page_template('snapgroups.html') # just add this decorator
def snaps(
request, template='snaps.html', extra_context=None):
context = {
'snapgroup': SnapGroup.objects.all(),
}
if extra_context is not None:
context.update(extra_context)
return render_to_response(
template, context, context_instance=RequestContext(request))
snaps.html:
{% if snapgroup.count > 0 %}
<div class="endless_page_template">
{% include page_template %}
</div>
{% block js %}
{{ block.super }}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{{ STATIC_URL }}endless_pagination/js/endless-pagination.js"></script>
<script>$.endlessPaginate();</script>
{% endblock %}
{% else %}
<li><p>No SNAPGROUP yet!</p></li>
<span class="clear_both"></span>
{% endif %}
snapgroups.html:
{% load endless %}
{% paginate snapgroup %}
{% for sg in snapgroup %}
<h4 id="combination" class="snap_date">{{sg.date|date:'l'}}, {{sg.date}}</h4>
<ul>
{% for snap in sg.snap_set.all %}
<li><img src="{{MEDIA_URL}}{{snap.image}}" alt="{{snap.caption}}" /></li>
{% endfor %}
<span class="clear_both"></span>
</ul>
{% endfor %}
{% show_more %}
Solved my problem by this post. Hope this will help someone else.

I can't display extended values of my user model

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.