I want to save the url of images in my database using django shell
here is my model
class Album(models.Model):
reference = models.IntegerField(null = True)
created_at = models.DateTimeField(auto_now_add=True)
available = models.BooleanField(default=True)
title = models.CharField(max_length=200)
picture = models.URLField()
artists = models.ManyToManyField(Artist, related_name='albums', blank=True)
here is what i did in the shell
album = Album.objects.create(title="Funambule", picture="/home/etali/Images/moi.png")
the url is correctly save in the database but it's impossible to load it in the view
here is the view
<div class="col-sm-4 text-center">
<a href="/">
<img class="img-responsive" src="{{ album.picture }}" alt="{{ album.title }}">
</a>
<h3>{{ album.title }}</h3>
{% for artist in album.artists.all %}
<p>{{ artist.name }}</p>
{% endfor %}
</div>
here is the error that appears when I inspect the code
Related
Hi everyone I'm trying to create an auction system with Django.
But when I go to the item profile, Django sends me an error:
Exception Value:
The 'image' attribute has no file associated with it.
auction.html
{% extends "base.html" %}
{% block content %}
{% load static %}
<div class="page-header">
<h1>OPEN AUCTIONS</h1>
</div>
<div class="container">
<div class="row">
{% for item in auction %}
<div class="col-sm-4">
<div class="card border-secondary" style="width: 25rem;">
<div class="card-header">
Auction {{item.id}}
</div>
<img src="{{ item.image.url }}" class="card-img-top" width="250" height="180">
<div class="card-body">
<h3 class="card-title" style="text-align:center" >{{ item.object }}</h3>
<p class="card-text">{{item.description}}<br> Price: ${{ item.open_price}}<br>
End: {{ item.close_date }}</p>
<form method="POST">
{% csrf_token %}
<input type="number" name='auct_id' value={{item.id}} readonly>
<button type="submit" class="btn btn-primary btn-sm">Go</button>
</form>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
If I remove item from <img src="{{ item.image.url }}" class="card-img-top" width="250" height="180"> the page work correctly but the image doesn't display. Like this:
view.py
#login_required(login_url="login")
def auction(request):
if request.user.is_superuser:
messages.error(
request, "super user can access to admin/ and new_auction page only"
)
return redirect("new_auction")
auction = Auction.objects.filter(active=True)
for data in auction:
check = check_data(data.close_date)
if check is False:
data.active = False
data.save()
check_winner(
request, data.id
)
check_prof = check_profile(
request
)
if check_prof is True:
return redirect("profile")
auctions_open = Auction.objects.filter(active=True)
if request.method == "POST":
form = request.POST
auct_ids = form["auct_id"]
auct_id = int(auct_ids)
request.session["selected_id"] = auct_id
return redirect("betting")
else:
return render(request, "auction/auction.html", {"auction": auctions_open})
models.py
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
# Create your models here.
class Auction(models.Model):
object = models.CharField(max_length=50)
description = models.CharField(max_length=256, default="")
image = models.ImageField(upload_to="media/", null=True, blank=True)
open_date = models.DateTimeField(auto_now_add=True)
close_date = models.DateTimeField()
total_bet = models.IntegerField(default=0)
open_price = models.FloatField(
default=0,
)
close_price = models.FloatField(default=0)
winner = models.CharField(max_length=256, default="")
active = models.BooleanField(default=True)
json_details_file = models.TextField(default="")
tx = models.CharField(max_length=256, default="")
def __str__(self):
return self.object
settings.py
MEDIA_ROOT = os.path.join((BASE_DIR), "media")
MEDIA_URL = "/media/"
According to your model field image, you must give different name instead of media to upload_to.
Let's give different name to upload_to:
image = models.ImageField(upload_to="images/", null=True, blank=True) #here added images instead of media
And in your template:
instead of this:
<img src="{{ item.image.url }}" class="card-img-top" width="250" height="180">
Try this way:
<img src="/media/{{ item.image }}" class="card-img-top" width="250" height="180">
And now that images will display.
Note: don't forget to migrate after modifying upload_to="images/"
I am creating E-Learning website and I want to show "Course Content or Lession" as a playlist which is related to subject. Like that image
but I am getting error Cannot query "Python Tutorials Teaser": Must be "Subject" instance. Python Tutorials Teaser is title of the lession.
view.py
def allsubject(request):
subj = Subject.objects.all()
context = {'subj': subj}
return render(request, 'allsubject.html', context)
def pvideos(request, slug):
vds = Videos.objects.filter(slug=slug).first()
coursecontent = Videos.objects.filter(subject=vds)
context = {'vds':vds, 'coursecontent':coursecontent}
return render(request, 'pvideos.html', context)
models.py
class Videos(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=500)
cont = models.TextField()
vurl = models.URLField(max_length=200)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='videos')
position = models.PositiveSmallIntegerField(verbose_name="videono.")
slug = models.CharField(max_length=130)
timeStamp = models.DateTimeField(default=now)
def __str__(self):
return self.title
pvideo.html
{% extends 'base.html' %}
{% block title %}Free Video Course {% endblock title %}
{% block body %}
<div class="container">
<div class="embed-responsive embed-responsive-21by9">
<iframe class="embed-responsive-item" src="{{vds.vurl}}" allowfullscreen></iframe>
</div>
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active font-weight-bold" id="home-tab" data-toggle="tab" href="#overview" role="tab"
aria-controls="home" aria-selected="true">Overview</a>
</li>
<li class="nav-item">
<a class="nav-link font-weight-bold" id="profile-tab" data-toggle="tab" href="#coursecontent" role="tab"
aria-controls="profile" aria-selected="false">Course Content</a>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="overview" role="tabpanel" aria-labelledby="home-tab">
<h2>{{vds.title}}</h2>
<p>{{vds.cont|safe}}</p>
</div>
<div class="tab-pane fade" id="coursecontent" role="tabpanel" aria-labelledby="profile-tab">
{% for c in coursecontent %}
{{c.title}}
{% endfor %}
</div>
</div>
</div>
{% endblock body %}
I think I made a mistake on views.py coursecontent = Videos.objects.filter(subject=vds). I want to show this playlist on that page where I show lessions. I hope you understand what I want. If anyone has any other idea besides this, so please help me.
I user click on course content then I show all lession related to subject
You are right, you have made a mistake in coursecontent = Videos.objects.filter(subject=vds)
Subject must either be the pk or an instance of subject but you're giving it another video instance. What you want is
coursecontent = Videos.objects.filter(subject=vds.subject).exclude(sno=vds.sno)
.filter(subject=vds.subject) will give you all videos with the same subject.
.exclude(sno=vds.sno) will exclude the current video from the query. This is useful if you want to show only the other videos... If you want to include all, just skip that part.
As a side note, you might want to improve your variable naming.
vds could be called video (it's singular)
vurl could be just url
cont could be content
Most of your model names should be singular (coz each is a single instance).
An e-learning website is a nice initiative.
I am trying to set an instance of a Modelform that render through ListView.
Program Model:
class Program(models.Model):
patient = models.ForeignKey(User, on_delete=models.CASCADE, default=0)
program_name = models.CharField(max_length=1000, default="")
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.id) + " - " + self.patient.username + " - " + self.program_name + " - " + str(self.date_posted)
def get_absolute_url(self):
return reverse('program-detail', kwargs={'pk': self.pk})
Exercise Model:
class Exercise(models.Model):
program = models.ForeignKey(Program, on_delete=models.CASCADE, default=0)
date_posted = models.DateTimeField(default=timezone.now)
name = models.CharField(max_length=1000, default="")
description = models.TextField(default="")
load_share = models.TextField(default="")
breath_method = models.TextField(default="")
recovery_method = models.TextField(default="")
measure_method = models.TextField(default="")
notes = models.TextField(default="")
extra_info = models.TextField(default="")
reps = models.PositiveSmallIntegerField(default=0)
sets = models.PositiveSmallIntegerField(default=0)
def __str__(self):
return str(self.program_id) + " - " + str(self.pk) + " - " + " - " + self.name + " - " + str(self.date_posted)
Data Model:
exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default="0")
set_number = models.PositiveSmallIntegerField(default=0)
spo2 = models.PositiveSmallIntegerField(default=0)
hr = models.PositiveSmallIntegerField(default=0)
physical_level = models.PositiveSmallIntegerField(default=0)
breath_level = models.PositiveSmallIntegerField(default=0)
sys = models.PositiveSmallIntegerField(default=0)
dia = models.PositiveSmallIntegerField(default=0)
misc_input = models.PositiveSmallIntegerField(default=0)
def __str__(self):
return self.exercise.name
My Exercise listView include the Data form that the User need to fill up, It is paginated to 1 exercise per page.
Exercise ListView:
# Exercise list inside each program + Data form
class ExerciseListView(LoginRequiredMixin, FormMixin, ListView):
model = Exercise
context_object_name = 'exercises'
form_class = DataForm
paginate_by = 1
def get_queryset(self):
program_num = get_object_or_404(Program, pk=self.kwargs.get('pk'))
return Exercise.objects.filter(program=program_num)
def form_valid(self, dataform):
program_num = get_object_or_404(Program, pk=self.kwargs.get('pk'))
exercises = Exercise.objects.filter(program=program_num)
for exe in exercises:
dataform.instance.exercise = exe.pk
print(dataform.instance.exercise)
return super(ExerciseListView, self).form_valid(dataform)
# Submit the Data form and redirect to the same page exercise
def add_data(request):
page = request.GET.get('page')
page = '?page={}'.format(page) if page else ''
if request.method == "POST":
form = DataForm(request.POST)
if form.is_valid():
data = form.save()
return redirect(reverse('program-detail', kwargs={'pk': data.exercise.program.pk}) + page)
forms.py:
class DataForm(forms.ModelForm):
class Meta:
model = Data
fields = ['set_number', 'spo2', 'hr']
I didn't add all the fields because it is too long for test stage.
template.py:
{% extends "program/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h3> Program Exercises List </h3>
{% for exercise in exercises %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
{% if user.is_superuser %}
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'exercise-update' exercise.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'exercise-delete' exercise.id %}">Delete</a>
<p class="article-content">{{ exercise.name }}</p>
{% else %}
<p class="article-content">{{ exercise.name }}</p>
{% endif %}
</div>
<div class="article-metadata">
<p class="article-content">{{ exercise.description }}</p>
<p class="article-content">{{ exercise.breath_method}}</p>
<p class="article-content">{{ exercise.recovery_method }}</p>
<p class="article-content">{{ exercise.measure_method }}</p>
<p class="article-content">{{ exercise.load_share }}</p>
<p class="article-content">{{ exercise.notes }}</p>
<p class="article-content">{{ exercise.extra_info }}</p>
<p class="article-content">{{ exercise.reps }}</p>
<p class="article-content">{{ exercise.sets }}</p>
</div>
<form action="{% url 'data-submit' %}{%if request.GET.page%}?page={{request.GET.page}}{%endif%}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Exercise Measurements</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Save</button>
</div>
</form>
</div>
</article>
{% endfor %}
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous Exercise</a>
{% endif %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next Exercise</a>
{% else %}
<a class="btn btn-outline-info mb-4" href="{% url 'web-home' %}">Exit</a>
{% endif %}
{% endif %}
{% endblock content %}
The instances I am trying to pass (in the Data form) without the user input are:
exercise - each Data form will be connect to an exercise in the database. as I mention before, the exercises are paginated 1 per page, maybe its something i can use?
I tried to solve it by that way:
def form_valid(self, dataform):
program_num = get_object_or_404(Program, pk=self.kwargs.get('pk'))
exercises = Exercise.objects.filter(program=program_num)
for exe in exercises:
dataform.instance.exercise = exe.pk
print(dataform.instance.exercise)
return super(ExerciseListView, self).form_valid(dataform)
It didn't work, I am still receiving id error for this instance.
set_number - each exercise as few sets. what I want to build is that:
the exercise as "sets" that define the number of sets the user need to perform. I want to set a "for" loop that count the number of sets and pass this instance "set_number" accordingly.
Each time the user submit the form, it will have an exercise and set_number.
Thanks!
I have problem with accessing by the link. I am using easy-thumbnail framework, and I created simple view for user list to list all existing users.
Error message:
django.template.exceptions.TemplateSyntaxError: Variable
'user.profile.photo' is an invalid source.
Django Traceback throws me to this view.
views.py file:
#login_required
def user_list(request):
users = User.objects.filter(is_active=True)
return render(request,
'account/user/list.html',
{'section': 'people',
'users': users})
urls.py file:
path('users/', views.user_list, name='user_list'),
template list.html:
{% extends "base.html" %}
{% load thumbnail %}
{% block title %}People{% endblock %}
{% block content %}
<h1>People</h1>
<div id="people-list">
{% for user in users %}
<div class="user">
<a href="{{ user.get_absolute_url }}">
<img src="{% thumbnail user.profile.photo 180x180 %}">
</a>
<div class="info">
<a href="{{ user.get_absolute_url }}" class="title">
{{ user.get_full_name }}
</a>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
sample code from base.html:
<li {% if section == "people" %}class="selected"{% endif %}>
People
</li>
models.py:
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
date_of_birth = models.DateField(blank=True, null=True)
photo = models.ImageField(upload_to='users/%Y/%m/%d/',
blank=True)
def __str__(self):
return f'Profile for user {self.user.username}'
Thank you for the helping in advance.
Reviewed the documentation https://easy-thumbnails.readthedocs.io/en/latest/usage/#templates. Creates a thumbnail from an object (usually a file field). I tried it and it helped solve my problem:
<img src="{{ user.profile.photo.url }}">
I had this problem too. You can solve the problem with the following solution:
Instead of users = User.objects.filter(is_active=True), use profiles = Profile.objects.all()
Change as follows: return render(request,'account/user/list.html',{'section': 'people', 'profiles': profiles}).
In the list.html file, change as follows:
{% extends 'base.html' %}
{% load thumbnail %}
{% block title %}People{% endblock %}
{% block content %}
<h1>People</h1>
<div id="people-list">
{% for profile in profiles %}
<div class="user">
<a href="{{ profile.user.get_absolute_url }}">
<img src="{% thumbnail profile.photo 180x180 %}" alt="{{ profile.user.last_name }}">
</a>
<div class="info">
<a href="{{ profile.user.get_absolute_url }}" class="title">
{{ profile.user.get_full_name }}
</a>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
I have two models SubCategory and Product i created a listview with model set to SubCategory and reference its related product set in template but items are not being loaded don't know what I have missed
models
class SubCategory(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=300)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=120)
price = models.FloatField()
image = models.ImageField(upload_to='pdt_imgs/')
sku = models.IntegerField()
available = models.BooleanField(default=True)
discount = models.IntegerField(default = 0)
category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
def __str__(self):
return self.name
Template in which I tried to reference product items related to subcategories
<div class="ps-block__categories">
<h3>Clothing & <br> Apparel</h3>
<ul>
{% for subcategory in object_list %}
<li>{{ subcategory.name }}</li>
{% endfor %}
</ul><a class="ps-block__more-link" href="#">View All</a>
</div>
<div class="ps-block__slider">
<div class="ps-carousel--product-box owl-slider" data-owl-auto="true" data-owl-loop="true"
data-owl-speed="7000" data-owl-gap="0" data-owl-nav="true" data-owl-dots="true" data-owl-item="1"
data-owl-item-xs="1" data-owl-item-sm="1" data-owl-item-md="1" data-owl-item-lg="1" data-owl-duration="500"
data-owl-mousedrag="off"><img src="{% static 'img/slider/home-3/clothing-1.jpg' %}" alt=""><a href="#"><img
src="{% static 'img/slider/home-3/clothing-2.jpg' %}" alt=""></a><a href="#"><img
src="{% static 'img/slider/home-3/clothing-3.jpg' %}" alt=""></a></div>
</div>
<div class="ps-block__product-box">
{% for product in object.product_set.all %}
<div class="ps-product ps-product--simple">
<div class="ps-product__thumbnail"><a href="product-default.html"><img src="{{ product.image.url }}"
alt=""></a>
{% if product.discount > 0 %}
<div class="ps-product__badge">-{{ product.discount }}%</div>
{% endif %}
{% if product.available == False %}
<div class="ps-product__badge out-stock">Out Of Stock</div>
{% endif %}
<ul class="ps-product__actions">
<li><a href="#" data-toggle="tooltip" data-placement="top" title="Read More"><i
class="icon-bag2"></i></a></li>
<li><a href="#" data-placement="top" title="Quick View" data-toggle="modal"
data-target="#product-quickview"><i class="icon-eye"></i></a></li>
<li><a href="#" data-toggle="tooltip" data-placement="top" title="Add to Whishlist"><i
class="icon-heart"></i></a></li>
<li><a href="#" data-toggle="tooltip" data-placement="top" title="Compare"><i
class="icon-chart-bars"></i></a></li>
</ul>
</div>
<div class="ps-product__container">
<div class="ps-product__content" data-mh="clothing"><a class="ps-product__title"
href="product-default.html">{{ product.name }}</a>
<div class="ps-product__rating">
<select class="ps-rating" data-read-only="true">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
<option value="2">5</option>
</select><span>01</span>
</div>
<p class="ps-product__price sale">UGX{{ product.price }}</p>
</div>
</div>
</div>
{% endfor %}
</div>
For now I cant load product items despite trying reference them as related objects of subcategory