How to retrieve filtered queryset used to render form fields in Django?

I have a Django form that contains a table with rows that reflect course objects from a database . Each row contains a checkbox input. This form also has some submit buttons that allow the user to filter the course objects shown in the table (besides a generic submit button).

This form is used to update the users profile with courses they are interested in. When the form is submitted, courses in the filter that are unchecked should be removed from the interested M2M relation and checked ones should be added to it.

To do that I need to know which inputs are checked , which I know how to retrieve, but I also need to know which courses are in the table that have unchecked inputs. Retreiving this is not as easy as ‘all the other courses in the database’ because my table does not always contain all course objects. If a user previously clicked one of the filter buttons, then the table contains only a filtered set of courses.

So I need to know which courses were used to create the table at rendertime, i.e. the ones that were injected as HTML context variable. Of course I know this at rendertime, but I don’t know how to retrieve it at POST request processing time.

I researched potential solutions and read something about using hidden inputs. The idea would be to give each row a hidden input with the course reference, which I could retrieve when the form is submitted. However I am curious if this would be the best way to go. Or if there is a better solution to this issue.

Please have a look at the code below, specifically the update_user_interests() function : How do I retrieve the courses that are in the form table context?

Form :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value='Submit'/>
{% for filter in filters%}
<input type="submit" name="filter" value='{{filter}}'/>
{% endfor %}
<table class="table table-striped table-bordered">
<tbody>
{% for course in courses %}
<tr>
<td>
<input type="checkbox"
name="checks"
value={{course.reference}}
{% if course in user_interests %} checked {% endif %}>
</td>
<td>
{{ course.reference|default:"" }}
</td>
<td>
{{ course.name|default:"" }}
</td>
<td>
{{ course.description|default:"" }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
</code>
<code><form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="submit" value='Submit'/> {% for filter in filters%} <input type="submit" name="filter" value='{{filter}}'/> {% endfor %} <table class="table table-striped table-bordered"> <tbody> {% for course in courses %} <tr> <td> <input type="checkbox" name="checks" value={{course.reference}} {% if course in user_interests %} checked {% endif %}> </td> <td> {{ course.reference|default:"" }} </td> <td> {{ course.name|default:"" }} </td> <td> {{ course.description|default:"" }} </td> </tr> {% endfor %} </tbody> </table> </form> </code>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" name="submit" value='Submit'/>
    {% for filter in filters%}
    <input type="submit" name="filter" value='{{filter}}'/>
    {% endfor %}
    <table class="table table-striped table-bordered">
        <tbody>
            {% for course in courses %}
                <tr>
                    <td>
                        <input type="checkbox" 
                        name="checks" 
                        value={{course.reference}}
                        {% if course in user_interests %} checked {% endif %}>
                    </td>
                    <td>
                        {{ course.reference|default:"" }}
                    </td>
                    <td>
                        {{ course.name|default:"" }}
                    </td>
                    <td>
                        {{ course.description|default:"" }}
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

</form>

View:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def table(request):
profile = Profile.objects.get(user=request.user.id)
allcourses = Course.objects.all()
filteropts = ['A','B','C']
if request.method == 'GET':
tablecourses = allcourses
user_interests = profile.interests.all()
if request.method == 'POST':
# update user interests from submitted form
update_user_interests(request, profile)
user_interests = profile.interests.all()
# filter the table if filter button clicked
filter = get_filter(request)
if filter:
tablecourses = Course.objects.filter(curriculum=filter).values()
else:
tablecourses = allcourses
return render(request, 'table.html',
{'courses': tablecourses,
'user_interests' : user_interests,
'filters':filteropts})
</code>
<code>def table(request): profile = Profile.objects.get(user=request.user.id) allcourses = Course.objects.all() filteropts = ['A','B','C'] if request.method == 'GET': tablecourses = allcourses user_interests = profile.interests.all() if request.method == 'POST': # update user interests from submitted form update_user_interests(request, profile) user_interests = profile.interests.all() # filter the table if filter button clicked filter = get_filter(request) if filter: tablecourses = Course.objects.filter(curriculum=filter).values() else: tablecourses = allcourses return render(request, 'table.html', {'courses': tablecourses, 'user_interests' : user_interests, 'filters':filteropts}) </code>
def table(request):
    profile = Profile.objects.get(user=request.user.id)
    allcourses = Course.objects.all()
    filteropts = ['A','B','C']
    
    if request.method == 'GET': 
        tablecourses = allcourses
        user_interests = profile.interests.all()
        
    if request.method == 'POST':
        # update user interests from submitted form
        update_user_interests(request, profile)
        user_interests = profile.interests.all()
        # filter the table if filter button clicked
        filter = get_filter(request)
        if filter:
            tablecourses = Course.objects.filter(curriculum=filter).values()
        else:
            tablecourses = allcourses
        
    return render(request, 'table.html',
        {'courses': tablecourses,
         'user_interests' : user_interests,
         'filters':filteropts})

Helpers:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def get_filter(request):
if 'filter' in request.POST:
return request.POST.getlist("filter")[0]
def update_user_interests(request, profile):
tablecourses = [] # How do I retrieve the courses that are in the form table ????
checked_courses = request.POST.getlist("checks")
for course in tablecourses:
ref = course.reference
if ref in checked_courses:
profile.interests.add(coursemodel)
else:
profile.interests.remove(coursemodel)
profile.save()
</code>
<code>def get_filter(request): if 'filter' in request.POST: return request.POST.getlist("filter")[0] def update_user_interests(request, profile): tablecourses = [] # How do I retrieve the courses that are in the form table ???? checked_courses = request.POST.getlist("checks") for course in tablecourses: ref = course.reference if ref in checked_courses: profile.interests.add(coursemodel) else: profile.interests.remove(coursemodel) profile.save() </code>
def get_filter(request):
    if 'filter' in request.POST:
        return request.POST.getlist("filter")[0]

def update_user_interests(request, profile):
    tablecourses = [] # How do I retrieve the courses that are in the form table ???? 
    checked_courses = request.POST.getlist("checks")
    for course in tablecourses:
        ref = course.reference
        if ref in checked_courses:
            profile.interests.add(coursemodel)
        else:
            profile.interests.remove(coursemodel)
    profile.save()

Models :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class Course(models.Model):
name = models.CharField(
unique=False,
null=False,
blank=False,
max_length=250
)
reference = models.CharField(
unique=True,
null=False,
blank=False,
max_length=250
)
curriculum = models.CharField(
unique=False,
null=True,
blank=True,
max_length=250,
)
description = models.TextField(
unique=False,
null=True,
blank=True,
max_length=2000,
)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
interests = models.ManyToManyField(
Course,
related_name='interests')
</code>
<code>class Course(models.Model): name = models.CharField( unique=False, null=False, blank=False, max_length=250 ) reference = models.CharField( unique=True, null=False, blank=False, max_length=250 ) curriculum = models.CharField( unique=False, null=True, blank=True, max_length=250, ) description = models.TextField( unique=False, null=True, blank=True, max_length=2000, ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) interests = models.ManyToManyField( Course, related_name='interests') </code>
class Course(models.Model):
    name = models.CharField(
        unique=False,
        null=False,
        blank=False,
        max_length=250
    )
    reference = models.CharField(
        unique=True,
        null=False,
        blank=False,
        max_length=250
    )
    curriculum = models.CharField(
        unique=False,
        null=True,
        blank=True,
        max_length=250,
    )
    description = models.TextField(
        unique=False,
        null=True,
        blank=True,
        max_length=2000,
    )

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    interests = models.ManyToManyField(
        Course,
        related_name='interests')

New contributor

user22574281 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật