related model fields not showing - python

I am having a trouble understanding what is wrong inside my code. Please can anybody tell me why the fields in locations = Location.objects.filter(user=add_profile.user) are not displayed in my html page.
models.py
class Location(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
my_location = models.CharField(max_length=120, choices=LOCATION_CHOICES)
update_date = models.DateField(auto_now=True, null=True)
date = models.DateField()
def __str__(self):
return self.my_location
class UserProfile(models.Model):
user = models.OneToOneField(User)
user_base = models.CharField(max_length=120, choices=LOCATION_CHOICES)
user_position = models.CharField(max_length=120)
user_phone = models.CharField(max_length=50)
first_name = models.CharField(max_length=120, null=True)
last_name = models.CharField(max_length=120, null=True)
slug = models.SlugField()
def save(self, *args, **kwargs):
self.slug = slugify(self.user)
super(UserProfile, self).save(*args, **kwargs)
def __unicode__(self):
return self.user.username
views.py
#login_required
def details(request, user_slug):
add_profile = UserProfile.objects.get(slug=user_slug)
locations = Location.objects.filter(user=add_profile.user)
print(locations)
context = {'add_profile': add_profile, locations: "locations"}
return render(request, 'details.html', context)
Though, the print(locations) is printing the requested data inside my cmd.
html code
{% for l in locations %}
<ul>
<li> {{l.my_location}} </li>
</ul>
{% endfor %}
My problem is that I am not having any an error to do know where to look.
Thank you.

Instead of
context = {'add_profile': add_profile, locations: "locations"}
should be
context = {'add_profile': add_profile, 'locations': locations}
Instead of using locations as value for context, you've used it as key and as value just the string "locations".

Related

reverse_lazy with no arguments not found

reverse_url is workin fine with a url that has-no/int:pk but does not work with a url that has /int:pk throws an error NoReverseMatch: Reverse for 'read_bty' with no arguments not found. 1 patterns tried:['read_bty/(?P[0-9]+)$']. The first (class=HBTYIndex) lists all customers created from the (class=HBTYCreateView) and the (class=HBTYReadView) displays the customers order records, the last (class=HBTYOrderView) is supposed to create an order and reverse_lazy to the url 'read_bty' but it keeps on throwing the above error when creating an order. Tried to change from int:pk to int:id still getting the same error. if i change the reverse_lazy to point to a url with no int:pk the record gets added and i get redirected to that page instead of staying on the same page and showing the new added record.
Views.py
class HBTYIndex(generic.ListView):
model = HbtyCustomers
context_object_name = 'bty'
paginate_by = 100
template_name = 'accounts/modals/bty/clientindex.html'
ordering = ['-id']
success_url = reverse_lazy('btylist')
def get_queryset(self):
qs = self.model.objects.all()
p_f = CustomerFilter(self.request.GET, queryset=qs)
return p_f.qs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = CustomerFilter(self.request.GET, queryset=self.get_queryset())
return context
# Create Customer
class HBTYCreateView(BSModalCreateView):
template_name = 'accounts/modals/bty/create_hbty.html'
form_class = btyForm
success_message = 'Success: Client was created.'
success_url = reverse_lazy('btylist')
# View Customer Orders History
class HBTYReadView(generic.ListView):
model = HbtyOrder
context_object_name = 'bty'
template_name = 'accounts/modals/bty/read_hbty.html'
allow_empty = False
pk_url_kwargs = 'hbtycustomer_pk'
paginate_by = 100
ordering = ['-id']
success_url = reverse_lazy('read_bty')
def get_queryset(self):
qs = self.model.objects.filter(hbtycustomer_id=self.kwargs['pk'])
p_f = HbtyOrdersFilter(self.request.GET, queryset=qs)
return p_f.qs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = HbtyOrdersFilter(self.request.GET, queryset=self.get_queryset())
return context
# Create New Order in the customer history page
class HBTYOrderView(BSModalCreateView):
template_name = 'accounts/modals/bty/create_hbty.html'
form_class = HairbtyOrderForm
success_message = 'Success: Order was created.'
success_url = reverse_lazy('read_bty')
read_hbty.html
<div class="row">
<div class="col-12 mb-3">
{% if filter.qs %}
{% include "accounts/modals/hairbty/vw_more.html" %}
{% else %}
<p class="no-books text-primary">No Client addeds yet.</p>
{% endif %}
</div>
</div>
Models.py
class HbtyCustomers(models.Model):
name = models.CharField(max_length=200, blank=False, null=True)
address = models.CharField(max_length=200, blank=False, null=True)
date = models.IntegerField(blank=False, null=True)
remarks = models.CharField(max_length=200, blank=False, null=True)
def __str__(self):
return self.name
class HbtyCategories(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class HbtySubcategories(models.Model):
categ = models.ForeignKey(HbtyCategories, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class HbtyOrder(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered'),
)
categ = models.ForeignKey(HbtyCategories, on_delete=models.SET_NULL, blank=True, null=True)
subcateg = models.ForeignKey(HbtySubcategories, on_delete=models.SET_NULL, blank=True, null=True)
hbtycustomer = models.ForeignKey(HbtyCustomers, on_delete=models.SET_NULL, blank=True, null=True)
price = models.IntegerField(null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
def __str__(self):
return str(self.id)
Urls.py
path('btylist/', views.HBTYIndex.as_view(), name="btylist"),
path('create_btycustomer/', views.HBTYCreateView.as_view(), name='create_btycustomer'),
path('create_btyorder/', views.HBTYOrderView.as_view(), name='create_btyorder'),
path('read_bty/<int:pk>', views.HBTYReadView.as_view(), name='read_bty'),
As you can tell from your urls.py, read_bty/HBTYReadView wants to see an int value named pk.
When you call that url in HBTYOrderView via reverse_lazy, you don't provide it, hence the error.
You can build out the success_url by creating a get_success_url method in your HBTYOrderView, rather than using a success_url property, something like:
def get_success_url(self):
return reverse_lazy('read_bty',kwargs={"pk": self.request.user.id} )
(I am assuming here that the ID that read_bty wants is the request.user.id )

Compare object with string in django template

I have two models which I want to output on a template. But only if the parent class object matches to the child class object.
{% for market in markets %}
{% if object.market|slugify == market.market %}
>>> DO SOMETHING <<<
{% endif %}
{% endfor %}
The problem is when I use slugify on the Object it's giving me a string which starts with a small letter but market.market outputs a string with a capital letter.
Do someone know a solid solution for that?
UPDATE:
my Views:
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
def market_list(request):
context ={
'markets': Market.objects.all()
}
return render(request, "market-list.html", context)
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()
description = models.TextField()
image = models.ImageField()
def __str__(self):
return self.title

How to show all foreign key attribute in Django template?

I want to fetch all the foreignkey table's attribute and show it in my HTML template. Here is my code in models, views and in the template:
models.py:
class OrderDashboard(models.Model):
title = models.CharField(max_length=100,default=None)
single_slug = models.SlugField(max_length=100, default=1)
description = models.TextField(max_length=1000)
thumb = models.ImageField()
date = models.DateField()
def __str__(self):
return self.title
class OrderScenario(models.Model):
webshop = models.CharField(max_length=100)
title = models.ForeignKey(OrderDashboard, default=None, on_delete=models.SET_DEFAULT)
order_qty = models.TextField(max_length=10)
order_date = models.DateField()
current_status = models.CharField(max_length=100)
ticket = models.CharField(max_length=200)
remark = models.TextField()
class Meta:
verbose_name_plural = "Scenario"
def __str__(self):
return self.webshop
Views.py:
def single_slug(request, single_slug):
report = OrderDashboard.objects.get(single_slug=single_slug)
return render(request, 'order_dashboard/report.html', {'report': report,
'OrderScenario': OrderScenario.objects.all})
I only want to view all the scenarios added in OrderScenario with respect to Title in OrderDashboard.
You should use backward relationship here; if you are passing the slug through the url, you can use:
views.py:
def single_slug(request, slug): # why you have self as the first argument?
report = OrderDashboard.objects.get(single_slug=slug)
return render(request, 'order_dashboard/report.html', {'report': report}
report.html:
{{ report.title }}
</p>Order Scenarios:</p>
{% for scenario in report.orderscenario_set.all %}
{{ scenario }}
{% endfor %}

ValueError at /author/admin/ in Django

I have the following blog project :
urls.py conf :
url(r'^author/(?P<author>\w+)/$', views.getAllPosts, name='grabAuthorPosts')
posts/models:
class Post(models.Model):
title = models.CharField(max_length=200)
summary = models.CharField(max_length=500, default = True)
body = models.TextField()
pub_date = models.DateTimeField(default=timezone.now)
category = models.ManyToManyField('Category')
author = models.ForeignKey(User, default=True)
slug = models.SlugField(max_length=100, unique=True, blank=True)
def __str__(self):
return self.title
def slug(self):
return slugify(self.title)
posts/views:
def getAllPosts(request, author=False):
latest_posts = Post.objects.all().order_by('-pub_date')
comments = Comment.objects.all().order_by('-pub_date')
author_posts = User.objects.get(id=author)
author_posts = author_posts.post_set.all()
context = {
'latest_posts':latest_posts,
'comments':comments,
'author_posts':author_posts
}
return render(request, 'posts/getAllPosts.html', context)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
templates/posts/getAllPosts:
<a href={% url 'grabAuthorPosts' author=post.author.username %}>
{{post.author}}</a>
I am trying to make it so that when the post.author link is clicked, the user will be taken to a page consisting of posts related to that particular author. The link formulation itself seems ok, as when clicked on a post created by admin, the url reads localhost/author/admin/
I believe my problem is in getting the context variable author_posts to work. I'm new to Django so any explanation greatly appreciated.
latest_posts, as well as author=False is used elsewhere in the template to get all posts regardless of author, which works fine.
The error is :
ValueError at /author/admin/
invalid literal for int() with base 10: 'admin'

Finding the Cross-Section of two List views in one Django template

I have two models that feed one view.
models.py
class Item(models.Model):
item_name = models.CharField(max_length=100)
item_type = models.ForeignKey(Item_type, on_delete=models.SET_NULL, null=True)
owned_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)****
added_at = models.DateTimeField('date item added')
updated_at = models.DateTimeField('last update')
def __str__(self):
return self.item_name
class Item_status(models.Model):
item = models.ForeignKey(Item, on_delete=models.SET_NULL, null=True)
borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
loaned_at = models.DateTimeField(default=None, blank=True, null=True)
due_back = models.DateTimeField(default=None, blank=True, null=True)
def __time__(self):
return self.loaned_at
def itemname(self):
return (self.item.item_name)
I have the following view
views.py
class LoanedItemsByUserListView(LoginRequiredMixin,generic.ListView):
model = Item_status
template_name ='catalog/item_status_list_borrowed_user.html'
paginate_by = 10
def get_queryset(self):
return Item_status.objects.filter(borrower=self.request.user).order_by('due_back')
def get_context_data(self, **kwargs):
context = super(LoanedItemsByUserListView, self).get_context_data(**kwargs)
context['Owned_list'] = Item.objects.filter(owned_by=self.request.user, item_type = 1)
context['Loaned_list'] = Item_status.objects.exclude(borrower=self.request.user).exclude(borrower__isnull=True)
return context
I would like to find the cross section of the 'Owned_list' and the 'Loaned_list' in a single template
Something like
<h2>Loaned Books</h2>
{% if Owned_list %}
<ul>
{% for thing in Owned_list.item_name and in Loned_list.item.item_name %}
<li>
{{thing}}
</li>
{% endfor %}
</ul
{% else %}
<p>There are no books in the library.</p>
{% endif %}
I have take a look at the django documentation here https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-display/, and around SO but not found exactly what I am looking for.
Thanks!

Categories