Loading specific foreign key attribute in Django Template - html

Devs,
I have a 2 Models and one of them have a foreign key attribute as a reference to the other. Now I am trying to view both objects in my Template.
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_context_data(self, **kwargs):
context = super(ItemDetailView, self).get_context_data(**kwargs)
context['markets'] = Market.objects.all()
# And so on for more models
return context
In my template I just want the exact market for my product
I tryed something like this:
{% for market in markets %} // or {% for object.market in markets %}
{% if market.market == object.market %}
>> Do smth if conditions match <<
{% endif %}
{% endfor %}
In the loop I get strings like x1, x2, x3 and object.market have the value x1.
So I just want to output the object for the corresponding market.
But if I check {% if market.market == object.market %} the conditions somehow don't match. When I print them out inside the loop I get x1,x2,x3,... for market.market and x1,x1,x1,... for object.market
These are my models:
class Market(models.Model):
market = models.CharField(max_length=30)
branch = models.CharField(choices=BRANCH_CHOICES, max_length=1)
image = models.ImageField(blank=True)
slug = models.SlugField(blank=True)
def __str__(self):
return self.market
def get_absolute_url(self):
return reverse("core:market-product-list", kwargs={
'slug': self.slug
})
class Item(models.Model):
title = models.CharField(max_length=100)
market = models.ForeignKey(Market, related_name='children', on_delete=models.CASCADE, blank=True, null=True)
price = models.FloatField()
discount_price = models.FloatField(blank=True, null=True)
category = models.ForeignKey(ItemCategory, related_name='children', on_delete=models.CASCADE, blank=True, null=True)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
path = models.CharField(default='/market-product-list/', max_length=100)
description = models.TextField()
image = models.ImageField()

I just solved the issue. The problem was that object.market is interpreted as an object not as a string. So it was impossible to check the conditions in the if-clause. I managed to output the corresponding market with converting the object to a string like this:
At first:
{% if object.market|slugify|capfirst == market.market %}
and then changed it to simply
{% if object.market == market %}
which is obviously the better solution
PS: I also learned that this is bad programming I should not filter in a Template but I am new to Django and I am glad that things are working now :)

Just call the field for the particular market as in the model.
{% for market in markets %} // or {% for object.market in markets %}
{% if market.market == object.market %}
{{ market.fieldname }}
{% endif %}
{% endfor %}

Why don't you loop through Product(Item) objects?

Related

'Profile' object is not iterable

views.py.
#login_required
def friends_profile(request):
f_profiles = Profile.objects.get(user=request.user)
return render(request, 'mains/friends_profile.html', {'f_profiles':f_profiles} )
urls.py
path('friends_profile/', views.friends_profile, name='friends_profile'),
template = friends_profile.html
{% extends "mains/base.html" %}
{% block content %}
{% for friends in f_profiles %}
{{ friends.full_name }}
{% empty %}
<li>NO DATA</li>
{% endfor %}
{% endblock content %}
models.py
class Profile(models.Model):
user = models.OneToOneField(User,
on_delete=models.CASCADE,default='',unique=True)
full_name = models.CharField(max_length=100,default='')
friends = models.ManyToManyField(User, related_name='friends',blank=True)
email = models.EmailField(max_length=60,default='')
date_added = models.DateTimeField(auto_now_add=True)
def get_friends(self):
return self.friends.all()
def get_friends_no(self):
return self.friends.all().count()
def __str__(self):
return f'{self.user.username}'
STATUS_CHOICES = (
('send', 'send'),
('accepted','accepted'),
)
class Relationship(models.Model):
sender = models.ForeignKey(Profile, on_delete=models.CASCADE,
related_name='sender')
receiver = models.ForeignKey(Profile, on_delete=models.CASCADE,
related_name='receiver')
status = models.CharField(max_length=8, choices=STATUS_CHOICES)
def __str__(self):
return f"{self.sender}-{self.receiver}-{self.status}"
'Profile' object is not iterable. This is raising when i open this template( friends_profiles.html ). Please... Help me in this ERROR. What am i missing in this ?
I will really appreciate your HELP.
You are only passing a single object f_profiles in the context to the template, but are trying to iterate over an iterable by doing {% for friends in f_profiles %}.
f_profiles = Profile.objects.get(user=request.user) this will only give you one object which is the profile of the request.user. You are not getting friends of the user with this line of code.
Also, it maybe better to use
f_profiles = get_object_or_404(Profile, user=request.user)
Try to replace this code in the templates:
{% for friends in f_profiles %}
{{ friends.full_name }}
with
{% for friend in f_profiles.friends.all %}
{{ friend.full_name}}
or
{% for friend in f_profiles.get_friends %}
{{ friend.full_name }}

Django-How do i get the HTML template to show data from the two models?

So i'm creating a to-do app. How do I get the html view to show the tasks? I tried to show the name of the tasks but it's blank. So far, it only shows the board name and the user who created it.
Here is my code so far:
Models.py
class Board(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Board")
name = models.CharField(max_length=200)
class Task(models.Model):
board = models.ForeignKey(Board, on_delete=models.CASCADE)
admin = models.ForeignKey(User, on_delete=models.CASCADE)
text = models.CharField(max_length=300)
complete = models.BooleanField(default=False)
assigned_to = models.CharField(max_length=30)
views.py
def board_post_detail(request, board_id):
obj = get_object_or_404(Board, id=board_id)
taskobj= Task.objects.filter(board=obj)
context = {"object": obj, "tasks": taskobj}
return render(request, 'boards/board_post_detail.html', context)
board_post_detail.html
{% block content %}
<h1>{{ object.name}}</h1>
<p> {{tasks.text}}<p>
<p>Created by {{object.admin.username }}</p>
{% endblock %}
I realise that I needed to use a for loop to iterate throught the tasks.
{% block content %}
<h1>{{ object.name}}</h>
<ul>
{% for task in tasks %}
<li>{{ task.text }} is assigned to {{ task.assigned_to }}</li>
{% endfor %}
</ul>
<p>Created by {{object.admin.username }}</p>
{% endblock %}

Why is my code not rendering a list of table on my web page?

I have a model D100Generator with an incrementing primary key. I am trying to mimic the Django tutorial pt. 3, substituting a list of table names for the questions that should be rendered on the index.html page. When I run the code, I get a <ul> bullet point, but no text. Is my latest_table_list not being populated? Or is it I'm calling the wrong thing?
I am very new to Python, web development and Stack Overflow, so forgive me if the formatting and explanation is poor on this.
I suspect I'm not calling the table_name field correctly, but nothing I've tried has been able to work.
I tried setting the line item for the list as:
<li>{{ d100Generator.table_name }}</li>
and as:
<li>{{ d100Generator.table_name }}</li>
Neither of which will help display as desired.
The D100Generator Model
class D100Generator(models.Model):
d_100_id = models.AutoField(primary_key=True)
field_of_interest = models.ForeignKey(FieldOfInterest, on_delete=models.CASCADE)
subreddit_post_id = models.ForeignKey(Subreddit, on_delete=models.CASCADE, blank=True, null=True)
module_id = models.ForeignKey(Module, on_delete=models.CASCADE, blank=True, null=True)
generic_website_id = models.ForeignKey(GenericWebsite, on_delete=models.CASCADE, blank=True, null=True)
table_name = models.CharField('table name', max_length=100)
system = models.CharField(max_length=150)
genre = models.CharField(max_length=250)
chart_type = models.CharField('Die used', max_length=15)
chart_instructions = models.TextField('Chart instructions & explanation')
roll_1 = models.TextField('1', blank=True, null=True)
roll_2 = models.TextField('2', blank=True, null=True)
roll_3 = models.TextField('3', blank=True, null=True)
...
roll_110 = models.TextField('110', blank=True, null=True)
def __str__(self):
return self.table_name
#Views.py Entry for Index
from django.shortcuts import render
from .models import D100Generator
def index(request):
latest_table_list = D100Generator.objects.order_by('-d_100_id')[:5]
context = {
'latest_table_list': latest_table_list
}
return render(request, 'generators/index.html', context)
##Code on the index.html page itself
<h1>Welcome to Capstone Generators' homepage!</h1>
<br>
<h2>Recent topics added include:</h2>
<br>
<h2>Recent tables added include:</h2>
{% if latest_table_list %}
<ul>
{% for d_100_id in latest_table_list %}
<li>{{ D100Generator.table_name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No tables are available.</p>
{% endif %}
I have one table the has been manually added via the admin page, so the bulleted list should include the table name "Your elf learned over 25 years..."
Here you are using loop variable d_100_id but you are trying to access table_name with D100Generator
So change this to:
{% for d_100_id in latest_table_list %}
<li>{{ d_100_id.table_name }}</li>
{% endfor %}

How to display publisher name along with the book name,as the code i am using now shows only book names.//using html using django?

To display name of the books,code implemented is :
search_results.html :
{% if books %}
<p>Found {{ books|length }} book{{ books|pluralize }}.</p>
<ul>
{% for book in books %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>
{% else %}
Now my question is how to show publisher name of same book along with the book name?
modelss.py:
class publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
def __str__(self):
return self.name
class book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(author)
publisher = models.ForeignKey(publisher)
publication_date = models.DateField()
def __str__(self):
return self.title
You can do something like this:
{% for book in books %}
<li>{{ book.title }} - {{ book.publisher.name }}</li>
{% endfor %}
I also suggest you to use select_related for this situations because if you have N books this will result to N extra database queries.
I don't know how your view function looks like but if you want to list all the books along with the publisher informations then your ORM query in your view function should look like this:
books = book.objects.select_related("publisher").
P.S.
Your class names should follow InitialCaps/CapWords pattern as well. In your situation you should have class Publisher instead of class publisher and class Book instead of class book.

How to access and make use of html data in django?

I am having a hard time figuring out the right logic for my problem, i have 3 models,
class Item(SmartModel):
name= models.CharField(max_length=64,help_text="Name for this item e.g Hamburger")
price=models.DecimalField(max_digits=9,decimal_places=2)
optionalitems = models.ManyToManyField('optionalitems.OptionalItemCategory',null=True,blank=True)
class OptionalItems(SmartModel):
"""Optional items that belong to an item e.g topping that belongs to a pizza"""
name = models.CharField(max_length=20, help_text="Item name.")
price = models.DecimalField(max_digits=9, decimal_places=2, null=True,blank=True)
class OptionalItemCategory(SmartModel):
"""Category to which optional items belong"""
title = models.CharField(max_length=20,help_text="Category name")
optional_items = models.ManyToManyField(OptionalItems)
in my template,
{%for optionalcategory in optionalcategories %}
<h5 id="blah"> {{ optionalcategory.title}} </h5>
{% for optionalitem in optionalcategory.optional_items.all %}
<ul>
<input type="radio" value="radio" name="optional" value="op"><li id="item_appearence">{{optionalitem.name}}<span> {{optionalitem.price}}</span></li><a/>
</ul>
{% endfor %}
{% endfor %}
So for example an Item like a burrito will have an OptionalItem steak or chicken.I am able to access the Item like so item = get_object_or_404(Item, pk=obj.id) but my problem is i cannot figure out how to capture the OptionalItem. I want to be able to access the OptionalItem, i want to obtain the value of the radio button and its attributes. its kind of tricky.
Your code is inconsistent and that makes it hard to read, understand and work with. Some advice, clean it up. Something like this:
class Category(models.Model):
name = models.CharField(max_length=200)
class Option(models.Model):
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)
class Item(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)
options = models.ManyToManyField(Option)
Than you need a from and a view. As I interpret your question: you want a form to select a option for an Item. So the code below will render all options and the widget RadioSelect() lets the user select one item. But why use radiobuttons? If an Item has a relation to one Option, than the Item model should have a foreignKey not M2M!
Form:
class ItemForm(ModelForm):
options = forms.ChoiceField(widget=forms.RadioSelect())
class Meta:
model = Item
fields = ( 'options', )
View:
from django.shortcuts import render
from django.http import HttpResponseRedirect
def your_view(request, id):
item = Item.objects.get(pk=id) # Your item object.
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
options = form.cleaned_data['options']
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ArticleForm(instance=article)
return render(request, 'contact.html', {
'form': form,
})
Template:
{% for obj in item.options_set.all %}
{{ obj.name }} {{ obj.price }}
{% endfor %}
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
I dind't test the code. But this should get you started. The documentation is your friend:
https://docs.djangoproject.com/en/1.5/topics/forms/
https://docs.djangoproject.com/en/1.5/#forms
In your template, you can simply render the price. I'd write a method in the Item model, that formats the OptionalItems the way you like.
i.e.
class Item(SmartModel)
...
def get_optional(self):
return ','.join([a.optionalitems for a in self.optionalitems.all()])
Of course, you should change that method to have it format the way you'd like.
If you pass a queryset of Items to your template, you can do something like the following:
{% for item in items %}
Name: {{ item.name}}
Price: {{ item.price }}
Optional Items: {{ item.get_optional }}
{% endfor %}