How can I show all this images in a carousel - django-models

I know beginners can ask stupid questions but that is the way trough all it.
Is it possible that i can list all this images in a carousel? or image gallery. How can i list this images easiest?
What would you suggest?
I don't want to use foreignkey because I cannot (I couldn't yet understand the save process in the views) save a separate model in a view.
Thanks a lot
class MyFamily(models.Model):
author = models.ForeignKey(Profile, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
update = models.DateField(auto_now=True)
title = models.CharField(max_length=100)
explanatipon = models.TextField(blank=True)
photo1 = models.ImageField(upload_to='posts/photos/')
photo2 = models.ImageField(upload_to='posts/photos/')
photo3 = models.ImageField(upload_to='posts/photos/')
photo4 = models.ImageField(upload_to='posts/photos/')
photo5 = models.ImageField(upload_to='posts/photos/')
active = models.BooleanField(default=True)
def __str__(self):
return str(self.title)[:30]
i tried to make it like #willem-van-onsem mentioned it but without success. I NEED HELP PLEASE
What did I do :
MODELS PROFILE:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.user.username)
MODELS MYFAMILY:
class MyFamily(models.Model):
author = models.ForeignKey(Profile, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
update = models.DateField(auto_now=True)
title = models.CharField(max_length=100)
explanatipon = models.TextField(blank=True)
photo1 = models.ImageField(upload_to='posts/photos/')
photo2 = models.ImageField(upload_to='posts/photos/')
photo3 = models.ImageField(upload_to='posts/photos/')
photo4 = models.ImageField(upload_to='posts/photos/')
photo5 = models.ImageField(upload_to='posts/photos/')
active = models.BooleanField(default=True)
#property
def photos(self):
photos = [self.photo1, self.photo2, self.photo3, self.photo4, self.photo5]
return [photo for photo in photos if photo is not None]
def __str__(self):
return str(self.title)[:30]
VİEWS :
def photo(request):
myfamily = MyFamily.objects.filter(active=True)
context = {
'myfamily':myfamily
}
return render(request, 'posts/create-form.html')

You can return the photo's in a list:
class MyFamily(models.Model):
# …
#property
def photos(self):
photos = [self.photo1, self.photo2, self.photo3, self.photo4, self.photo5]
return [photo for photo in photos if photo is not None]
If you construct a view where you pass the MyFamily object as myfamily to the template render engine, we can generate HTML for a Bootstrap carousel:
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
{% for photo in myfamily.photos %}
<div class="carousel-item {% if forloop.first %}active{% endif %}">
<img class="d-block w-100" src="{{ photo.url }}" alt="First slide">
</div>
{% endfor %}
</div>
</div>
That being said, I think the modelling might be improved with an extra model. Right now one can only upload exactly five object. Normally one defines an extra model (MyFamilyPhoto) with a ForeignKey to the MyFamily in this case to allow to generate an arbitrary number of MyFamilyPhotos for each MyFamily. For an arbitrary MyFamily object, you will need to add a parameter to the url. In the view you can obtain the myfamily of the user with:
from django.contrib.auth.decorators import login_required
#login_required
def photo(request):
myfamily = MyFamily.objects.get(active=True, author__user=request.user)
context = {
'myfamily': myfamily
}
return render(request, 'posts/create-form.html')
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].

Related

Django template pulling related data with "<QuerySet [<XXXXX>]>

My template is pulling the data I want it to from a related model, but it's also pulling <QuerySet [<XXXXX>]> where I only want it to display, in this case, the album title.
The Song model is as such
class Song(models.Model):
title = models.CharField(max_length=255)
playlist = models.ManyToManyField(Playlist)
in_queue = models.BooleanField()
is_playing = models.BooleanField()
album = models.ManyToManyField(Album)
keyword = models.ManyToManyField(Keyword)
audio_file = models.FileField()
lyrics = models.TextField()
p_graph = models.ManyToManyField(Album, related_name='phonograph')
and the Album class is as such
class Album(models.Model):
title = models.CharField(max_length=255)
artist = models.ManyToManyField(Artist)
year = models.IntegerField()
p_graph = models.CharField(max_length=255)
artwork = models.ImageField()
def __str__(self):
return self.title
Thanks

How to store list in Django model field while using SQLite

I'm stuck with the issue that I need to insert the list [ ] in the model field while using SQLite,
Group_Model.py:
class ClassificationGroup(models.Model):
vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True)
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=1000)
classification_id = models. [what do i take here to make it capable to store list of ids that will be related to the classification table.]
Classification_Model.py
class Classification(models.Model):
id = models.IntegerField()
name = models.CharField(max_length=100)
description = models. CharField(max_length=1000)
domain_name = models.CharField(max_length=200)
i just want to store the list of classification in the one field of the Classification Group Mentioned above, Please help me out in this.
Add a method to your class to convert it automatically.
import json
class ClassificationGroup(models.Model):
#...
classification_id = models.CharField(max_length=200)
def set_classification_id (self, lst):
self.classification_id = json.dumps(lst)
def get_classification_id (self):
return json.loads(self.classification_id)
your view:
obj = ClassificationGroup.objects.create(name="name",**data)
obj.set_classification_id([1,2,3])
obj.save()
#there are several examples of using this method
your HTML:
{% for obj in objects %}
{{ obj.name }}
{{ obj.get_classification_id }}
{% endfor %}

How do i access another column from related table other than the foreign key, when creating an API view

Im using django for a web app and i am creating REST API views. Is there a way i can access two tables in one view? If not, how can can i retrieve a non-foreign key column from a related record. The below code is retrieving a vase record based on a URL parameter. I want to access the artistName which is stored in artist table (a one-to-many with Vase table), not artist_id which is stored in Vase
class FilterVases(generics.ListAPIView):
serializer_class = VaseSerializer
def get_queryset(self):
queryset = Vase.objects.all()
artist_id = self.request.query_params.get('artist_id')
if artist_id is not None:
queryset = queryset.filter(artist_id=artist_id)
vaseID = self.request.query_params.get('vaseID')
if vaseID is not None:
queryset = queryset.filter(vaseID=vaseID)
return queryset
edited to add
This is models for Artist and Vase:
class Artist(models.Model) :
artistID = models.CharField(max_length=10)
artistName = models.CharField(max_length=100)
class Vase(models.Model):
vaseID = models.CharField(max_length=10)
vaseRef = models.CharField(max_length=255,blank=True,null=True)
inscription = models.CharField(max_length=255,blank=True,null=True)
fabric = models.CharField(max_length=100, blank=True,null=True)
subject = models.CharField(max_length=255,blank=True,null=True)
technique = models.CharField(max_length=100,blank=True,null=True)
height = models.FloatField(max_length=100,blank=True,null=True)
diameter = models.FloatField(max_length=100,blank=True,null=True)
shape = models.ForeignKey(Shape, on_delete=models.CASCADE)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
provenance = models.ForeignKey(Provenance, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
In the Vase model add this:
def artist_name(self):
return self.artist.artistName
Hence, it will look like:
class Vase(models.Model):
vaseID = models.CharField(max_length=10)
vaseRef = models.CharField(max_length=255,blank=True,null=True)
inscription = models.CharField(max_length=255,blank=True,null=True)
fabric = models.CharField(max_length=100, blank=True,null=True)
subject = models.CharField(max_length=255,blank=True,null=True)
technique = models.CharField(max_length=100,blank=True,null=True)
height = models.FloatField(max_length=100,blank=True,null=True)
diameter = models.FloatField(max_length=100,blank=True,null=True)
shape = models.ForeignKey(Shape, on_delete=models.CASCADE)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
provenance = models.ForeignKey(Provenance, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
def artist_name(self):
return self.artist.artistName
In the VaseSerializer add the 'artist_name' to the fields Meta.
If you want to add this custom fields to all Vase Model fields, refer to this topic Django Rest framework, how to include '__all__' fields and a related field in ModelSerializer ?
class VaseSerializer(serializers.ModelSerializer):
class Meta:
model = models.Vase
fields = '__all__'
extra_fields = ['artist_name']
def get_field_names(self, declared_fields, info):
expanded_fields = super(VaseSerializer, self).get_field_names(
declared_fields, info)
if getattr(self.Meta, 'extra_fields', None):
return expanded_fields + self.Meta.extra_fields
else:
return expanded_fields
Below should your view:
class FilterVases(generics.ListAPIView):
serializer_class = VaseSerializer
def get_queryset(self):
queryset = Vase.objects.all()
query_artist = self.request.query_params.get('artist_name')
if query_artist is not None:
try:
artist = Artist.objects.get(artistName=query_artist)
queryset = queryset.filter(artist=artist)
except:
pass
vaseID = self.request.query_params.get('vaseID')
if vaseID is not None:
queryset = queryset.filter(vaseID=vaseID)
return queryset

Django show only one element

I have product with image but when i try show image only this product django show me all image product how i can fix it ? I try wite slice don't work beacuse if i do |slice:"0:1" show me image but not image this product.
class Product(models.Model):
category = models.ForeignKey(Category, related_name='product')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='product/%Y/%m/%d',
blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
promo = models.BooleanField(default=False)
news = models.BooleanField(default=True)
section = models.CharField(max_length=50, choices=SECTION_CHOICES, default=None)
detailimage = models.ImageField(upload_to='product/detail/%Y/%m/%d',
blank=True)
detailimagetwo = models.ImageField(upload_to='product/detail/%Y/%m/%d',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
#property
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
#property
def detail_url(self):
if self.detailimage and hasattr(self.detailimage, 'url'):
return self.detailimage.url
#property
def detailtwo_url(self):
if self.detailimagetwo and hasattr(self.detailimagetwo, 'url'):
return self.detailimagetwo.url
def get_absolute_url(self):
return reverse('shop:product_detail',
args=[self.id, self.slug])
My views.py
def product_detail(request, id, slug):
product = get_object_or_404(Product,
id=id,
slug=slug,
available=True)
products = Product.objects.all()
return render(request,
'shop/product/detail.html',
{'product': product,
'products': products})
and my detail.html
{% extends "shop/base.html" %}
{% load static %}
{% block title %}{{ product.name }}{% endblock %}
{% block content %}
{% for p in products %}
<img src="{{p.detail_url}}" class="img-responsive">
{% endfor %}
</div>
</div>
{% endblock %}
if u want somethink more comment and i will how fast i can add it .
change your view
def product_detail(request, id, slug):
product = get_object_or_404(Product,
id=id,
slug=slug,
available=True)
return render(request,
'shop/product/detail.html',
{'product': product})
and in template change
{% for p in products %}
to
{% for p in product %}
you can solve the problem by removing one 's' in template but i suggest change the view function as mentioned
in case your using Pillow not just the address of image as string change this
{{p.detail_url}}
to
{{p.fieldname.url}}

edit and update the row in database using django

models.py
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
age = models.IntegerField()
def __unicode__(self):
return "{0} {1} {2} {3} {4}".format(
self, self.first_name, self.last_name, self.email, self.age)
class Book(models.Model):
book_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
author=models.ForeignKey(Author)
def __unicode__(self):
return "{0} {1} {2}".format(
self.pk, self.book_name, self.publisher_name)
forms.py
class AuthorForm(ModelForm):
class Meta:
model = Author
BookFormset = inlineformset_factory(Author, Book,
fields=('book_name', 'publisher_name'), extra=1,
can_delete=False)
urls.py is
admin.autodiscover()
urlpatterns = patterns('',
url('^$', index),
url('^index/$', index),
url('^addbook/$', addbook),
url('^book_detail/$', book_detail, 'book_summary'),
url('^editbook/(?P<book_id>\d+)/$', editbook) ,
url('^deletebook/(?P<book_id>\d+)/$',deletebook) ,
url(r'^admin/', include(admin.site.urls)),
)
I need to perform edit and update the row in database,i did it by using single table.But using two table have some confusion how to take 2nd table using that particular id.I am using forms in this.Can you help me in this to write codes in views.py.Example for doing the same using two table is no where i seen.
Thanks
def update_book(request, book_id):
author = get_object_or_404(Author, pk=author_id)
form = AuthorForm(instance=author)
book_formset = BookFormset(instance=author)
if request.method == 'POST':
form = AuthorForm(request.POST, instance=author)
if form.is_valid():
author = form.save(commit=False)
book_formset = BookFormset(request.POST, instance=author)
if book_formset.is_valid():
author.save()
book_formset.save()
return redirect('/index/')
return render_to_response('updatebook.html',{
'form': form, 'formset': book_formset
},context_instance=RequestContext(request))
<div align="center">
<tr>
<form method="POST">
{% csrf_token %}
<h5>Author:</h5>
{{ form.as_p }}
<h5>Book:</h5>
{{ formset.as_p }}
<input type="submit" value="submit">
</form>
</tr>
</div>

Resources