How to make elided pagination work in django-tables2 - django

I am trying to use django-tables2 v2.5.2 to render a table of products.
Pagination renders correctly, it basically looks like:
['prev',1,2,3,4,5,'...',18,'next']
each button is tag with href='?page=x' and after click it updates url with the page parameter but ellpsis button ('...') has href='#' and obviously does nothing when clicked on. Other pages buttons works fine.
Do you have any idea how to setup django and/or django-tables2 to make elided pagination work?
I am trying to setup simple table with products. I am using function view and RequestConfig, like this:
views.py
def product_list(request: HttpRequest):
all_items = Product.objects.all().order_by("-publish_date")
product_filter = ProductFilter(request.GET, queryset=all_items)
table = ProductTable(product_filter.qs)
RequestConfig(request, paginate={"per_page": 5}).configure(table)
return render(
request, "product/product_list.html", {"table": table, "filter": product_filter}
)
and my tables.py code looks like this:
class ProductTable(tables.Table):
image_url = ImageColumn(verbose_name="Image")
publish_date = tables.DateColumn(format="d M Y", order_by=["publish_date"])
user = tables.Column(verbose_name="Verified by")
title = tables.Column(verbose_name="Product")
class Meta:
model = Product
template_name = "django_tables2/bootstrap.html"
sequence = ("title", "producer", "user", "status", "publish_date", "image_url")
exclude = ("id", "image_url")
filterset_class = ProductFilter
I tried to read documentation to django-tables2 and django framework but I think I must be missing something.
I am expecting the ellipsis button in pagination to load missing page range, so I guess it needs to have href set to something else than '#'.
EDIT:
I think I found the solution that works for me and most likely is what I was supposed to do.
The ellipsis button should not be clickable in the first place, its href='#' is set to correct value.
I styled the button with css to make it unclickable via pointer-events:none, changed cursor to look like its not clickable.
Basically I made the pagination look like and behave like pagination on StackOverflow (check bottom of the page here https://stackoverflow.com/questions)

I think I found the solution that works for me and most likely is what I was supposed to do.
The ellipsis button should not be clickable in the first place, its href='#' is set to correct value.
I styled the button with css to make it unclickable via pointer-events:none, changed cursor to look like its not clickable.
Basically I made the pagination look like and behave like pagination on StackOverflow (check bottom of the page here https://stackoverflow.com/questions)

Related

How to add a custom button or link beside a form field

I am using Django with crispy_forms third party library. I want to add a link beside a form field like some forms in Django admin app. How can I do this?
You've picked quite a complicated example that uses a method I wouldn't even recommend. But I'll try to explain how you see what you're seeing, and keep it short.
That is a AdminTimeWidget(forms.TimeInput) and a AdminDateWidget both nested in a AdminSplitDateTime(SplitDateTimeWidget(MultiWidget)). The MultiWidget part of this isn't really important, that's just how you bind two widgets together to provide one value (a datetime.datetime).
Here's what AdminTimeWidget looks like:
class AdminTimeWidget(forms.TimeInput):
#property
def media(self):
extra = '' if settings.DEBUG else '.min'
js = [
'vendor/jquery/jquery%s.js' % extra,
'jquery.init.js',
'calendar.js',
'admin/DateTimeShortcuts.js',
]
return forms.Media(js=["admin/js/%s" % path for path in js])
def __init__(self, attrs=None, format=None):
final_attrs = {'class': 'vTimeField', 'size': '8'}
if attrs is not None:
final_attrs.update(attrs)
super().__init__(attrs=final_attrs, format=format)
That adds a DateTimeShortcuts.js script to the page (in the way that Admin Widgets can, via the form media property) and it's that script that iterates input tags looking for date and time inputs.
There's a LOT of machinery involved to get that happening but again, in effect, it's just a bit of javascript that looks for a date/time input and adds the HTML client-side.
But you probably don't want to do that.
As I said, that's a very complicated widget, and in Admin where it's harder to alter things on the fly. If you want to write an Admin widget, you probably do want to go that way.
But if you already control the template, or a crispy layout, you could just bung in some HTML. Crispy has an HTML element that you can throw into layouts. This is well documented.
Or if you want a reusable widget, you could use a custom template. Since Django 1.11, Widgets use templates to render.
Create a widget, borrowing from an existing one to save time
from django.forms import widgets
class DateWithButtonWidget(widgets.DateInput):
template_name = 'widgets/date_with_button.html'
Customise the template with the HTML you want:
{% include "django/forms/widgets/input.html" %} <button>MY BUTTON</button>
Use that widget in your form:
class MyForm(forms.ModelForm):
fancydate = forms.DateField(widget=DateWithButtonWidget)
Of course, wiring that button to do something is all up to you. Using a fully-scripted option might be what you need after all.

How to render django form differently based on what user selects?

I have a model and a form like this:
class MyModel(models.Model):
param = models.CharField()
param1 = models.CharField()
param2 = models.CharField()
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('param', 'param1', 'param2')
Then I have one drop down menu with different values and based on what value is selected I'm hiding and showing fields of MyForm. Now I have to take one step further and render param2 as a CheckboxInput widget if user selects a certain value from a drop down but in other cases it should be standard text field. So how would I do that?
I know this post is almost a year old, but it took me multiple hours to even find a post related to this topic (this is the only one I found, which came up as related when submitting my own question), so I felt the need to share my solution.
I wanted to have a form that would show and require a text field if an option from a dropdown menu matched a value stored in another model. I had a foreignKey relation between two models and I passed an instance of Model1 into the ModelForm for Model2. If a value chosen for a variable in Model2 matched a variable already set in Model1, I wanted to show and require a textfield. It was basically a "choose Other and then enter your own description" scenario.
I did not want the page to reload (I was trying to have this work in both mobile and desktop browsers with the least delay/reloads and using the same code for both), so I could not use the mentioned multiple forms loading in a view option. I started trying to do it with AJAX as suggested above when I realized I was over thinking the problem.
The answer was using JS and clean methods in the form. I added a non-required field (field1) that was not in Model2 to my Model2Form. I then hid this using jQuery and only displayed it (using jQuery) if the value of another field (field2) matched the value of the variable from Model1. To make that work, I did decide to have a hidden < span > in my template with the pk of the variable so I could easily grab it with jQuery. This jQuery worked perfectly for hiding and showing the field correctly so the user could choose the "other" value and then decided to choose a different one instead (and go back and forth endlessly).
I then used a clean method in my Model2Form for field1 that raised a ValidationError if no value was entered when the value in field2 matched my Model1 variable. I accessed that variable by using "self.other = Model1.variable" in my __ init __ method and then referencing that in the clean_field1 method.
I would have liked to have been able to accomplish this without having to hide and show a field with JS, but I think the only solutions for doing so with views or ajax caused delays/reloads that I did not want. Also, I liked the general simplicity of the method I used, rather than having to figure out how to pass partial forms back and forth through the HTTPRequest.
Update:
In my situation, I was creating entries for lost and found items and if the location where the item was found was not a provided option, then I wanted to show a textbox for the user to enter the location. I created a location object that was set as the "other" location and then displayed the textbox when that object was selected as the "found" location.
In forms.py, I added an extra CharField and use a clean method to check if the field is required and then throw a ValidationError if it wasn't filled in:
class Model2Form(forms.ModelForm):
def __init__(self, Model1, *args, **kwargs):
self.other = Model1.otherLocation
super(Model2Form, self).__init__(*args, **kwargs)
...
otherLocation = forms.CharField(
label="Location Description",
max_length=255,
required=False
)
def clean_otherLocation(self):
if self.cleaned_data['locationFound'] == self.other and not self.cleaned_data['otherLocation']:
raise ValidationError("Must describe the location.")
return self.cleaned_data['otherLocation']
Then in my JavaScript, I checked if the value of the "found" location was the "other" location (the value of which I had in a hidden span on my html page). I then used .show() and .hide() on the textbox's parent element as necessary:
$("#id_locationFound").change( function(){
if ($("#id_locationFound").val() == $("#otherLocation").attr("value")){ //if matches "other" location, display textbox; otherwise, hide textbox
$("#id_otherLocation").parent().show();
}else
$("#id_otherLocation").parent().hide();
});
Your best guess would be to trigger a "POST" request when you select something from your drop down menu.
The Value of that "POST" has to correspond your values you use to determine which field you would like to output.
Now you will actually need two forms:
class MyBaseForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('param', 'param1', 'param2')
class MyDropDownForm(MyBaseForm):
class Meta:
widgets = {
'param2': Select(attrs={...}),
}
So as you can see the DropDownForm has been derived from MyBaseForm to make sure it will have all the same properties. But we have modified the widget of one of the fields.
Now you can update your view. Please note, this is untested Python + Pseudocode
views.py
def myFormView(request):
if request.method == 'POST': # If the form has been submitted...
form = MyBaseForm(request.POST)
#submit button has not been pressed, so the dropdown has triggered the submission.
#Hence we won't safe the form, but reload it
if 'my_real_submitbotton' not in form.data:
if 'param1' == "Dropdown":
form = MyDropDownForm(request.POST)
else:
#do your normal form saving procedure
else:
form = ContactForm() # An unbound form
return render(request, 'yourTemplate.html', {
'form': form,
})
This mechanism does the following:
When the form is submitted it checks if you have pressed the "submit" button or have used a dropdown onChange to trigger a submission. My solution doesn't contain the javascript code you need to trigger the submission with an onChange. I just like to provide a way to solve it.
To use the 'my_real_submitbutton' in form.data construct you will be required to name your submit button:
<input type="submit" name="my_real_submitbutton" value="Submit" />
Of course you can choose any string as Name. :-)
In case of a submit by your dropdown field you must check which value has been selected in this drop down menu. If this value satisfies the condition you want to return a Dropdown Menu you create an instance of DropDownForm(request.POST) otherwise you can leave everything as it is and rerender your template.
On the downside this will refresh your page.
On the upside it will keep all the already entered field values. So no harm done here.
If you would like to avoid the page refresh you can keep my proposed idea but you need to render the new form via AJAX.

Add a custom method in Django model to know if the current user is the author

I am retrieving a bunch of things with a queryset and displaying them as a list, that is then clickable to view the chosen article's details.
So in the article's details view, I have a is_creator method:
#login_required
def is_creator(userProfile, article):
if userProfile == article.creator:
return True
else:
return False
So I can display an edit button at will.
On the homepage though, it's a different story because I'm making a query, and giving the queryset directly to the template that will make a for loop to display the titles. I still want to know for each article if the current user is the creator though.
So I'm thinking of adding the work in the model itself, not to have to duplicate code anywhere.
#property
def is_creator(self,user):
if self.creator.user == user:
return 1
else:
return 0
I was thinking that by adding that in the model, I should be able to call in the template {% if event.is_creator user %}test{% endif %} pretty easily. Seems that I'm wrong, because I'm facing:
TemplateSyntaxError at /
Unused 'user' at end of if expression.
I'm coming from the PHP world so it feels like this should work, but I'm obviously doing something wrong.
Thanks in advance :)
EDIT: I'm guessing that another solution would be in the view to loop through the Queryset with something like:
variables['articles'] = Event.objects.filter(
(Q(creator=me) | Q(bringing__attendee=me)) & Q(date_start__lt=datenow) & Q(date_end__gt=datenow)
).order_by('-date_start')
for article in variables['articles']:
article.iscreator=1 (I can do some more work here)
But it seems like having to loop over the QS is not the best idea.
It is very sad but you cant pass params to methods from templates(indeed this is a good idea - so you don't mix presentation logic with model logic, almost :) ). You have to write a template tag for this purpose.
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
tag would look like this(not tested):
#register.simple_tag(takes_context=True) # assuming you are running in request context
def current_user_is_creator(context,article):
user = context['request'].user
return article.creator.user == user # dont forget to add proper checks
Or you could prepare required data in the view.

Django admin raw_id_fields table display

Django raw_id_fields don't display tables the way I expect, am I doing something wrong? I'm trying to use a raw_id_fields widget to edit a ForeignKey field as follows:
#models.py
class OrderLine(models.Model):
product = ForeignKey('SternProduct')
class SternProduct(models.Model):
def __unicode__(self): return self.product_num
product_num = models.CharField(max_length=255)
#admin.py
#import and register stuff
class OrderLineAdmin(admin.ModelAdmin):
raw_id_fields=('product')
I get the little textbox and magnifier widget as expected, but clicking the magnifier gives me this:
flickr.com/photos/28928816#N00/5244376512/sizes/o/in/photostream/
(sorry, can't post more than one hyperlink apparently)
I thought I would get something closer to the changelist page c/w columns, filters and search fields. In fact, that's apparently what others get.
Any thoughts about how to enable the more featureful widget?
Ah, OK, this should have been obvious, but it isn't explained in the Django docs. The list that appears in the raw_id_fields popup uses the same options as the admin object for the referenced model. So in my example, to get a nice looking popup I needed to create a SternProductAdmin object as follows:
class SternProductAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'drawing_number', 'drawing_revision',)
list_filter = ('drawing_number',)
search_fields = ('drawing_number',)
actions = None
Hopefully this will help others in the future.

Django Forms - change the render multiple select widget

In my model I have a manytomany field
mentors = models.ManyToManyField(MentorArea, verbose_name='Areas', blank=True)
In my form I want to render this as:
drop down box with list of all
MentorArea objects which has not
been associated with the object.
Next to that an add button which
will call a javascript function
which will add it to the object.
Then under that a ul list which has
each selected MentorArea object with
a x next to it which again calls a
javascript function which will
remove the MentorArea from the
object.
I know that to change how an field element is rendered you create a custom widget and override the render function and I have done that to create the add button.
class AreaWidget(widgets.Select):
def render(self, name, value, attrs=None, choices=()):
jquery = u'''
<input class="button def" type="button" value="Add" id="Add Area" />'''
output = super(AreaWidget, self).render(name, value, attrs, choices)
return output + mark_safe(jquery)
However I don't know how to list the currently selected ones underneath as a list. Can anyone help me? Also what is the best way to filter down the list so that it only shows MentorArea objects which have not been added? I currently have the field as
mentors = forms.ModelMultipleChoiceField(queryset=MentorArea.objects.all(), widget = AreaWidget, required=False)
but this shows all mentors no matter if they have been added or not.
Thanks
For me the functionality you described sounds a lot like what you can achieve with using the ModelAdmin' filter_horizontal and filter_vertical settings.
The widget they render lives in django.contrib.admin.widgets.FilteredSelectMultiple. You should have a look at its code!