Django endless pagination url issue on page reload - django-endless-pagination

I am using endless pagination for my django project. On a page where I display records as a report, things work well.
However, when I include some "operations" with my records, I have issues.
e.g. my table row displays information and has additional column which takes the user to edit form.
{% extends "base/home.html" %}
{% load endless %}
{% block maincontent %}
{% paginate 5 atlist %}
<table> class="table">
{% for rec in atlist %}
<tr>
<!-- ... Headers ... and other columns code taken out .... -->
<td>
<button class="btn btn-primary btn-sm" onclick="location.href='/secure/editmytypes?ID={{rec.uuid}}'">Edit</button>
<button class="btn btn-primary btn-sm" onclick="location.href='/secure/deletemytypes?ID={{rec.uuid}}'">Delete</button>
</td>
</tr>
{% endfor %}
</table>
{{ pages.previous }} {{ pages.next }}
{% endblock %}
When the above template is loaded the first time, {{ pages.previous }} {{ pages.next }} display proper links like
"/list?page=2"
and behaves properly if I only do next / previous page navigation.
But, when the user clicks on Edit link (Edit Button) in a row to goto the edit form - do the operation and come back to this list (both the forms save data and transfers control back to this list) the {{ pages.previous }} {{ pages.next }} links become
"/secure/editmytypes?ID='..uuid...'&pages=2"
or
"/secure/deletemytypes?ID='..uuid...'&pages=2"
Does anyone have any pointers I could use ?
Thanks in advance.

Changing the way my edit for returns control back to this list form did the trick for me.
I was doing
# return render(request,'base/list_mytypes.html',{'atlist':mytypeslist,},)
which was the problem .. I changed it to
return redirect('/secure/listmytypes',{'atlist':mytypeslist,},)
and now suddenly the page links are proper !!
Doing some R&D in this since I think both the shortcuts essentially achieve the same effect (I know they return different HttpResponse objects but that should not have any effect on a url in some other page - unless I am missing something here).

Related

trouble showing desired checkbox validation state w/ bootstrap5 for django model form w/ m2m field and checkboxselectmultiple widget

I have a checkboxselectmultiple on an m2m model field in an ModelForm that is required - meaning at least one of the choices must be selected. I am using the boostrap5 was-validated class on my form:
<form method="POST" action="{{ request.path }}" {% if attempt_submit %}class="was-validated"{% endif %}>
This question is about how the validation shows up on my form with bootstrap5. Should be red border and red ! if not validated, green border and checkmark if so. However, for my checkboxes, if I don't have any selected (and everything else on the form validates), the form will show each checkbox option as green instead of red. Yet, it does know that it's invalid because the page focus will come back up the checkbox area to show the user what to correct (and it doesn't pass form.is_valid() in views.py.
Why are these labels and boxes still showing green and how can I show them as red until I select one and it's now valid?
Along the lines of this post, I have tried adding
{% if form.sales_location.field.required %}required{% else %}form.sales_location.field.required=""{% endif %}
to the checkbox <input>, but then each field is required and if I select one, the other remaining options still remain red - as if every option would have to be selected for the form to validate. Am I supposed to do this anyway and then add something else (JS?) to disable that?
Not sure exactly what code would be helpful to see...
in models.py, this is the field:
sales_location = models.ManyToManyField(SalesLocation, verbose_name="Where do you sell your products? (select all that apply)" )
in forms.py
model = AssessmentProfile
fields = [
'sales_location',
...
]
widgets = {
'sales_location': forms.CheckboxSelectMultiple(attrs={
'class': 'form-check',}),
}
I add this because I read this post about making sure that I use a `ModelMultipleChoiceField' - but I assume that is already happening because it's a model form.(?)
Probably most important, in the template thisform.html, here's how I'm manually adding this form element:
<div class="field-wrapper">
{{ form.sales_location.label_tag }}
<ul id="id_sales_location" class="form-check">
{% for pk, choice in form.sales_location.field.widget.choices %}
<li>
<input {% for location in location_qs %}{% if location == pk %}checked='checked'{% endif %}{% endfor %}
name="sales_location" class="form-check-input" type="checkbox" value="{{ pk }}" id="id_sales_location_{{forloop.counter0}}"
{% if already_submitted %}disabled="disabled"{% endif %}>
<label class="form-check-label" for="id_sales_location_{{forloop.counter0}}">
{{ choice }}
</label>
</li>
{% endfor %}
</ul>
</div>
Also, I tried updating css to manually format red, but think that doesn't address the root of the problem, plus, I wasn't able to do it successfully anyway.
Thanks for taking a look and for any suggestions.
In the end, I used javascript to solve this problem.
I updated the form template
<div class="field-wrapper">
{{ form.sales_location.label_tag }}
<ul id="id_sales_location" class="form-check">
{% for pk, choice in form.sales_location.field.widget.choices %}
<li>
<input {% for location in location_qs %}{% if location == pk %}checked='checked'{% endif %}{% endfor %}
name="sales_location" class="form-check-input" type="checkbox" value="{{ pk }}" id="id_sales_location_{{forloop.counter0}}"
{% if not form.sales_location.field.required %} {% else %} required {% endif %}
{% if already_submitted %}disabled="disabled"{% endif %}>
<label class="form-check-label" for="id_sales_location_{{forloop.counter0}}">
{{ choice }}
</label>
</li>
{% endfor %}
</ul>
</div>
to add required to the input if the checkbox is required. This allows all the checkboxes to come up red when validating, if the field is empty.
Then, I added this javascript to remove 'required' if it's checked.
<script>
// Select all checkboxes using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=sales_location]");
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
for (var cb of checkboxes) {
cb.removeAttribute('required');
}
})
});
</script>
If the field is not required, nothing changes. But if it is, then the required attribute on the <input>is gone and all the checkboxes show up green, which is what I wanted.
It's not perfect because if the checkboxes become unchecked, they don't change back to red. So I am making a dirty assumption that if someone checked a box, they wouldn't go back and uncheck it and try to submit. In which case, the validation would show green (and unchecked) until Submit was pressed again, but then it would take them back to this field which would be red again. If you know how to improve my code by adding the different case for the change function (only if the field is required), please feel free to add that. Cheers.

How to make a selection button inside a multistep form wizard in Django that renders an output without proceeding to the next step?

I am new to Django and I am making a project with a multistep form using django-formtools. The problem is, in my step 2 form, I have selection fields that I need to pass in the backend to perform some calculations and then render the output. The user can make changes anytime based on the output. I made an apply changes button which should trigger the backend process and a proceed to next step button if the user decides to finalize the selected changes. However, when I click the apply changes button, it leads me to the next step instead.
Here's my HTML code:
<form action="" method="POST">
{% csrf_token %}
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ form }} # three selection fields
<button name="apply_changes">Apply Changes</button>
{% endif %}
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans '‹ Previous Step' %}</button>
{% endif %}
<input type="submit" value="{% trans 'Finish' %}">
</form>
Here's my SessionWizardView method code snippet:
def get_context_data(self, form, **kwargs):
context = super(StepWizard, self).get_context_data(form=form, **kwargs)
if self.steps.current == 'step_1':
# save step 1 data to sessions
if self.steps.current == 'step_2':
step1_data = self.get_all_cleaned_data()
# if apply changes button is clicked
data = self.request.POST.get('apply_changes')
# process data
# add output to context
return context
I need help on how can it rightly be done. Thanks in advance!
So for future django developers who encountered the same problem as me, here's the answer to my question:
1) validate the data in step 2 which is temporarily the default values of my selection fields; and
2) override the post method to load the current page using the goto_step wizard function and embed it in the apply changes button
You can find the guide here :)
And then there 'ya go! Once the user clicks the apply changes button, the page reloads and the output is rendered in the form.
Still needs to optimize it though :D

how to get django pagination unique item id across all pages?

I am learning how to implement django pagination.
I want to let user save all changes (the whole form no matter which pagination )when he/she clicks the save-all button. However, when using forloop.counter0, the django will render duplicate forloop counter.
How can I generate continuous unique id from 0 to n-1 so that at views.py, the views can recognize every items? Thanks!
{% for thing in things %}
<tr id="tr-{{ thing.id }}">
<td style="display:none"><input type="text" name="hidden-id-{{ forloop.counter0 }}" value="{{ thing.id }}"></td>
</tr>
{% endfor %}
Is there existing any methods like plussing the pagecounter and the forloop counter?
After some trials-and-errors:
I've found that django by default (or maybe always) don't let us save things across all page(pagination).
To generate unique IDs across all pages, we can use the |add filter together with the start_index attribute which is autogenerated by django.
{% for thing in things %}
<tr id="tr-{{ thing.id }}">
<td style="display:none"><input type="text" name="hidden-id-{{ things.start_index |add:forloop.counter0 }}" value="{{ thing.id }}"></td>
</tr>
{% endfor %}

Anchor Links from One Page to Another in Django

I have a real estate site that dynamically populates the /listings page with a list of all current listings in the database - and, I have a sidebar on the other pages that randomly displays one listing at a time if it is tagged as 'featured'. Since the sidebar is just a summary of the listing, I would like to provide a link that would take the visitor to the /listing list page and then based on the anchor, position the screen to the featured listing they would like to see. I can get the anchor to work if I hard code a link outside of the object loop for the listings, but can get it to work dynamically using the id of the listing.
Here is what I am attempting to do:
My Sidebar - Notice the 'More Info' link before the closing - I would like to use the unique object ID as the anchor link
{% for listing in listings %}
<div class="featured-block">
...
<p style="font-weight: bold">For more information please contact {{ user.first_name }} {{ user.last_name }} at {{ listing.phone }}.More Info</p>
</div>
{% endfor %}
I then have an <a name="{{ listing.id }}"></a> on the listing page; I even tried <div id="{{ listing.id }}"></div> with no luck.
Is it because the link from the sidebar is linking to an anchor on the listings page that hasn't been generated yet? Any help is always greatly appreciated. Thank you.
you can use
{% for listing in listings %}
<div class="featured-block">
...
<p style="font-weight: bold">For more information please contact {{ user.first_name }} {{ user.last_name }} at {{ listing.phone }}.{{listing.id}}</p>
</div>
{% endfor %}
The url template tag
{% url 'listing_list' listing.id %}
will generate the url for the id refer docs and
{{listing.id}}
will show the id on the html

Django URL is being changed by a submit button

I'm very new to Django and not super familiar with web programming in general, so it's very likely that there is an easy fix to my problem that I'm just unaware of.
My web app is a photo gallery. People can click on a photo to see an enlarged version with buttons on either side for older or newer pictures. In addition, the photos in the gallery can be sorted by tags, which are passed along as URL parameters.
My problem is that when I click on one of the submit buttons, Django replaces the parameters in my URL with the name of the button, thus destroying my reference to what tag I was using. For example, "127.0.0.1:8000/gallery/view/6/?tag=people" upon clicking next, gets converted to "127.0.0.1:8000/gallery/view/6/?older=Older" when it's trying to process the URL.
Code from my HTML:
<form action="/gallery/view/{{ photo.id }}/?tag={{ tag }}" method="get">
{% if has_newer %}
<input type="submit" name="newer" value="Newer">
{% endif %}
<img src="{{ photo.photofile.url }}">
{% if has_older %}
<input type="submit" name="older" value="Older">
{% endif %}
</form>
In my view.py I pass in the tag plus other information in a render_to_response, but I'm not sure how to/if I can reclaim it while handling the buttons.
render_to_response('item/view.html', {'photo':photo, 'tag':tag, 'related_tags': related_tags, 'related_photos': related_photos, 'has_newer': has_newer, 'has_older': has_older}, context_instance=RequestContext(request))
Here's the view.py code for processing the buttons:
if 'newer' in request.GET:
if has_newer:
return HttpResponseRedirect('/gallery/view/%s/?tag=%s'%(newer[1].id, tag))
else:
return HttpResponseRedirect('/gallery/')
if 'older' in request.GET:
if has_older:
return HttpResponseRedirect('/gallery/view/%s/?tag=%s'%(older[1].id, tag))
else:
return HttpResponseRedirect('/gallery/')
<form action="/gallery/view/{{ photo.id }}/" method="get">
{% if has_newer %}
<input type="submit" name="newer" value="Newer">
{% endif %}
<!--This will append a tag parameter with given value to the querystring -->
<input type="hidden" name="tag" value="{{ tag }}">
<img src="{{ photo.photofile.url }}">
{% if has_older %}
<input type="submit" name="older" value="Older">
{% endif %}
</form>
Note that the query string is removed from action (as it won't be used) and the older and newer parameters will still be sent along.