django eccomerce prodcut name not showing in file - django

i am creating a new django eccomorce website now in product detail page here is my code
the problem is i cant see product name correct in html page problem with first()
when i use first then only product name showing but all products have same name i have 8 producs in my page eight product name same to first just like overwriting also i cant use for loop with first()
i will add some pics
urls.py
path('collection/<str:cate_slug>/<str:prod_slug>',views.product_view,name="productview"),
views.py
def product_view(request,cate_slug,prod_slug):
if (Category.objects.filter(slug=cate_slug, status=0)):
if (Products.objects.filter(slug=prod_slug, status=0)):
products = Products.objects.filter(slug=prod_slug, status=0).first()
context = {'products':products}
else:
messages.error(request,"no such product found")
return redirect("collection")
else:
messages.error(request,"no such category found")
return redirect("collection")
return render(request,"product_view.html",context)
models.py
class Products(models.Model):
category = models.ForeignKey(Category,on_delete=models.CASCADE)
slug = models.CharField(max_length=150, null=False, blank=False)
product_name = models.CharField(max_length=150, null=False, blank=False)
product_image = models.ImageField( upload_to=get_image,null=True,blank=True)
description = models.TextField(max_length=500,null=False,blank=False)
original_price = models.IntegerField(null=False,blank=False)
selling_price = models.IntegerField(null=False,blank=False)
status = models.BooleanField(default=False,help_text="0=default , 1=Hidden")
trending = models.BooleanField(default=False,help_text="0=default , 1=Trending")
meta_title = models.CharField(max_length=150,null=False,blank=False)
meta_keyword = models.CharField(max_length=150,null=False,blank=False)
meta_description = models.CharField(max_length=400,null=False,blank=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.product_name
productview.html
{% block content %}
<h1>{{ products.product_name }} </h1>
{% endblock %}
i just want correct product name for every category i stucked here in morning helping are appreciated thank you all for helping till now

I think you need to loop through your produckts:
{% for product in products %}
<h1>{{ product.product_name }}</h1>
{% endfor %}
view:
def product_view(request,cate_slug,prod_slug):
if (Category.objects.filter(slug=cate_slug, status=0).exists()):
if (Products.objects.filter(slug=prod_slug, status=0).exists()):
products = Products.objects.filter(slug=prod_slug, status=0)
context = {'products':products}
else:
messages.error(request,"no such product found")
return redirect("collection")
else:
messages.error(request,"no such category found")
return redirect("collection")
return render(request,"product_view.html",context)
Note that usually the model name is singular, so it should be class Products(models.Model):

Related

when I try to render tags I get Wallpaper.Wallpaper.None

views.py
def download(request, wallpaper_name):
try:
wallpaper = Wallpaper.objects.get(name=wallpaper_name)
similar_wallpapers = wallpaper.tags.similar_objects()[:2]
except Exception as exc:
wallpaper = None
similar_wallpapers = None
messages.error = (request, 'Sorry! data does not exist')
context = {'wallpaper': wallpaper, 'similar_wallpapers': similar_wallpapers}
return render(request, 'Wallpaper/download.html', context)
models.py
class Tags(models.Model):
tag = models.CharField(max_length=100)
def __str__(self):
return self.tag
class Wallpaper(models.Model):
name = models.CharField(max_length=100, null=True)
size = models.CharField(max_length=50, null=True)
pub_date = models.DateField('date published', null=True)
resolution = models.CharField(max_length=100, null=True)
category = models.ManyToManyField(Category)
tags = TaggableManager()
Device_Choices = [
('PC', 'pc'),
('mobile', 'mobile')
]
Devices = models.CharField(max_length=20,choices=Device_Choices, default= 'PC')
image = models.ImageField(upload_to='Wallpaper/Images/', default="")
def __str__(self):
return self.name
download.html
<div class="tag">
<h3>Tags</h3>
<ul>
<li>{{wallpaper.tags}}</li>
</ul>
</div>
I want all the tags of that particular wallpaper to be rendered
and if possible please tell me if there is any other way to handle tags, because using taggit its very difficult i am getting manny errors
Tags are a many-to-many relation so you need to use .all in your template to get them. However, this will just show you the queryset, so you need to loop through them to render their names:
<ul>
{% for tag in wallpaper.tags.all %}
<li>{{ tag.name }}</li>
{% endfor %}
</ul>

How to add condition to a manytomany relationship

I'm a little new to Django, so my question may be basic, but bare with me. Let's say I'm sharing my posts with some of my friends (who are manytomany relation with the post), but also giving an extra condition for whether they can comment on it, or not. This condition, together with the name of the user to be shared with are submitted through a forum. Now my problem is that I don't know how/where to save this condition. I will show you some of my code.
Models.py
class Task(models.Model):
name = models.CharField(max_length=50)
text = models.TextField()
deadline = models.DateTimeField()
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='taskset')
shared = models.ManyToManyField(User, blank=True, related_name = 'shared_list')
def __str__(self):
return f"{self.name}-{self.user.username}"
class Comment(models.Model):
text = models.TextField()
task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='comments')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments')
created = models.DateField(auto_now_add=True)
def __str__(self):
return f"{self.user.username}-{self.task}"
Share form html
{% extends 'base.html'%}
{% load crispy_forms_tags %}
{% block content %}
<h3>Enter the Username of the Friend you want to share with</h3>
<form method="POST">
{% csrf_token %}
{{form|crispy}}
<input type="submit", value="Share">
</form>
{% endblock content %}
And the view processing it
def share(request, id):
task = Task.objects.get(id = id)
if request.method == 'POST':
share_with = User.objects.get(username = request.POST['username'])
if share_with is not None:
task.shared.add(share_with)
task.save()
return redirect('index')
else:
form = ShareForm()
return render(request, 'share.html', {'form':form})
Thanks a lot, I've been stuck for two hours, PLEASE HELP!

Django Display multipe categories on page

I have this model.py file:
class Category(models.Model):
title = models.CharField(max_length=255, verbose_name="Title")
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.title
class Video(models.Model):
title = models.CharField(max_length=128)
description = models.TextField(default='')
thumbnail = models.ImageField(default='default_thumbnail.png', upload_to='thumbnails')
date_posted = models.DateTimeField(default=timezone.now)
category = models.ForeignKey(
Category,
on_delete=models.SET_DEFAULT,
#null=True,
default=1,
verbose_name="Category"
)
def __str__(self):
return self.title
Each video has its own category and I want to display on one page a given number of films in each category.
Currently, I'm only showing the last 5 videos on the page:
def home(request):
latest_videos = Video.objects.all().order_by('-date_posted')[:5]
categories = Category.objects.all()
context = {
'latest_videos': latest_videos,
#'categories': categories,
}
return render(request, 'videos/home.html', context)
I have no idea how to display a given number of movies in each category. I tried to send all the videos and query them on the template, but this is probably impossible.
Any ideas? I'm still learning Django, but this time I found a problem I can't solve all day.
Thanks
I don't know how many categories do you need to show in your template but one way to do this is like:
def home(request):
ready_data = []
all_categories = Category.objects.prefetch_related('video_set').all() # Note that video_set is your default related query name
for _c in all_categories:
related_videos = _c.video_set.all().order_by('-date_posted')[:5]
ready_data.append({"category_id": _c.id, "category_title": _c.title, "related_videos": related_videos})
context = {
'data': ready_data
}
return render(request, 'videos/home.html', context)
And you should also change this part of your template to something like:
{% for d in data %}
<p> category: {{ d.category_id }}, {{ d.category_title }} </p>
{% for v in d.related_videos %}
<h3> Videos </h3>
<p> {{ v.id }}- {{v.title}} </p>
{% endfor %}
{% endfor %}
This way you can show each category and 5 last of it's related videos.

Problem with set value in view and template

I want to create a list where the user can give titles to his list in which he selects in which category he should be, this is how the model looks like
class UserListAnime(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
anime = models.ManyToManyField(Anime, through='ListAnime')
class Anime(models.Model):
title = models.CharField(max_length=200)
slug = extension_fields.AutoSlugField(populate_from='title', blank=True)
class ListAnime(models.Model):
LIST_CHOICES = (
(WATCHING, 'Oglądam'),
(PLANNING, 'Planuję'),
(COMPLETED, 'Ukończone'),
(DROPPED, 'Porzucone'),
(ONHOLD, 'Wstrzymane'),
(MISSING, 'Pomijam'),
)
user = models.ForeignKey(UserListAnime, on_delete=models.CASCADE, null=True, blank=True)
anime = models.ForeignKey(Anime, on_delete=models.CASCADE, null=True, blank=True)
type = models.CharField(max_length=30, choices=LIST_CHOICES, null=False, blank=False)
In the view I only have to take a list of the user and I have displayed it but I want it to be filtered through the type in ListAnime
def ListAnimeView(request, pk, username):
list_anime = UserListAnime.objects.filter(user__pk=pk, user__username=username,
listanime__type='ogladam',
anime__listanime__type='ogladam').all()
context = locals()
and html looks like
{% for list in list_anime.anime.all %}
{{ list }}
{% endfor %}
My question is how to extract all records when type = LIST_CHOICES and show this in html
EDIT: SOLVED just need change in view from UserListAnime,objects.. to ListAnime.objects
and in html should be
{% for list in list_anime %}
{{ list.anime }}
{% endfor %}
I don't know exactly what are you trying to achieve. Do you want to get a list of ListAnime entities given a user, and get only which are of type 'ogladam'?
def listAnimeView(request, pk):
list_anime = ListAnime.objects.filter(user__user_id=pk, type='ogladam')
return render(request, 'template-name', context=['list_anime': list_anime])'

django - can't filter object and transfer to template

I've got a model which I'm trying to filter according to an argument passed in the url, then display the filtered object via a template, but I don't know what I'm doing wrong.
Here's the urls.py:
url(r'^courses/(?P<course_code>\w+)/$', views.course, name="course"),
Here's the view:
from website.models import Course
def course(request, course_code):
current_course = Course.objects.filter(short_title='course_code')
template = loader.get_template('website/course.html')
context = Context({
'current_course': current_course,
})
return HttpResponse(template.render(context))
Here's the model:
class Course(models.Model):
title = models.CharField(max_length=200)
short_title = models.CharField(max_length=5)
course_type = models.CharField(max_length=100)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
fee = models.IntegerField()
places = models.IntegerField()
venue = models.CharField(max_length=200)
description = models.TextField()
short_description = models.TextField()
age_low = models.IntegerField()
age_high = models.IntegerField()
And here's the template:
{% if current_course %}
{% for course in current_course %}
{{ current_course.title }}
{% endfor %}
{% else %}
<p>Sorry, that course doesn't exist.</p>
{% endif %}
And when I load the page /courses/CR1 (the course with short_title="CR1" definitely exists because it renders fine on another template where I'm not filtering but just displaying all the courses), it gives me "Sorry, that course doesn't exist."
Can anyone see what I'm doing wrong?
In this line:
current_course = Course.objects.filter(short_title='course_code')
You're checking for course titles with the exact text 'course_code'. You mean to use the value of the variable course_code:
current_course = Course.objects.filter(short_title=course_code)