I have some problem with fronend, select tag html code. I have creating sorting option.
All is working fine if it is like a list or block (depending from villing), but then i truing to make a dropdown and add select tag all categorys gone , only ALL STATUS.
Could you please explain me there is my mistake and why ?
MY HTML
<div class="top-selector-right">
<select name="status-candidate">
{% if stat_selected == 0 %}
<div class="top-selector-right">
<option><a class="nav-link"><i class="fa-solid fa-bars"></i> ALL STATUS</a></option>
</div>
{% else %}
<div class="top-selector-right">
<option><a class="nav-link" href="{% url 'candidates' %}"> ALL STATUS</a></option>
</div>
{% endif %}
{% for s in status %}
{% if s.pk == stat_selected %}
<option><a class="nav-link" href="{{ s.get_absolute_url }}">{{ s.ff_status_id }}</a></option>
{% else %}
<option><a class="nav-link" href="{{ s.get_absolute_url }}">{{ s.ff_status_id }}</a></option>
<!-- <a class="nav-link" href="{{ s.get_absolute_url }}"><i class="fa-solid fa-ellipsis-vertical"></i> {{ s.ff_status }}</a>-->
{% endif %}
{% endfor %}
</select>
</div>
My views.py
def show_status(request, np_ff_status_id):
new_candidates = NewPlacement.objects.filter(np_ff_status_id=np_ff_status_id)
status = SatusActivity.objects.all()
context = {
'new_candidates': new_candidates,
'status': status,
'stat_selected': np_ff_status_id,
}
return render(request, 'placements/candidates.html', context=context)
models.py Just part of the models.py
class SatusActivity(models.Model):
NEW = 'New placement'
CANCELED = 'Canceled'
CONTACTED = 'Contacted'
WAITING = 'Waiting answer for the client'
ACCEPTED = 'Accepted'
DECLINED = 'Declined'
ONHOLD = 'On hold'
NOTANSWERING = 'Not answering'
STATUS = [
(NEW, 'New placement'),
(CANCELED, 'Canceled'),
(CONTACTED, 'Contacted'),
(WAITING, 'Waiting answer for the client'),
(ACCEPTED, 'Accepted'),
(DECLINED, 'Declined'),
(ONHOLD, 'On hold'),
(NOTANSWERING, 'Not answering'),
]
ff_status = models.CharField(max_length=30, choices=STATUS, default=NEW, db_index=True)
def __str__(self):
return self.ff_status
def get_absolute_url(self):
return reverse('status', kwargs={'np_ff_status_id': self.pk})
FULL urls.py on APP
urlpatterns = [
path('candidates', views.candidates, name='candidates'),
path('candidates_easy', views.candidates_easy, name='candidates_easy'),
path('new', views.placement, name='new'),
path('post/<int:id>/', show_post, name='post'),
path('category/<int:np_ff_location_id>/', show_category, name='category'),
path('status/<int:np_ff_status_id>/', show_status, name='status'),
]
Related
I need to open the same form multiple times while looping trough some items.
This is the form:
class CancelRefundForm(forms.forms.Form):
cancel = forms.BooleanField(label='Check to cancel the refund', required=True ,widget=forms.CheckboxInput(attrs={
'class': 'hidden-checkbox',
'name': 'hiddenCheckBoxName'
}
))
item = forms.IntegerField(
required=True,
widget=forms.NumberInput(attrs={
'class': 'cancel-item-input',
'value': '',
'type': 'hidden'
}),
)
This is the HTML:
<div class="order-items-display">
{% for item in order.orderitem_set.all %}
<div class="single-order-item">
<span >
<a href="{{ item.item.get_absolute_url }}">
<img src="../../../media/{{ item.item.main_image }}" alt="{{ item.item.title }} image">
</a>
</span>
<span class="order-item-details">
<h3><a href="{{ item.item.get_absolute_url }}">
{{ item.item.title }}
{% if item.replica %}
<small>(Replica)</small>
{% endif %}
</a></h3>
<p><strong>Price: </strong>{{ item.old_price }}€</p>
{% if item.quantity > 1 %}
<p><strong>Quantity: </strong>{{ item.quantity }}</p>
<p><strong>Total: </strong>{{ item.get_old_total_price }}€</p>
{% endif %}
{% if order.refund_deadline > nowDate %}
<p><b>The deadline for requesting a refund ends in {{ order.refund_deadline }}(30 days)</b></p>
{% else %}
<p><b>The deadline for requesting a refund ended in {{ order.refund_deadline }}.</b></p>
{% endif %}
<button class="myBtnPri update-cart" data-product="{{item.id}}" data-action="add">
<a class="mySecLink" href="#">
Buy Again
</a>
</button>
{% if item.refund_requested %}
<p><b>Refund requested: </b> {{ item.refund_requested }}</p>
<p><b>Refund granted: </b> {{ item.refund_granted }}</p>
<form action="{% url 'order-details' order.slug %}" method="POST" class="cancel-form">
{% csrf_token %}
{{ cancelForm.item }}
<label for="{{ cancelForm.cancel.id_for_label }}" class="myCheckbox">
{{ cancelForm.cancel }}
<div class="checkbox-box"></div>
<b>Check to cancel the refund</b>
</label>
<button class="myBtnPri cancel-btns" type="submit" data-item="{{ item.item.id }}">
<a class="mySecLink">
Cancel Refund
</a>
</button>
</form>
{% elif item.refund_requested == False and order.refund_deadline > nowDate %}
<button class="myBtnPri refundBtn" data-item="{{ item.item.id }}" data-qty="{{ item.quantity }}">
<a class="mySecLink" href="#">
Refund?
</a>
</button>
{% else %}
<p>Since the refund deadline is over you can no longer refund this Iitem.</p>
{% endif %}
</span>
</div>
{% endfor %}
</div>
In this html I display the items ordered by the user from an old order he made where the user can choose to refund a specific item. If the the user asks for a refund the template will then display a form that asks if the user wants to cancel the refund.
If the user decides to refund more than one item from the same order I will have to display the cancelForm one time for each item.
In my views I have:
def order_details_view(request, slug):
dataCart = cartData(request)
cancelForm = CancelRefundForm()
# toRefundItems = len(OrderItem.objects.filter(order = order, refund_requested = True))
# cancelRefundFormSet = formset_factory(CancelRefundForm, extra=toRefundItems)
# formset = cancelRefundFormSet()
order.refund_deadline = order.refund_deadline.astimezone(timezone.utc).replace(tzinfo=None)
if request.method == 'POST':
cancelForm = CancelRefundForm(request.POST)
# formset = cancelRefundFormSet(request.POST)
# CANCEL REFUND FORM LOGIC
if cancelForm.is_valid():
itemId = cancelForm.cleaned_data['item']
orderItem = OrderItem.objects.get(order = order, item = itemId)
if orderItem.refund_requested == True:
orderItem.refund_requested = not cancelForm.cleaned_data['cancel']
orderItem.save()
refund = RefundedItems.objects.get(order = order, item = orderItem)
refund.delete()
order.save()
messages.success(request, f'You successfully canceled the refund of the item {orderItem.id}.')
return redirect(f'/order_details/{order.slug}/')
context = {
'order': order,
'cancelForm': cancelForm,
# 'cancelForm': formset,
'nowDate': datetime.datetime.now(),
'cartItems': dataCart['cartItems'],
}
return render(request, 'users/order_details.html', context)
As you can see by the comments I tried to use formset_factory, but it did not work
because I needed to open more than one form.
And the way I have above its also not working properly. The multiple forms are displayed in the template but when I check the box from any form it just updates the first one.
Should I create another view and template to deal with this using formset's? Or am I missing something?
Thanks
To anyone that has the same question, I decided to make one form for each item I needed using Javascript then I displayed it in the template and connected the form to a new view that only handles the cancel refund form's information.
I am trying to use Pagination with the Django Filter function, But I am getting this error.
http://127.0.0.1:8000/product_search/?page=2&search=e
Cannot use None as a query value
product = Product.objects.filter(productName__contains=name)
Here is The view.py function
def searchProduct(request):
name = request.POST.get("search", None)
try:
product = Product.objects.filter(productName__contains=name)
paginator = Paginator(product, 2)
page = request.GET.get('page')
page_product = paginator.get_page(page)
if page_product:
context = {
'searchResults': page_product,
'name': name
}
return render(request, "Amazon/searchResult.html", context)
else:
return render(request, "Amazon/searchResult.html", {'message': "No Product Found"})
except Product.DoesNotExist:
return HttpResponse("Page Not Found")
Here is HTML/Jinja code
<nav aria-label="...">
{% if searchResults.has_other_pages %}
<ul class="pagination justify-content-center">
{% if searchResults.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ searchResults.previous_page.number }}&search={{ name }}" tabindex="-1">
Previous</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" tabindex="-1">Previous</a>
</li>
{% endif %}
{% for i in searchResults.paginator.page_range %}
{% if product.number == i %}
<li class="page-item active">
<a class="page-link" href="#">{{ i }}</a>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="?page={{ i }}&search={{ name }}">{{ i }}</a>
</li>
{% endif %}
{% endfor %}
{% if searchResults.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ searchResults.next_page_number }}&search={{ name }}">Next</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link">Next</a>
</li>
{% endif %}
</ul>
{% endif %}
</nav>
I have a rough Idea that no value is getting passed in filter function that is why it is showing this error. So, any Idea how can I resolve it??
Simply filter your queryset when name is provided, eg.
name = request.POST.get('search')
page_number = request.GET.get('page')
products = Product.objects.all()
if name: # only filter when name provided
products = products.filter(productName__contains=name)
try:
page = Paginator(products, 2).get_page(page_number)
except EmptyPage:
return render(request, "Amazon/searchResult.html", {'message': "No Product Found"})
return render(request, "Amazon/searchResult.html", {
'searchResults': page_product,
'name': name
})
So I am trying to display a badge notifier on my inbox only if I have > 0 messages. For some reason, my if statement isn't working. I'm not sure if it's a syntax issue or if my logic is wrong. I am returning a count of my messages, which is displaying and working correctly. I simple want to run my if statement on that count.
base.html/ message counter part
{% if unread_messages > 0 %}
<li>
<a ref = 'stylesheet' href="{% url 'dating_app:conversations' user.id %}" type="text/css" class="notification">
<span>Inbox</span>
<span class="badge">{% unread_messages request.user %}</span>
</a>
</li>
{% else %}
<li>
<a ref = 'stylesheet' href="{% url 'dating_app:conversations' user.id %}">
<span>Inbox</span>
</a>
</li>
{% endif %}
unread_messages_counter.py
from django import template
from dating_app import models
register = template.Library()
#register.simple_tag
def unread_messages(user):
return user.receiver.filter(viewed=False).count()
You need to call your custom tag with the as argument so that you can store the result in a variable that you can then use in your conditions
{% unread_messages request.user as user_unread_messages %}
{% if user_unread_messages > 0 %}
{% endif %}
{{ user_unread_messages }}
The docs for as are at the bottom of this section
Main problem is that user is not defined. So, you have to include tag with context and simple_tag could not do so. Therefore, you have to use inclusion_tag(to take context i.e, request(in this case). Refs_inclusion
#register.inclusion_tag('pathwhere_you_rendered.html', takes_context=True)
def unread_messages(context):
request = context['request'] // request from
try:
unread_messages = request.user.receiver.filter(viewed=False).count()
except:
// When user is not logged in
unread_messages=0
return {'unread_messages':unread_messages}
pathwhere_you_rendered.html could be like, home/base.html
I can iterate over different products using
<li
{ % if not category % }class = "selected" {% endif % }>
All
</li>
{% for c in categories %}
<li {% if category.slug == c.slug %}class="selected"{% endif %}>
{{ c.name }}
</li>
{% endfor %}
this is my code for a dropdown list, but it is not showing anything after books.
<li class="nav-item dropdown ">
<a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">
Categories
</a>
<p class=" dropdown-menu ">
<a class="dropdown-item" href="{% url 'shop:product_list' %}">All</a>
<a class="dropdown-item" href="#">Electronics</a>
<a class="dropdown-item" href="#">Books</a>
<ul>
<li {% if not category %}class="selected"{% endif %}>
All
</li>
{% for c in categories %}
<li {% if category.slug == c.slug %}class="selected"{% endif %}>
<a class="dropdown-item" href="{{ c.get_absolute_url }}">{{ c.name }}</a>
</li>
{% endfor %}
</ul>
</p>
</li>
I want to add this code to my dropdown list
<li {% if not category %}class="selected"{% endif %}>
All
</li>
{% for c in categories %}
<li {% if category.slug == c.slug %}class="selected"{% endif %}>
<a class="dropdown-item" href="{{ c.get_absolute_url }}">{{ c.name }}</a>
</li>
{% endfor %}
but this code is showing nothing in the drop down list
my views.py file:
from django.shortcuts import render, get_object_or_404
from .models import Category, Product
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request, 'shop/products/list.html', {
'category': category,
'categories': categories,
'products': products
})
my models.py:
from django.db import models
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_list_by_category', args=[self.slug])
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products', on_delete=True)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
image = models.ImageField(upload_to='products/%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)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
--------------------------------------------------------------------------------
I think that it is because you are nesting a ul inside a p and it is invalid HTML.
I have a template which contains:
Example 1:
{% if player_mark %}
{% if commun.intern > threshold %}
<a class="btn btn-success btn-sm pull-right"
href="{% url 'games:map:town_map' map_id=map.id home_id=homecall.id %}"><i
class="fa fa-phone-square fa-fw"></i>
{{ title_header }}</a>
{% endif %}
{% endif %}
Example 1 Context:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['player_mark'] = True
context['title_header'] = "This is map for home town"
return context
This same statement is copy and pasted about 15 times and to make it tidier i'm looking into having one and it look like this
Example 2:
{% if {{ player_header }} %}
{% if commun.intern > threshold %}
<a class="btn btn-success btn-sm pull-right"
href="{% url '{{ url_header }}' map_id=map.id home_id=homecall.id %}"><i
class="fa fa-phone-square fa-fw"></i>
{{ title_header }}</a>
{% endif %}
{% endif %}
then just updating it inside the context with what i need like so
Example 2 Context:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['player_header'] = ???
context['url_header'] = ???
context['title_header'] = "This is map for home town"
)
return context
I thought id be able to just replace the if statement in example one with contents of Example 2 but then i don't know how to structure this in the context_view.
Any ideas, need anything else let me know.
This is my attempt so far on the url context:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['url_header'] = 'games:map:town_map' + "?{}{}".format(
map_id=self.map.id, ----- Unsure if this is correct way to pass url varibales
home_id=self) ----- Unsure if this is correct way to pass url varibales
context['header'] = "This is map for home town"
return context
Hopefully this gives a better idea of what i'm talking about.
Solution HTML:
{% if button %}
{% if commun.intern > threshold %}
<a class="btn btn-success btn-sm pull-right"
href="{% url url_path map_id=map.id home_id=homecall.id %}"><i
class="fa fa-phone-square fa-fw"></i>
{{ header }}</a>
{% endif %}
{% endif %}
Solution Context:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['button'] = True
context['url_path'] = 'games:map:town_map'
context['header'] = "This is map for home town"
return context
How i got to solution, after some html reading i found that i was going wrong because of the brackets {{}} These are for printing {% %} are for using functions.