Django dropbox dynamic error - django

I have a page that display all the objects acorrding to the catergory the students pick.
I implemented a pagination on the site to split the objects at different pages.
The problem occurs when the students pick a catergory from the dropbox and tries to flick through the pagination for new and old entries.
The reason this happens because everytime the user picks a catergory from the dropbox , the dropbox get reset once it retrieve the objects. So when users try to flick through objects using the pagination . The pagination doesn't know what data to retrieve because the dropbox catergory get reset and redirec the users to a blank page.
A solution to this is to program the dropbox to remain static for the choices the users make so when the users flicks through the data split by the pagination , the pagination know can retrieve objects according to the dropbox.
I can't figure out how to make this dropbox remain static for the choices the users make.
my views.py
def BoardFinder(request):
form = BoardFinderForm(request.POST)
fo = BoardFinderForm()
if form.is_valid():
Category = form.cleaned_data['Category']
posts = Board.objects.filter(Category=Category)
paginator = Paginator(posts, 1)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_pages)
return render(request,"boardfinder.html",{"posts":posts,"fo":fo})
return render(request,"boardfinder.html",{"fo":fo})
My models.py
class Board(models.Model):
MATH = 'MATH'
ENGLISH = 'ENGLISH'
SCIENCE = 'SCIENCE'
LANGUAGE = 'LANGUAGE'
CATEGORY = (
(MATH, 'Math'),
(ENGLISH, 'English'),
(SCIENCE, 'Science'),
(LANGUAGE, 'Language'),
)
Category =models.CharField(max_length=30,choices=CATEGORY)
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
picture = models.OneToOneField('Picture',related_name='picture',blank=True,null=True)
def __unicode__(self):
return self.name
class BoardFinderForm(forms.ModelForm):
class Meta:
model = Board
fields = ('Category',)
Important parts of my boardfinder.html
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ fo.as_p }}
<input type = "submit" value= "Find WhiteBoard" />
</form>
{% for post in posts.object_list %}
<div class="title">{{ post.name }}</div>
{% endfor %}

<form method="GET">
<p><select name="category">
<option value=""
{% if not request.session.category %}selected{% endif %}>
(All subjects)
</option>
<option value="ENGLISH"
{% if request.session.category == "ENGLISH" %}selected{% endif %}>
English
</option>
<option value="LANGUAGE"
{% if request.session.category == "LANGUAGE" %}selected{% endif %}>
Language
</option>
<option value="MATH"
{% if request.session.category == "MATH" %}selected{% endif %}>
Math
</option>
<option value="SCIENCE"
{% if request.session.category == "SCIENCE" %}selected{% endif %}>
Science
</option>
</select></p>
<input type = "submit" value= "Find WhiteBoard" />
</form>
def BoardFinder(request):
category = request.GET.get('category')
if category:
request.session['category'] = category
posts = Board.objects.filter(Category=category)
paginator = Paginator(posts, 1)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_pages)
return render(request,"boardfinder.html",{"posts":posts,"fo":fo})
return render(request,"boardfinder.html",{"fo":fo})

Related

Flexible Django Filter (django-filter package)

I'm currently implementing some filters and I'm facing multiple problems. First of all my checkbox works when clicking on the brand title, not the actual:
this is my .html code:
<form method="get">
<div class="toggle-list product-categories">
<h6 class="title">Sorteer</h6>
<div class="shop-submenu">
<ul>
{{ filter.form.order_by }}
</ul>
</div>
</div>
<div class="toggle-list product-categories">
<h6 class="title">Merk(en)</h6>
<div class="shop-submenu">
<ul>
{% for f in filter.form.brand %}
<li>
<input type="checkbox" name="brand" id="brand">
<label for="brand">{{ f }}</label>
</li>
{% endfor %}
</ul>
</div>
</div>
<input type="submit" value="Filter">
</form>
my filter in filters.py:
class SortFilter(django_filters.FilterSet):
ORDER_BY_CHOICES = (
('-discount_sort', 'Hoogste korting'),
('-new_price', 'Hoogste prijs'),
('new_price', 'Laagste prijs'),
)
order_by = django_filters.ChoiceFilter(label='Sorteer op', choices=ORDER_BY_CHOICES, method='filter_by_order',
empty_label=None)
brand = django_filters.ModelMultipleChoiceFilter(queryset=Product.objects
.order_by('brand')
.filter(categorie='eiwitten')
.values_list('brand', flat=True).distinct()
, widget=forms.CheckboxSelectMultiple, required=False)
class Meta:
model = Product
fields = ['brand']
def filter_by_order(self, queryset, name, value):
return queryset.order_by(value)
view function for this certain page:
def eiwit(request):
# filter alleen eiwitproducten
eiwit_list = ['eiwitten']
eiwit_filter = Q()
for item in eiwit_list:
eiwit_filter = eiwit_filter | Q(categorie=item)
products = models.Product.objects.filter(eiwit_filter)
product_amount = len(products)
# sorteer filter
filtered = SortFilter(
request.GET,
queryset=products
)
# paginator
paginator = Paginator(filtered.qs, 12)
page = request.GET.get('page')
try:
response = paginator.page(page)
except PageNotAnInteger:
response = paginator.page(1)
except EmptyPage:
response = paginator.page(paginator.num_pages)
product_front_end = {
'final_products': response,
'filter': filtered,
'count': product_amount,
}
return render(request, 'producten/eiwit.html', product_front_end)
Second of all, I would like the filter to be more generic. As in all categories have different amount of brands. As you can see I currently create options by selecting all the 'brand' values within the 'eiwitten' categorie (in filters.py). Is there a way to call the filter in views.py with a variable (like 'eiwittien'). Which then will be used to adjust the filter in filter.py according to the page it is on? This way I have a dynamic filter for all categories.
This might help with some of your issues. Your input tag is missing information on the name/id fields. You should be able to populate those by adding template tags to fill the values.
<input type="checkbox" id="BSN" name="BSN"> <label for="BSN">BSN</label>

Django Choice Form add selected options

Hi all its my code if i choice in select list django work but i want after submit choices not be change.
After submit first choices again seeing.
My Form
class PostSorguForm(forms.Form):
HIKAYE_CHOICES=(('1','En Son Çıkanlar'),('2','En Çok Okunanlar'))
sorgu_form = forms.ChoiceField(choices=HIKAYE_CHOICES,required=False)
My view
class ArticleListView(FormMixin,ListView):
context_object_name = 'articles'
template_name = 'includes/article/article-list.html'
paginate_by = 15
form_class= PostSorguForm
def get_queryset(self):
queryset = Article.objects.all()
if self.request.GET.get("sorgu_form"):
selection = self.request.GET.get("sorgu_form")
if selection == "2":
queryset = Article.objects.all().order_by('-hit_count_generic__hits')
else:
queryset=Article.objects.filter(published=True).order_by('created_date').reverse()
return queryset
my template
<form method="GET" action="">
<div class="form-group">
<select class="form-control" name="sorgu_form" id="id_sorgu_form" onchange="this.form.submit()">
{% for x,y in form.fields.sorgu_form.choices %}
<option value="{{x}}">{{y}}</option>
{% endfor %}
</select>
</div>
</form>
i want after query option selected
i search a hours and i found now it's work
if you have another idea please write
<option value="{{x}}" {% if '?sorgu_form=2' in request.get_full_path %}selected{% endif %}>{{y}}</option>

How to update template on Django view request post

I am doing some filtering. I have initial results on my page, then there is a form, that on select, I want to filter some data and update template.
The template doesn't seem to be updated though.
from .services import service
# Home Page View
def home_view(request, *args, **kwargs):
update_list = service.get_updates()
if request.method == 'POST':
filter_string = request.POST.get('filter')
update_list = [update for update in update_list if update['type'] == filter_string]
print(len(update_list))
page = request.GET.get('page', 1)
paginator = Paginator(update_list, 2)
try:
updates = paginator.page(page)
except PageNotAnInteger:
updates = paginator.page(1)
except EmptyPage:
updates = paginator.page(paginator.num_pages)
context = {
'updates': updates
}
return render(request, "home.html", context)
Template file:
<form method="post" id="filterformhome">
{% csrf_token %}
<select class="frm-input" onchange="homeFilter(this);">
<option value="job">{% trans "Jobs" %}</option>
<option value="market">{% trans "Products" %}</option>
<option value="question">{% trans "Questions" %}</option>
<option value="blog">{% trans "Blogs" %}</option>
</select>
</form>
{% for update in updates %}
{{update.title}}
{% endfor %}
What would be the better way of doing this?
You need to use JS for that, otherwise you will only see the change reflected by refreshing the page.

Django-Filter | Looping over form fields

I am using django-filter which works as intended. I am however trying to loop over the form fields but the standard django attributes aren't working. The only one that does is {{ form.id_for_label }}. Am I missing something?
My template code:
<form action="" method="get">
{% for form in forms.form.product_colours %}
<div class="form-group">
<input type="checkbox" name="product_colours" id="{{ form.id_for_label }}" value="{{ form.value }}">
<label for="{{ form.id_for_label }}">{{ form.label }}</label>
</div>
{% endfor %}
<input type="submit" />
</form>
The reason I don't want to simply use {{ form }} is because it loads the <label> before the <input> whereas I'd need it to work viceversa to fit into my styling. I would prefer not to have to change the styling.
In case they are needed, here are my (simplified) models, FilterSet and my view:
Model:
class ProductColour(models.Model):
name = models.CharField(max_length=255)
colour_hex = models.CharField(max_length=16, default="#FFF")
def __str__(self):
return self.name
class Product(Page):
# My product fields
product_colours = ParentalManyToManyField('products.ProductColour', blank=True)
FilterSet:
class ProductFilter(django_filters.FilterSet):
product_colours = django_filters.ModelMultipleChoiceFilter(name="product_colours",
label="Product Colour",
widget=forms.CheckboxSelectMultiple,
queryset=ProductColour.objects.all(),
conjoined=False)
class Meta:
model = Product
fields = ['product_colours']
View:
def get_context(self, request):
context = super(Page, self).get_context(request)
all_products = ProductFilter(request.GET, queryset=Product.objects.live()).qs
forms = ProductFilter(request.GET, queryset=Product.objects.live())
paginator = Paginator(all_products, 9) # Show 9 resources per page
page = request.GET.get('page')
try:
products = paginator.page(page)
except PageNotAnInteger:
products = paginator.page(1)
except EmptyPage:
products = paginator.page(paginator.num_pages)
context['forms'] = forms
context['products'] = products
return context
In case you are wondering what the ParentalManyToManyField is, it's a Wagtail CMS class.
OK so I have found the solution - as user #Vicmathur suggested in the comments above I tried adding {% for check in form %}{% endfor %} and it threw up a 'BoundWidget' object is not iterable error.
So I googled BoundWidget and found the related Django documentation.
Instead of trying to access the data through, for example, {{ form.value }}, I need to specify{{ form.data.value }}

Django Paginator Error

I'm been trying to implement django paginator into my whiteboard app so I can split the pictures into different pages.
The problem occurs when I attempt to move across different pages.I limited each page to 1 objects and uploaded few pictures to test if the pagination works between pages but when I try to move across different pages using the pagination method, it doesn't respond.
http://img854.imageshack.us/img854/3303/94627386.jpg
I'm been researching and testing for solutions to this problems through the django pagination docs and I think problem lay at the pagination module method at my template.
My views.py
def Boat(request ,animal_id):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
picture = Picture.objects.filter(board=animal_id)
paginator = Paginator(picture,1)
page = request.GET.get('page')
try:
picture = paginator.page(page)
except PageNotAnInteger:
picture = paginator.page(1)
picture = paginator.page(paginator.num_pages)
return render(request,'boat.html',{'picture':picture })
My boat.html
{% if picture.object_list %}
<ul>
{% for pet in picture.object_list %}
{% if pet.image %}
<br>
<img src= "{{ pet.image.url }}" </a>
<br>
</a>
</li>
{% endif %}
<br>
View Comment Like<br/>
{% for c in picture %}
{% ifequal c.picture.id pet.id %}
<br>{{ c.body }}</li>
<br>{{ c.created}}</li>
<br>{{ c.user}}</li>
{% endifequal %}
% endfor %}
{% endfor %}
</ul>
{% endif %}
Add Pictures to your board<br/>
{% if number %}
{{number}}
{% endif %}
Return back to Profile<br/>
<br><br><br><br><br>
<div class="pagination">
<span class="step-links">
{% if picture.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ picture.number }} of {{ picture.paginator.num_pages }}.
</span>
{% if picture.has_next %}
next
{% endif %}
</span>
</div>
Parts of my module
class Picture(models.Model):
user = models.ForeignKey(User)
board = models.ForeignKey(Board,blank=False,null=False,related_name='board')
image = models.FileField(upload_to="images/",blank=True)
description = models.TextField()
is_primary = models.BooleanField(default=False)
def __unicode__(self):
return self.description
def Boat(request ,animal_id):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
picture = Picture.objects.filter(board=animal_id)
paginator = Paginator(picture,1)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
picture = paginator.page(page)
except (EmptyPage, InvalidPage):
picture = paginator.page(paginator.num_pages)
picture = paginator.page(paginator.num_pages)
return render(request,'boat.html',{'picture':picture })
#this is view
#this is views files
#login_required(login_url='/login')
# class Base_page_list2(ListView):
def Base_page_list(request,*args, **kwargs):
# tiket = Tiket.objects.all()
# lastest_tiket =Tiket.objects.order_by('-id').all()[:8]
tiket_list = Tiket.objects.all()
paginator = Paginator(tiket_list,2)
page = request.GET.get('page')
page_obj = paginator.get_page(page)
context ={
'tiket':None,
'page_obj':page_obj,
}
context['tiket']=['page_obj']
if request.user.is_superuser:
context['tiket']= Tiket.objects.all()
elif not request.user.is_hrm:
raise Http404('شما نمی توانید به این صحفه دسترسی داشته باشید')
elif request.user.is_mis :
context['tiket']= Tiket.objects.filter(status_tag='s')
elif request.user.is_mali:
context['tiket']=Tiket.objects.filter(status_tag='m')
elif request.user.is_mosh:
context['tiket']=Tiket.objects.filter(status_tag='c')
elif request.user.is_modir:
context['tiket']=Tiket.objects.filter(status_tag='b')
elif request.user.is_kz:
context['tiket']=Tiket.objects.filter(status_tag='k')
elif request.user.is_pa:
context['tiket']=Tiket.objects.filter(status_tag='p')
else:
context['page_obj']['tiket']=Tiket.objects.filter(author=request.user)
return render(request,'hrm_account/base.html',context)
`enter code here`error
File "/home/ali/Desktop/testsharen2/sharen/sharen_hrm/views.py", line 128, in Base_page_list
context['page_obj']['tiket']=Tiket.objects.filter(author=request.user)
TypeError: 'Page' object does not support item assignment