Method Not Allowed (POST): /items/ - python

So i'm trying to do a filter with django, to filter the items on the main page. A little context:
An item can be assigned to a user or not. I want a filter, to see what items are assigned and which items aren't.
This is my function in views.py:
class ItemsView(ListView):
template_name = 'inventory/items.html'
context_object_name = 'items_list'
def get_queryset(self):
if (self.request.user.is_authenticated):
if self.request.method == "get":
searched = self.request.GET.get('searched')
if searched == "None":
return Item.objects.filter(assigned_user__isnull=True, company=getCompany(self.request.user))
else:
return Item.objects.filter(assigned_user__isnull=False, company=getCompany(self.request.user))
else:
return Item.objects.filter(company=getCompany(self.request.user))
And this is from my items.html:
<form method="post" action="/items">
{% csrf_token %}
<select name="item_filter">
<option value="None">Not Checked In</option>
<option value="Checked_In">Checked In</option>
</select>
<input type="submit" value="filter">
</form>
So basically what i want is, that the user can pick one of the two choices in the dropdown-menu, and the items should be listed based on the choice he made.
When i use this form and click the submit button, the screen gets white and in my console, the error
Method Not Allowed (POST): /items/ appears. Has this something to do with the fact i'm using the generic.ListView for my view?
Thank you

in list view is POST not allowed. But you dont need it:
In template:
<form action="/items">
<select name="item_filter">
<option value>Not Checked In</option>
<option value="Checked_In">Checked In</option>
</select>
<input type="submit" value="filter">
</form>
in view:
class ItemsView(ListView):
... # any staff
def get_queryset(self):
query = {'company':getCompany(self.request.user)}
if (self.request.user.is_authenticated):
query['assigned_user__isnull'] = bool(self.request.GET.get('item_filter'))
return Item.objects.filter(query)

Related

can not send multiple select values to django view

I have a select and has multiple values but in the backend
knowledge_keywords list is empty
knowledge_keywords = request.POST.getlist('knowledge_keywords')
<div class="container">
<div class="input-group"> <span class="input-group-addon">
<input type="checkbox" class="form-check-input" name="key_words_check_box" value="1">
</span>
<select class="hidden" id="keywords" name="knowledge_keywords" multiple="multiple" data-role="tagsinput">
</select>
</div>
</div>
Views.py
keywords = request.POST.getlist('keywords')
in template
<select name="keywords" multiple="true">
<option value="1">Keyword 1</option>
<option value="2">Keyword 2</option>
<option value="3">Keyword 3</option>
<option value="4">Keyword 4</option>
<option value="5">Keyword 5</option>
</select>
try this and print keywords variable if it still gives an error then comment again and state what error is given, i have tried this, it is working.
Don't write form in html, reuse Django logic.
You can create a Form class:
Forms.py
from django import forms
class MyForm(forms.Form):
CHOICES = (
("option1", "option1"),
("option2", "option2"),
)
knowledge_keywords = forms.MultipleChoiceField(
widget=forms.CheckboxSelectMultiple, choices=CHOICES
)
template.html
<form method='post'>
{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='submit'>
</form>
use the FormView provided by Django that help you to manage form in the view, for example:
Views.py
from django.views.generic import FormView
from forms import MyForm
class MyView(FormView):
form_class = MyForm
template_name = 'template.html'
def form_valid(self, form):
# can you access to cleaned value in the form inside
# form.cleaned_data['knowledge_keywords']
# and you can execute query or something else
return super().form_valid(form)
you can instead take all the options by jquery and put them in an input which is hidden.Then send them to backend
var SelectOptions = ''
// event listener when user submits the button
$("#buttonsubmit").click(function(){
$("#keywords option").each(function(){
SelectOptions = SelectOptions + $(this).val().trim() + ' '
});
// put the values in SearchKeyword input
$("#SearchKeyword").val(SelectOptions)
});

Django pagination resets

I am building an application that lists certain records from a database. The database is quite large and I am building a pagination to show a specific number of rows. Currently I have set a default value for the paginate_by. Here is the class that I am using.
class HomePageView(ListView):
model = Syslog
template_name = 'home.html'
context_object_name = 'all_logs';
paginate_by = 10
def get_paginate_by(self, queryset):
return self.request.GET.get("paginate_by", self.paginate_by)
I have implemented and a feature that allows clients to change the pagination levels like so:
<form action="" method="get">
<select name="paginate_by" onchange='this.form.submit()'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</form>
When the home page is loaded with the default value the number of pages show correctly. When a user submit another paginate_by value the number of pages change accordingly. The problem is that when the pagination parameter is changed and a user click on let's say 2nd page the paginate_by resets to the default.
Regards,
Jordan
you have to first get request path and after that you have to put a page number in
{{ request.path }} # -without GET parameters
{{ request.get_full_path }} # - with GET parameters
you have to use without get parameters
<select name="report" onchange="location = this.value;" class="form-control">
<option value="{{request.path}}?page=page_logic">1</option>
</select>
here page_logic can be 1,2,3,4 ...
I have figure out a way to do what I was looking for, so I ended up with this.
This is how the form looks like.
<form action="" method="get" id="form">
<select name="paginate_by" onchange = "this.form.submit();">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
For the pagination feature I ended up using a custom template tag that alters the ?page parameter, so when a client clicks on ?page=1 for example, he is redirected to www.example.com/?paginate_by=2&page=1 and if he clicks on ?page=2, he is redirected to www.example.com/?paginate_by=2&page=2 (without the custom tag he would be redirected to www.example.com/?paginate_by=2&page=1&page=2)

django forms print select values

I am trying to return the selected choice value from a dropdown menu in django. The option (in html) is dynamically populated from the database's model primary key.
HTML
<form class="student-ID-search" action="{% url 'new_coach_schedule' %}" method="post" >
<select class="form-control" id="student_select">
<option>Select student ID</option>
{% for student_data in students_data %}
<option value="{{ student_data.pk }}">{{ student_data.pk }}</option>
{% endfor %}
</select>
</form>
<button class="btn" type="submit" name="search_result" value="select>
<i class="fa fa-search"></i>
</button>
views.py
students_data = Student.objects.all()
search_result = NewStudentSearchForm(request.POST)
if 'search_result' in request.POST:
test_print_to_screen = search_result['student_select']
print(test_print_to_screen)
args = {'students_data': students_data}
return render(request, 'static/html/new_coach_schedule.html', args)
else:
return render(request, 'static/html/new_coach_schedule.html', args)
forms.py
class NewStudentSearchForm(forms.Form):
search_field = forms.CharField(max_length=50) # This is for something else.
student_select = forms.ModelChoiceField(queryset=Student.objects.all(), empty_label=None)
When I make use of ModelChoiceField, test_print_to_screen does not print out the selected choice that I chose in the html select box.. It prints out everything instead.
EG:
<select name="student_select" id="id_student_select">
<option value="5">Student object (5)</option>
<option value="6">Student object (6)</option>
<option value="7">Student object (7)</option>
<option value="8">Student object (8)</option>
<option value="9">Student object (9)</option>
<option value="10">Student object (10)</option>
<option value="11">Student object (11)</option>
<option value="12">Student object (12)</option>
<option value="13">Student object (13)</option>
</select>
How can I go about in my forms.py so that when i select the value in my browser, it will return / print out the selected choice back to me?
Update
As per the comments, I updated my views.py file to include cleaned_data as follows:
if 'search_result' in request.POST:
search_result = NewCoachSearchForm(request.POST)
print(search_result)
if search_result.is_valid():
test = search_result.cleaned_data['student_select']
print(test)
else:
print(search_result.errors)
However, this produces a stacktrace error:
<ul class="errorlist"><li>student_select<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
When using Django forms, please call form's is_valid() method and then if it is valid use cleaned_data attribute to access submitted values.
students_data = Student.objects.all()
search_result = NewStudentSearchForm(request.POST)
if search_result.is_valid():
cd = search_result.cleaned_data
selected_student = cd['student_select'] # Here you get Student instance

How to get select field text from html form in django?

I have created a form with select field in template ehrinfo.html
<form action="{% url 'ehrs:compcreate' %}" method="GET">
<select>
<option value="Vital Signs">Vital Signs</option>
<option value="Cancer Signs">Cancer Signs</option>
</select><br><br>
<input type="submit" value="Select Template" class="addehr">
</form>
I have defined form class as:
class templateselect(forms.Form):
CHOICES = (
('Vital Signs', 'Vital Signs'),
('Cancer Signs', 'Cancer Signs'),
)
template = forms.ChoiceField(widget=forms.Select, choices=CHOICES)
Now I want to get selected text from this form in view compcreate. So I used:
def compcreate(request):
if request.method == 'GET':
form = templateselect(request.GET)
print("a")
if form.is_valid():
print("b")
template = str(form.cleaned_data["template"])
but it cant get past the if form.is_valid(): part as 'a' is printed but 'b' is not printed on console. What is the problem? How can I get the selected text in compcreate()?
The proper way to render your form would be to pass it in to your template via the context object and change your template. For example:
<form action="{% url 'ehrs:compcreate' %}" method="GET">
{{ form.as_p }}<br><br>
<input type="submit" value="Select Template" class="addehr">
</form>
If you want to stick with your current setup, looking at the html produced by the previous solution suggests that adding a name (equal to the name of your field in the Form class declaration) to your select field should also work:
<form action="{% url 'ehrs:compcreate' %}" method="GET">
<select name="template">
<option value="Vital Signs">Vital Signs</option>
<option value="Cancer Signs">Cancer Signs</option>
</select><br><br>
<input type="submit" value="Select Template" class="addehr">
This approach works with ModelForm and POST request:
def compcreate(request):
if request.method == 'POST':
form = templateselect(request.POST)
if form.is_valid():
ts = form.save(commit=False)
print(ts.template)
Let me know if it works in your case.

Django - Multiple Choice Field - Form Not saving

I have a Django application and want to display multiple choice checkboxes in a user's profile. They will then be able to select multiple items.
But I am not able to save the form that is created. Can anyone help?
My models.py looks like this:
class multiChoice(models.Model):
user=models.ForeignKey(User)
Options = (
("AUT", "Australia"),
("DEU", "Germany"),
("NLD", "Neitherlands")
)
Countries = models.ManyToManyField(Choices,choices=Options)
User.multiChoice=property(lambda u:multiChoice.objects.get_or_create(user=u)[0])
forms.py:
class multiChoiceForm(forms.Form):
Countries = forms.ModelMultipleChoiceField(queryset=Choices.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
class Meta:
model=multiChoice
fields=("Countries")
views.py:
def multiChoice_v1(request):
args = {}
args.update(csrf(request))
if request.method == 'POST':
form = multiChoiceForm(request.POST)
if form.is_valid():
countries = form.cleaned_data.get('countries')
countries.save()
form.save_m2m()
return HttpResponseRedirect('/accounts/loggedin/')
else:
form=multiChoiceForm()
args={}
args.update(csrf(request))
args['form']=form
return render_to_response('editprofile_v2.html', args)
urls.py - snippet of the multi-choice view alone:
url(r'^accounts/profile_v2/$', 'guitarclubapp.views.multiChoice_v1'),
editprofile_v2.html:
<html>
<form method='post'>{% csrf_token %}
<label> Countries </label>
<select name="Countries" id="Countries" class="multiselect" multiple="multiple">
<option value="AUT" selected="selected">Austria</option>
<option value="DEU" selected="selected">Germany</option>
<option value="NLD" selected="selected">Netherlands</option>
</select>
<input type='submit' value='submit'>
</form>
</html>
Is there anything that I am missing out (or) have done anything wrong?
Should I change the way I am defining my model?
Any help or references would be greatly appreciated.
Thanks in advance.

Categories

Resources