I'm making a post from a webpage that is generated dynamically from Django DB content. The data is put into a combo box and is supposed to send the customer id back to Django so I can parse some more queries with it and then display only the customers data that was selected.
However instead of retruning my post data it returns the csrf token instead of the posted data.
<form method='post' action='' id='customers'>
{% csrf_token %}
<select>
{% for item in customer %}
<option value={{ item.customer_id }} name='customer_id'>{{ item.customer_name }}</option>
{% endfor %}
<input type = 'submit' value='Edit'>
</select>
{{ post }}
{{post.customer_id}} #doesnt work either.
this is what it returns:
<QueryDict: {u'csrfmiddlewaretoken': [u'CpzKrwmZsmfiiNHngNWDFSNxqUoBykYO']}>
def portal(request):
customers = Customer.objects.all()
if request.method == 'POST':
vm_groups = Vm_group.objects.all()
vms = Vm.objects.all()
selected_customer = request.POST.copy()
#selected_customer_id = selected_customer['customer_id']
post = selected_customer
context = Context({'customer': customers, 'vm_groups':vm_groups, 'vms':vms, 'post':post,
})
return render(request, 'portal.html', context)
else:
context = Context({'customer': customers,})
return render(request, 'portal.html', context)
Also how would I get just the customer_id from the returned data once it works correctly?
selected_customer = request.POST.copy()
selected_customer_id = selected_customer['customer_id']
Like so?
You need to put the name attribute on the select element, not the option.
But you should probably be using Django's forms framework, anyway.
As #Daniel told that, You need to add name field to select tag not for option tag,
<select name='customer_id'>
{% for item in customer %}
<option value={{ item.customer_id }} >{{ item.customer_name }}</option>
{% endfor %}
<input type = 'submit' value='Edit'>
</select>
Related
i have a dropdown list having the store name,when i select a store from that i need store_key from that select value
def store_list(request):
displaystores=stores.objects.all()
if request.POST:
store_pk_list = request.POST.getlist('stores', None)
print(request.POST.getlist('stores.unit_key', None))
selected_store_obj_list = stores.objects.filter(pk__in=store_pk_list)
print(selected_store_obj_list)
return render(request,'storelist.html',{'stores':displaystores})
html
<form action="" method="post">
{% csrf_token %}
--store_name--
{%for result in stores%}
<option value="{{result.unit_key}}">{{result.unit_name}}</option>
{%endfor%}
</select>
Once you get the form through the POST, validate the data and then use them,
Check this,
getting value from form field
I am trying to set the initial choices in a dropdown, on profile edit for selecting Business type. But I want the dropdown to already have the current instance' selections already chosen. But I just cant figure out how to render this on the frontend. I heard of a select option that jinja template offers, to do this?
I will take a code snippet from my app,
def edit_profile(request):
request_user = request.user
# FOR SENDING USER TO SERVER
if request.method == 'POST':
template_name = 'business/profile_view.html'
first_name = request.POST['first_name']
business = request.POST.getlist('business_type', '')
if business == '':
pass
try:
user_obj = Account.objects.get(email=request.user)
""" Loop over business types and assign to user """
user_obj.business.clear()
for _business in business:
user_obj.business.add(_business)
return redirect('/auth/edit_profile/')
except Exception as e:
message = {"message": "Profile edit ERROR"}
return render(request, template_name, message)
# FOR SERVER TO USER
if request.method == 'GET':
template_name = 'business/profile_view.html'
context = dict()
user_obj = Account.objects.get(email=request.user)
context['business_type'] = user_obj.business
if request.path == '/auth/edit_profile/':
return render(request, template_name, context)
elif request.path == '/auth/edit_profile_edit/':
return render(request, 'business/profile_edit.html', context)
And my Template
<select class="selectpicker" name="business_type" multiple="multiple"title="Select a category">
{% for business in business_types %}
<option value="{{ business.id }}">{{ business.name }}</option>
{% endfor %}
</select>
You can add "selected" to your views context:
context['selected'] = business # or however you are identifying the selected
then in the html you can add the selected tag with an ifequal statement:
{% for business in business_types %}
<option {% if ifequal business.name selected.name %}selected{% endif %}
value="{{ business.id }}">{{ business.name }} </option>
{% endfor %}
or if the context is a list, then you can use {% if business in selected_businesses %}
{% for business in business_types %}
<option {% if business in selected_businesses %}selected{% endif %}
value="{{ business.id }}">{{ business.name }} </option>
{% endfor %}
I'd recommend looking into Django's forms system. It does a lot of the work of setting up forms, rendering widgets, and even validating your data for you. You can also send forms with the current instance already filled in
So I have a form that updates a key_instance object with a borrower. Currently my app needs the user to enter the name of the borrower, but I want it to display a dropdown list of data from another model the user model to select from, is there anyway to do this in a class based view? Here are my views.py and my template. What I was thinking is that I would like to use a get_list_or_404 on the user model and display it as a drop down list in the template and use that selection to populate the form field.
I manged to get the dropdown list to display in my template but I'm not sure as to how to save that value in my views.
Does anyone know if this is the right way or if this is doable? Thank you!!
views.py
def submit_key_request(request, pk):
"""
View function for renewing a specific keyInstance by admin
"""
key_inst=get_object_or_404(KeyInstance, pk=pk)
names = get_list_or_404(Users)
# If this is a POST request then process the Form data
if request.method == 'POST':
# Create a form instance and populate it with data from the request (binding):
form = UpdateKeyForm(request.POST)
# Check if the form is valid:
if form.is_valid():
# process the data in form.cleaned_data as required (here we just write it to the model due_back field)
key_inst.is_requested = True
key_inst.status = 'r'
key_inst.date_requested = datetime.date.today()
key_inst.borrower = form.cleaned_data['borrower']
key_inst.save()
# redirect to a new URL:
return HttpResponseRedirect(reverse('all-available-keys') )
# If this is a GET (or any other method) create the default form.
else:
form = UpdateKeyForm(initial={'borrower': 'N/A'})
return render(request, 'catalog/keyinstance_request_update.html', {'form': form, 'keyinst':key_inst})
template
{% extends "base_generic.html" %}
{% block content %}
<div class="wrapper">
<div class="centered"> <h1>Request Keys For Room: {{keyinst.roomkey}}</h1></div>
<div class="square-box">
<div class="square-content">
<form action="" method="post" >
{% csrf_token %}
<table style="display: inline-flex">
{{ form}}
</table>
<select name = 'name'>
{% for name in names %}
<option value="{{ name }}">{{ name }}</option>
{% endfor %}
</select>
<p>
(Please use their login name i.e. <b>{{ user.get_username }}</b>)
</p>
<p><input required id="checkBox" type="checkbox" onclick="validate()"> I accept the terms and conditions</p>
<p id="text" style="display:none">You Have Agreed To the Terms and Conditions</p>
<input type="submit" value="Submit" />
</form>
</div>
</div>
</div>
{% endblock %}
Here is how I manged to do it, Not sure if this is the best 'pythonic' or best practice. Please let me know if it's not.
my views.py
def submit_key_request(request, pk):
"""
View function for renewing a specific keyInstance by admin
"""
key_inst=get_object_or_404(KeyInstance, pk=pk)
names = get_list_or_404(User)
# If this is a POST request then process the Form data
if request.method == 'POST':
name = request.POST['name']
key_inst.is_requested = True
key_inst.status = 'r'
key_inst.date_requested = datetime.date.today()
key_inst.borrower = name
key_inst.save()
return HttpResponseRedirect(reverse('all-available-keys') )
# If this is a GET (or any other method) create the default form.
else:
pass
return render(request, 'catalog/keyinstance_request_update.html', {'keyinst':key_inst, 'names':names})
template
{% extends "base_generic.html" %}
{% block content %}
<div class="wrapper">
<div class="centered"> <h1>Request Keys For Room: {{keyinst.roomkey}}</h1></div>
<div class="square-box">
<div class="square-content">
<form action="" method="post" >
{% csrf_token %}
</br>
<select name = 'name' required>
{% for key in names %}
<option value="{{ key }}">{{ key }}</option>
{% endfor %}
</select>
<p>
(Please use their login name i.e. <b>{{ user.get_username }}</b>)
</p>
<p><input required id="checkBox" type="checkbox" onclick="validate()"> I accept the terms and conditions</p>
<p id="text" style="display:none">You Have Agreed To the Terms and Conditions</p>
<input type="submit" value="Submit" />
</form>
</div>
</div>
</div>
{% endblock %}
I have a model with a lot of fields. I only have a few fields I that I want to be required. So instead of the change list super long, I want to have a short change list then have admin actions that can give predefined subsets of the fields.
The initial action takes me to the correct page but when I submit the form it returns me to whatever page I designate, but doesn't update the fields. I am okay with tearing this down starting over again if needed. I think what I really need to know, what do I put in the action="" portion of the html to have the recursion work properly?
I am using django 1.7. I have to obfuscate a lot of my fields as a cya thing since I am working in a heavily information secure field.
Here is my admin.py
class CredentialAdmin(admin.ModelAdmin):
fields = ['reservedBy','reserveto']
list_display = ['reservedBy','reserveto']
class reserveToFormAdmin(forms.Form):
reservedBy = forms.CharField(widget=forms.Textarea, max_length=50)
reserveto = forms.DateTimeField(widget=forms.DateTimeInput)
def reserveCred(self, request, queryset):
form = None
plural = ''
if 'submit' in request.POST:
form = self.reserveToFormAdmin(request.POST)
for f in form.fields:
print f
print form.is_valid()
print form.errors
if form.is_valid():
reservetos = form.cleaned_data['reserveto']
reservedBys = form.cleaned_data['reservedBy']
print "hello"
count = 0
for cred in queryset:
cred.reserveto = reservetos
cred.reservedBy = reservedByss
cred.save()
count += 1
if count != 1:
plural = 's'
self.message_user(request, "Successfully reserved %s cred%s." % (count, plural))
return HttpResponseRedirect(request.get_full_path(),c)
if not form:
form = self.reserveToFormAdmin(initial={'_selected_action' : request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})
return render(request,'admin/reserveCreds.html',{'creds':queryset, 'form':form, 'path':request.get_full_path()})
reserveCred.short_description = "Reserve Selected Creds"
actions = [check_out_a_cred,check_in_a_cred,audit_creds,CompareAudits,reserveCred]
reserveCreds.html
{% extends "admin/base_site.html" %}
{% block content %}
<p>How long and which department to reserver creds:</p>
<form action="{{ path }}" method="post">{% csrf_token %}
{{ form }}
<input type="submit" name="submit" value="submit" />
<input type="button" value = "Cancel" />
</form>
<h2> reserving: </h2>
<ul>
{% for cred in creds %}
<li> {{ cred.userid }} </li>
{% endfor %}
</ul>
{% endblock %}
I'm quite new to Django, so I aplogize if I am making dumb mistakes.
Here is the code I have so far:
For views.py:
def bylog(request):
if request.POST.get('Filter'):
return render(request, 'index.html', context)
filtered_login = Invalid.objects.values_list('login').distinct()
filtered = []
for item in filtered_login:
filtered.append(item[0])
results = {'results': results, 'filtered': filtered}
return render(request, 'bylog.html', context)
Here is a snippet of bylog.html:
<select id>"dropdown">
{% for item in filtered %}
<option value={{ item }}">{{ item }}</option>
{% endfor %}
</select>
<input type="submit" value="Filter" name="Filter" />
My main goal is to get the value from the drop down list, and after the user clicks the Filter button, the value gets passed to another template.
Is that even possible?
Thanks for you help.
The basic for your goal I supose it is to manage POST in django, meaning that you want to send any data/variables from a template to a view and then do any operation with it (send it to another template, or store...)
The basic for this is(Using HTML form, not Django form):
- Create a HTML form in the template
- Add the selects/inputs with the data you want to manage and a button/input to make the post
- Manage the post in the view
EXAMPLE
template form
<form id="" method="post" action=".">
{% csrf_token %}
<select id="any_name" name="any_name">"dropdown">
{% for item in filtered %}
<option value={{ item }}">{{ item }}</option>
{% endfor %}
</select>
<input type="submit" value="Filter" name="Filter" />
</form>
view.py
def your_view(request):
if request.method == 'POST': # If anyone clicks filter, you receive POST method
data = request.POST['any_name']
# Do what you need here with the data
# You can call another template and send this data
# You can change any_name for the variable you want, changing the name and id in the select
#Your view code
I recommend you to read about Django forms because if you need a bigger form, to manage the data of a model with a lot of fields, a Django Form will save you a lot of time
Working with Django Forms