How to display the content on the form in django - html

I try to display the content on the form in Django. I want to display the result to response when input the email from search bar. How do display the result to response?
views.py
from django.shortcuts import render
from django.utils import timezone
import requests
from .models import StorageList
from django.db.models import Q
def xGET(x_auth_user, x_auth_key):
url = 'https://ssproxy.ucloudbiz.olleh.com/auth/v1.0'
headers = {'X-Storage-User': x_auth_user, 'X-Storage-Pass': x_auth_key}
response = requests.get(url, headers=headers)
print response.headers
def storage_list(request):
today = timezone.now().date()
queryset_list = StorageList.objects.all()
for data in queryset_list:
MEM_ID = data.mem_id
MEM_SQ = data.mem_sq
X_AUTH_USER = data.x_auth_user
X_AUTH_KEY = data.x_auth_key
URL = data.x_storage_url
API_KEY = data.accesskey
query = request.GET.get('q')
if query == MEM_ID:
xGET(X_AUTH_USER, X_AUTH_KEY)
return render(request, "storage/storage_list.html")
template
{% extends "base.html" %}
{% block content %}
<div class='col-sm-6 col-sm-offset-3'>
<h1>{{ title }}</h1>
<form method='GET' action='' class='row'>
<div class='col-sm-6'>
<div class='input-group'>
<input class='form-control' type='text' name='q' placeholder='Search posts' value='{{ request.GET.q }}'/>
<span class='input-group-btn'>
<!-- <input class='btn btn-default' type='submit' value='Search' /> -->
<button class='btn btn-default' type='submit'>Search <i class="fa fa-search"></i></button>
</span>
</div>
</div>
</form>
{% endblock content %}
my url page
response
[23/Jun/2016 16:40:49] "GET /storage/ HTTP/1.1" 200 5844
{'Content-Length': '126', 'X-Trans-Id': 'tx76ab9e218a2c4e4c9ed5642c89ae1033', 'X-Auth-Token-Expires': '77233', 'X-Auth-Token': 'AUTH_tkb6e12312141494254', 'Connection': 'close', 'X-Storage-Token': 'AUTH_t1231321131413c9b94254', 'Date': 'Thu, 23 Jun 2016 07:40:52 GMT', 'X-Storage-Url': 'https://ssproxy.ucloudbiz.olleh.com/v1/AUTH_be2b4d4d-3e5d-487c-bf31-bc42f7cf9ce8', 'Content-Type': 'text/html; charset=UTF-8'}

I don't know why you don't use existed django framework functions like forms. But to send response to "storage/storage_list.html" you could try:
def xGET(x_auth_user, x_auth_key):
url = 'https://ssproxy.ucloudbiz.olleh.com/auth/v1.0'
headers = {'X_Storage_User':x_auth_user, 'X_Storage_Pass':x_auth_key}
response = requests.get(url, headers=headers)
return response
def storage_list(request):
today = timezone.now().date()
queryset_list = StorageList.objects.all()
for data in queryset_list:
MEM_ID = data.mem_id
MEM_SQ = data.mem_sq
X_AUTH_USER = data.x_auth_user
X_AUTH_KEY = data.x_auth_key
URL = data.x_storage_url
API_KEY = data.accesskey
query = request.GET.get('q')
if query == MEM_ID:
response = xGET(X_AUTH_USER, X_AUTH_KEY)
# if user matched send the response
return render(request, "storage/storage_list.html",context = response)
return render(request, "storage/storage_list.html")
template
{% extends "base.html" %}
{% block content %}
<div class='col-sm-6 col-sm-offset-3'>
<h1>{{ title }}</h1>
<form method='GET' action='' class='row'>
<div class='col-sm-6'>
<div class='input-group'>
<input class='form-control' type='text' name='q' placeholder='Search posts' value='{{ request.GET.q }}'/>
<span class='input-group-btn'>
<!-- <input class='btn btn-default' type='submit' value='Search' /> -->
<button class='btn btn-default' type='submit'>Search <i class="fa fa-search"></i></button>
</span>
</div>
</div>
</form>
{% if X_Storage_User and X_Storage_Pass %}
User: {{X_Storage_User}}
Pass: {{X_Storage_Pass}}
{% endif %}
{% endblock content %}

Related

Modifying a dropdown menu option in a form Django

I have a dropdown menu that i'm using to fill a field on a form, but, as i'm just starting with django and html, i'm using another form to edit and update the data of the previous form. But i cant make the dropdown menu to work on that second form.
The model:
class Orden(models.Model):
STATUS = (
('En espera', 'En espera'),
('En proceso', 'En proceso'),
('Terminado', 'Terminado'),
('Entregado', 'Entregado'),
)
num_orden = models.CharField(max_length=20, default='')
fechain = models.CharField(max_length=30, default='')
fechaout = models.CharField(max_length=30, default='')
instrumento = models.CharField(max_length=30, default='')
marca = models.CharField(max_length=20)
referencia = models.CharField(max_length=30, default='')
serial = models.CharField(max_length=15, default='')
encargado = models.CharField(max_length=50, default='')
abono = models.CharField(max_length=15, default='')
procesos = models.TextField(default='')
estado = models.CharField(max_length=50, null=True, choices=STATUS) # <--- This one
client = models.ForeignKey(Cliente, on_delete=models.CASCADE, default='', related_name="client")
The view related to the first form:
def ordenfill(request, client_id):
if request.method == 'POST':
orden = ordenForm(request.POST)
if orden.is_valid():
orden.instance.client_id = client_id
init = orden.save()
return redirect('ordenview', id=init.id)
else:
orden = ordenForm()
client = Cliente.objects.get(id=client_id)
context = {
'orden': orden,
'client': client,
}
return render(request, 'ordenfill.html', context)
The template part asociated to that dropdown menu:
<form method="POST" class="post-form" action="{% url 'ordenfill' client.id %}">
{% csrf_token %}
<div class="container">
<br>
.
.
.
<div class="form-group row">
<label class="col-sm-2 col-form-label">Estado</label>
<div class="col-sm-4">
{{orden.estado}}
</div>
</div>
</div>
</form>
Image of the First Form
Dropdown menu on the first form
The view related to the second form:
def ordenupd(request, id):
orden = Orden.objects.get(id=id)
status = Orden.STATUS
context = {
'orden': orden,
'status': status,
}
return render(request, "ordenupd.html", context)
Edit: the view that saves the changes in the second form
def ordenmod(request, id):
orden = get_object_or_404(Orden, id=id)
if request.method == 'GET':
orden = ordenForm(instance=orden)
return redirect("ordenview", id=id)
else:
orden = ordenForm(request.POST, instance=orden)
print(orden.errors)
if orden.is_valid():
orden.save()
return redirect("ordenview", id=id)
else:
orden = clienteForm()
return redirect("ordenview", id=id)
The template part asociated to the dropdown menu of that view:
<form method="POST" class="post-form" action="/ordenmod/{{orden.id}}">
<input type="hidden" name="id" id="id" required maxlength="20" value="{{orden.id}}"/>
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Estado</label>
<div class="col-sm-4">
<select name="select_path" id="select_path">
<option value="{{orden.estado}}">{{orden.estado}}</option>
{% for items in status %}
<option value ="{{orden.estado}}">{{orden.estado}}</option>
{% endfor %}
</select>
</div>
</div>
</div>
</form>
And the webpage of that view:
Dropdown menu on the second form
How can i make that dropdown menu on the second form to work like the one on the first form?
#chnage your view as below
from .models import STATUS
def ordenupd(request, id):
status = STATUS
context = {
'status': status,
}
return render(request, "ordenupd.html", context)
#change your HTML form template as below
<form method="POST" class="post-form" action="/ordenmod/{{orden.id}}">
<input type="hidden" name="id" id="id" required maxlength="20" value="{{orden.id}}"/>
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Estado</label>
<div class="col-sm-4">
<select name="select_path" id="select_path">
{% for items in status %}
<option value ="{{item.1}}">{{item.1}}</option>
{% endfor %}
</select>
</div>
</div>
</div>
</form>

Fetch preventing rendering template in the controller

I'm working on a project for a class and I have starter code that I am editing. they way its supposed to work is that when the user creates a venue it goes to the home page with a message saying venue x has been listed. Once I add the post request in the new_venue.html it does nothing after I click the submit button nothing happens, but I know its doing something because the app.py prints the name that signed up.
Below is Code from the new_venue.html.
I added the script section and the post request
{% extends 'layouts/main.html' %}
{% block title %}New Venue{% endblock %}
{% block content %}
<div class="form-wrapper">
<form id="venueInfo" method="post" class="form">
<h3 class="form-heading">List a new venue <i class="fa fa-home pull-right"></i></h3>
<div class="form-group">
<label for="name">Name</label>
{{ form.name(id='name', class_ = 'form-control', autofocus = true) }}
</div>
<div class="form-group">
<label>City & State</label>
<div class="form-inline">
<div id='city' class="form-group">
{{ form.city(class_ = 'form-control', placeholder='City', autofocus = true) }}
</div>
<div id='state' class="form-group">
{{ form.state(class_ = 'form-control', placeholder='State', autofocus = true) }}
</div>
</div>
</div>
<div id='address' class="form-group">
<label for="address">Address</label>
{{ form.address(class_ = 'form-control', autofocus = true) }}
</div>
<div id='phone_num' class="form-group">
<label for="phone">Phone</label>
{{ form.phone(class_ = 'form-control', placeholder='xxx-xxx-xxxx', autofocus = true) }}
</div>
<div id="genres" class="form-group">
<label for="genres">Genres</label>
<small>Ctrl+Click to select multiple</small>
{{ form.genres(class_ = 'form-control', autofocus = true) }}
</div>
<div id="fb_link" class="form-group">
<label for="genres">Facebook Link</label>
{{ form.facebook_link(class_ = 'form-control', placeholder='http://', autofocus = true) }}
</div>
<input type="submit" value="Create Venue" class="btn btn-primary btn-lg btn-block">
</form>
<script type="text/javascript">
document.getElementById("venueInfo").onsubmit=function(e){
e.preventDefault();
fetch('/venues/create',{
method:'POST',
body:JSON.stringify({
'name': document.getElementById('name').value,
'city': document.getElementById('city').value,
'state': document.getElementById('state').value,
'address': document.getElementById('address').value,
'phone_num': document.getElementById('phone_num').value,
'genres': document.getElementById('genres').value,
'fb_link': document.getElementById('fb_link').value,
}),
headers: {'Content-type': 'application/json'}
})
.then(function(){
})
}
</script>
</div>
{% endblock %}
below is the code from app.py
#app.route('/venues/create', methods=['GET'])
def create_venue_form():
form = VenueForm()
return render_template('forms/new_venue.html', form=form)
#app.route('/venues/create', methods=['POST'])
def create_venue_submission():
name = request.get_json()['name']
print(name)
flash('Venue ' + request.form['name'] + ' was successfully listed!')
return render_template('pages/home.html')
flash messages work with redirection, refer to https://flask.palletsprojects.com/en/1.1.x/patterns/flashing/#simple-flashing
so instead rendering the template, return redirection object to the home page:
#app.route('/venues/create', methods=['POST'])
def create_venue_submission():
# name = request.get_json()['name']
name = request.values.get('name')
print(name)
flash('Venue ' + request.form['name'] + ' was successfully listed!')
# return render_template('pages/home.html')
return redirect(url_for('home')) # -- HERE --
Update
i think you are doing things the wrong way, you don't need the javascript to submit the form data via ajax post since ajax is used to update the page without reloading it (btw you didn't put any logic in .then(function(){}) callback to show up the message), but after submitting the form you want to redirect the user to the home page with a flash message so the ajax approach you are using is the wrong approach, just remove or comment the javascript code block and add the action to the form
<form id="venueInfo" method="post" action="{{ url_for('create_venue_submission') }}" class="form">
...
and in your function create_venue_submission() you should change
name = request.get_json()['name']
to
name = request.values.get('name')
# other fields
name = request.values.get('name')
city = request.values.get('city')
state = request.values.get('state')
address = request.values.get('address')
phone_num = request.values.get('phone_num')
genres = request.values.get('genres')
fb_link = request.values.get('fb_link')
see this wiki https://stackoverflow.com/a/16664376/12368419
If you are submitting your form via ajax, you will need to redirect in the success portion of the ajax call. Also, keep in mind that flash will not work via ajax. You will need to use the standard form post.
$.ajax({
'url': 'post_url',
success: function(msg){
//read the msg here and determine if success or not then redirect
}
})
This will not work when doing an ajax form post:
return redirect(url_for('index'))
If you use the standard (pseudo code) without posting via ajax, it will redirect:
<form method=post action=route>
<input type=submit>
</form>

Extracting data using ajax from a database in django and then display it in view

How should I extract data from a database using ajax in Django and display it in view in the form of charts. I wanna select items from dropdown options and then display those selected data in the webpage in the form of charts.
Can anyone please guide me in this.
My codes are:
index.html:
<div class="row">
<form class="form-row" action="{{ }}" method="post">
{% csrf_token %}
<div class="form-group col-md-2">
<select class="form-control select2" >
<option>Select Major Head</option>
{% for major in majors %}
<option value="{{ major.pk }}">{{ major.pk }}: {{ major.description } </option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<input type="submit" value="Display">
</div>
</form>
</div>
.
.
.
<div class="card-body" >
<div id="chart">
<embed type="image/svg+xml" src= {{ chart|safe }} />
</div>
views.py:
def home(request):
majors = Major.objects.filter(percentages__isnull=False).distinct().order_by("pk")
if request.method == 'POST':
form = request.POST.get('be_nextyr_total')
line_chart = pygal.Line(width=1500)
line_chart.title = 'Budget Estimation'
context = {
"chart": line_chart.render_data_uri(),
'majors': majors
}
return render(request, "website/index.html" , context )
charts.js
$('form').on('Display',function(e){
e.preventDefault();
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('action'),
data : $(this).serialize(),
success : function(data) {
// $(".printArea").empty().append(data).css('visibility','visible');
return data;
}
});
});

Django form using bootstrap

I have the following dictionary:
POSSIBLE_POSITIONS = (
('1', 'Brazo'),
('2', 'Muñeca'),
('3', 'Pierna'),
('4', 'Pie'),
)
This is used in the following form:
from interface.positions import *
from django import forms
class PositionForm(forms.Form):
position = forms.ChoiceField(choices = POSSIBLE_POSITIONS, label="", initial=1, widget=forms.Select())
This is the view that renders my html template:
def add(request):
return render(request, 'interface/add_user.html', {'device_list': Device.objects.all(), 'form': PositionForm()})
And this is the html code:
<body>
<form class="square" action="{% url 'interface:add_perform' %}" method="post">
{% csrf_token %}
<div class="form-group">
<label>ID paciente</label>
<input autofocus class="form-control" name="user_id" placeholder="Ejemplo: 58192">
</div>
<div class="form-group">
<label>Dispositivo a usar</label>
<select name="device_id" class="form-control">
{% for device in device_list %}
<option>{{ device.id }}</option>
{% endfor %}
<option selected="selected"> Sin dispositivo </option>
</select>
</div>
<div class="form-group">
<label>Posición dispositivo</label>
<div class="form-control"> {{ form }} </div>
</div>
<div class="form-group square_button">
<button class="btn btn-success btn-md form-control" type="submit"> Crear Paciente </button>
</div>
</form>
</body>
The problem is that as you can see on the following image, this isn't bootstrap css, so it is really weird. How I can fix that?
I want it like the 'Dispositivo a usar' selector.
SOLVED
I found the solution here: Define css class in django Forms
Loop through form object and set the form-control class in select tag. It should work.
def __init__(self, *args, **kwargs):
super(PositionForm, self).__init__(*args, **kwargs)
self.fields['position'].widget.attrs['class'] = 'form-control'
Can be solved adding the css class directly on the form:
class PositionForm(forms.Form):
position = forms.ChoiceField(choices = POSSIBLE_POSITIONS, label="", initial=1, widget=forms.Select(
attrs={
'class': 'form-control'
}
))

How to use POST in Django

I use Django 1.11.3 and python2.7
I want write a easy message board
and here is my code
<form name='my form' action='/talkpost/' method='POST'>
{% csrf_token %}
{% for m in moods %}
<input type='radio' name='mood' value='{{ m.status }}'>{{ m.status }}
{% endfor %}
<textarea name='user_post' rows=3 cols=70></textarea><br/>
<label for='user_id'>nickname:</label>
<input id='user_id' type='text' name='user_id'>
<label for='user_pass'>password</label>
<input id='user_pass' type='password' name='user_pass'><br/>
<input type='submit' value='submit'>
<input type='reset' value='reset'>
<input type="hidden" name="ok" value="yes">
</form>
urls.py
url(r'^talkpost/', talkpost),
url(r'^talk/', talk),
talk is just for user to see the from and talkpost is for Django to get the post
request
views.py
def talk(request):
template = get_template('talk.html')
moods = Mood.objects.all()
message = 'Leave some message!'
html = template.render(locals())
return HttpResponse(html)
def talkpost(request):
template = get_template('talk.html')
if 'ok' in request.POST:
user_id = request.POST['user_id']
user_pass = request.POST['user_pass']
user_post = request.POST['user_post']
user_mood = request.POST['mood']
message = 'success!'
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)
I try using {% csrf_token %} and RequestContext But i still get CSRF token missing or incorrect.
I have no idea how to fix it
add the following:
from django.views.decorators.csrf import csrf_protect
your function will be:
#csrf_protect
def talkpost(request):
template = get_template('talk.html')
if 'ok' in request.POST:
user_id = request.POST['user_id']
user_pass = request.POST['user_pass']
user_post = request.POST['user_post']
user_mood = request.POST['mood']
message = 'success!'
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)
more info here:
https://docs.djangoproject.com/ko/1.11/ref/csrf/#how-to-use-it