How to use string of <li> in django view? - python

I am building a blog where users can click on several <li> items in the sidebar to show blog posts according to the clicked category.
The desired outcome is somewhat to the official documentation, so that I will end up with /blog/category and the according blog posts rendered.
The problem is that if I visit the main page (or http://127.0.0.1:8000/ in development) it raises an error
render_blog() missing 1 required positional argument: 'category'
So how can I use the view render_blog both for the main page and for the categories clicked to render the according blog posts?
html
<li class="navigation-item" id="spotlights-item">
<div id="spotlights-ctn">Hot Stocks<img id="fire-icon" src="{% static 'images/fire.svg' %}" alt="finsphere.io"></div>
</li>
urls
urlpatterns = [
path('AsiaPacific/<category>', render_blog, name='AsiaPacific'),
url(r'^$', render_blog, name='render_blog'),
]
views.py
def render_blog(request, category):
category = category
if not category:
# Main blog as landing page
# Get 5 latest posts and order by publish date, newest first
posts = Post.objects.filter(publish_date__lte=now).order_by('-publish_date')[:5]
return render(request, 'blog/blog.html', {'posts': posts})
else:
# Blog displayed as Category Selection
posts = Post.objects.filter(categories__title=category, publish_date__lte=now)
return render(request, 'blog/blog.html', {'posts': posts})

Im not 100% sure I'm following, but you don't have to use the href on an anchor tag to link anywhere. You can just set href="" and give every link a class such as "category-link". Then tie your ajax onclick event to the class, and have the code first pull the text or another attribute from the link and submit it as a variable:
$('.category-link').on('click', function() {
var link = $(this);
var page = link.data('page');
var category = link.data('category');
$.ajax({
type: 'post',
url: '/lazy_load_posts/',
data: {
'page': page,
'category': category,
'csrfmiddlewaretoken': window.CSRF_TOKEN // from blog.html
},
(...)

Related

why my dropdown menu not working on some page

I tried to learn django a few day ago and make a simple website use that, but for a reason my dropdown in home page didn't work but in another page it's work properly.
Here my html template for that
<div class="dropdown-menu">
{% for category in links %}
<a class="dropdown-item" href="{{ category.get_url }}">{{category.category_name}}</a>
{% endfor %}
</div>
and here my code for django urls.py
urlpatterns = [
path('', views.store, name='store'),
path('<slug:category_slug>/', views.store, name='product_by_category'),
]
and here my code for links references
def menu_links(request):
links = Category.objects.all()
return dict(links = links)
i don't know why in my home page the dropdown button didn't work but in another page it work. i tried to find on my navbar templates and i think there is no problem there but the dropdown still not working and i tried to find on settings.py(to check installation app) but i did it
views.py
def home(request):
products = Product.objects.all().filter(is_available = True)
context = {
'products' : products,
}
return render(request, 'home.html', context)
anyone have idea where the problem is?
The reason why my dropdown not work in some page is because i'm include header tag in my home.html, even it's already in my base.html template
If someone have similar problem please check your page maybe you make some mistake like me

Django fails at properly redirecting from one view to another

I have a search bar on the side of the webpages of the app I'm working on, what I'm trying to do is have my search view take in the user's query, compare it with a list of entries and if what the user typed in matches the title of any of the entries available, search should redirect to another view called title which handles rendering the HTML file of the entry the user searched for along with matching it with the appropriate URL (i.e if the user searches for the Django entry, title renders HTML file of said entry and assigns it the URL "example.com/Django")
The problem lies in the fact that every time i redirect from search to title, title renders the HTML file reserved for the case in which no entry matches what the user searched for, no matter whether the entry is available or not.
It should also be noted that the path for the search view is a mess. if i write the path like that path("<str:search>", views.search, name="search") i get a NoReverseMatch error saying that Django was expecting an argument but received none, but path("search", views.search, name=search) causes the rendered error page to have the URL "example.com/search" which is not what i want, i want it to redirect to title so that the title view assigns the correct URL.
i am new to Django so my apologies for the long question, but I've been cracking at this problem for days with no use, Below is the code for both title and search views, urls.py and the HTML code of the search bar (the form). Please do ask for more info should you need it.
Thank you in advance for your help.
HTML
<form action="{% url 'wiki:search' %}" method="POST">
{% csrf_token %}
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
views.py
def title(request, title):
entry = util.get_entry(title)
if entry == None:
return render(request, "encyclopedia/error.html")
else:
return render(request, "encyclopedia/entry.html", {
"entry": entry,
})
def search(request):
if request.method == "POST":
query = request.POST["q"]
entries = util.list_entries
if query in entries:
if util.get_entry(query) == None:
return render(request, "encyclopedia/error.html")
else:
return redirect('wiki:title', title=query)
else:
return render(request, "encyclopedia/index.html")
urls.py
app_name = "wiki"
urlpatterns = [
path("", views.index, name="index"),
path("<str:title>", views.title, name="title"),
path("search", views.search, name="search")
]

how to make sub pages url in django

In my online store django project, I want to create a sub-page which shows the details of a product that is listed in a page.
in urls.py I created the urls for both pages like bellow:
path('wwqm', views.water_quality_sensor , name='wwqm'),
path('wwqm/<str:water_sensor_title>', views.water_sensor_item, name='water_sensor_item'),
in this scenario, a bunch of items are being shown in wwqm. user click on a product and the water_sensor_item should load up.
I know its not important but here is views.py:
def water_quality_sensor(request):
queryset_list = Water_quality_sensor.objects.order_by('-product_name').filter(is_published=True)
context = {
'water_quality_sensor': queryset_list,
}
return render(request, 'products/water_quality_sensor.html', context)
def water_sensor_item(request, water_sensor_title):
water_sensors = get_object_or_404(Water_quality_sensor, title=water_sensor_title)
context = {
'water_sensors': water_sensors
}
return render(request, 'products/water_sensor_item.html' , context)
I try to build the url for each item based on a parameter that is passed to its view(products title).
In my templates, I try to create a link like the following:
<a href="{% url 'water_sensor_item' w_q_sensor.title %}" class="card hoverable mb-4 text-dark" >
one my products' title is 3725. when I click on that product in the main page, I get the following error:
Django Version: 3.1.2
Exception Type: NoReverseMatch
Exception Value: Reverse for 'water_quality_sensor' not found. 'water_quality_sensor' is not a valid view function or pattern name.
What am I doing wrong?
in your urls.py
path('wwqm', views.water_quality_sensor , name='wwqm'),
you used name wwqm. But it looks like somewhere in your template (most likely water_sensor_item.html), you have something similar to :
<a href="{% url 'water_quality_sensor' %}"
Change it to wwqm or change name in urls.py
UPDATE
It is better to use <str:title><int:pk> in your urls, to avoid when you have the same name in two products. pk is unique.
in your urls.py
path('wwqm/<str:water_sensor_title><int:pk>', views.water_sensor_item, name='water_sensor_item'), # add <int:pk>
in your template:
# since url is taking both title and pk arguments, you need to provide both of them.
<a href="{% url 'water_sensor_item' title= w_q_sensor.title pk=w_q_sensor.pk %}" class="card hoverable mb-4 text-dark" >
in your view:
def water_sensor_item(request, water_sensor_title, pk): # added pk
water_sensors = get_object_or_404(Water_quality_sensor, pk=pk) # use pk to get the object
context = {
'water_sensors': water_sensors
}
return render(request, 'products/water_sensor_item.html' , context)

How to have Django templates display slugs

Hi guys i am new to django...i been watching youtube videos and reading books on Django but am still struggling with templates. I am working on a ecommerce project and i would love a bit of help with templates. So i want my template to display a list of categories as links on a sidebar. I have defined a slug field in my category models and i have managed to map a url...but i am still not getting a list of categories on my index page sidebar.
This is my url pattern and this is working perfect. When i click 127.0.0.1.000/food it's working (food is a category)
path('<slug:category_slug>/', views.category, name='category'),
the view function
def category(request, category_slug):
"""Defines category views"""
categories= get_object_or_404(Category, slug= category_slug)
context = {'categories': categories}
return render(request, "categories_list.html", context)
This is the categories_list.html template that i need help with
<h3> Shop by Category </h3>
{% if category in categories %}
<li>
{{category.name}}
</li>
{% endif %}
My wish is to have the categories displayed on the sidebar of my index page as links. I have used {% include 'category_list.html' %} on my index page template, and its only displaying the Shop by Category heading instead of the categories when i am on the index page. I have tried the for loop in my template but if didn't work, it kept on saying category object not iterable...so i ended up using the if statement. Any help will be appreciated
get_object_or_404() method returns single instance or None if it is not found.
You can't iterate that way on object.
Try next
View
def category(request, slug):
"""Defines category views."""
return render(request, 'categories_list.html', {'category': get_object_or_404(Category, slug=slug)})
Template
{{ category.slug }}

Django Navbar Categories Link Issues

When I click the categories link in the menu, I get the following error.
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/post/categorylist/
Raised by: post.views.post_detail
No Post matches the given query.
models.py
def get_categorylist_url(self):
return reverse('post:categorylist', kwargs={'slug': self.slug})
views.py
def post_categorylist(request, slug):
if not request.user.is_superuser:
raise Http404()
post = get_object_or_404(Post, slug=slug)
post.categorylist()
return redirect('post:categorylist')
urls.py
path('categorylist/',views.post_categorylist, name='categorylist'),
header.html
<li>Kategoriler</li>
categorylist.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
Test message.
</body>
</html>
If your root urls.py is as posted you should be going to http://127.0.0.1:8000/categorylist/ because that is the path the URL is linked to.
However, you've got a slug in your views but it isn't handled by your URLs so you might have a problem there as well. Because your view expects a slug, try changing your view to look for it;
path('categorylist/<slug:slug>/',views.post_categorylist, name='categorylist'),
Your error raised by: post.views.post_detail so your url is wrong.
You want get slug argument but your url hasn't any slug parameter. Firstly you should fix your url path.
Than, If you want when user click to x category link and get products in x category, let's make example:
Firstly create this view:
views.py:
def category_list(request):
# Category loops on index page.
category_list = Category.objects.filter()
context = {
"category_list": category_list,
}
return context
Than, we should add this context to our context processor for accessing everywhere (because it is navbar, so navbar will be top of every page, right?)
settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["templates"],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
************************************,
'YOURMODELNAME.views.category_list',
],
},
},
]
Finally, you will access all categories on your project, just add this code on your template:
navbar.html:
{% for category in category_list %}
<a href="{% url 'categories' slug=category.slug %}">
{{ category.name }} <!--You can use ul-li for displaying them-->
</a>
{% endfor %}
Ok, we displayed our categories, but when user click any link, should redirect to filtered list in clicked category. So we should create page and link for this page:
views.py:
def category_list(request, slug):
category = Category.objects.get(slug=slug)
posts = Post.objects.filter(category=category)
context = {
"posts": posts, #filtered products
}
return render(request, "posts_in_category.html", context)
urls.py:
path('category/<slug:slug>', views.category_list, name="category_list")
posts_in_category.html:
{% for post in posts_in_category %}
{{ post.name }}
{% endfor %}
If you miss anything, I can explain in Turkish ;)
I'm using this codes. How do I add links?
views.py
def categorylist(request):
# Category loops on index page.
categorylist = Category.objects.filter()
context = {
"categorylist": categorylist,
}
return render(request, "post/categories.html", context)
categories.html
{% for post in categorylist %}
{{ post.name }}
{% endfor %}

Categories

Resources