Django form using bootstrap - html

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'
}
))

Related

How to set the name value and choice field value in html form fields without using django-forms?

Suppose I want to give user 2 option in html select tag.
i want help to, full MVC implementation in Python.
i dont want to use django form.
Sample html code:
<form method="POST">
<div class="form-row">
<div class="name">Name</div>
<div class="value">
<div class="input-group">
<input class="input--style-5" type="text" name="name" required>
</div>
</div>
</div>
<div class="form-row">
<div class="name">Applying In</div>
<div class="value">
<div class="input-group">
<div class="rs-select2 js-select-simple select--no-search">
<select name="subject" required>
<option disabled="disabled" selected="selected"> Applying Department</option>
<option>Backend</option>
<option>Mobile</option>
</select>
<div class="select-dropdown"></div>
</div>
</div>
</div>
</div>
Use option = request.GET['subject'] in a view.py which will be invoked on form submission. You will get only one option because you are selecting single option in template.
suppose we have a model like this:
from django.db import models
from django import forms
class Foo(models.Model):
CHOICES= (
('choice_one', 'choice one'),
('choice_two', 'choice two'),
)
user_choices= models.CharField(max_length=10, choices=CHOICES)
class FooForm(forms.ModelForm):
class Meta:
model = Foo
fields = ['user_choices']
views:
from django.shortcuts import redirect, render
from . import models
def user_choices(request):
url = request.META.get('HTTP_REFERER') # get last url
if request.method == 'POST':
form = models.FooForm(request.POST)
if form.is_valid():
data = models.Foo()
data.user_choices= request.GET.get('user_choices')
data.save()
return redirect(url)
return render(request, 'user_choices.html', context)
then in the template:
<form action="{% url 'app_name:user_choices' %}" method="POST"> # url to above function
<select name ='user_choices'>
<option name="user_choices" value="choice_one">choice one</option>
<option name="user_choices" value="choice_two">choice two</option>
</select>
<button type="submit">submit</button>
</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;
}
});
});

change value form after press button (django)

I have a form where when I select my option and press the "Select" button I need to update the form with the data of my selected object. My problem is that when I do my static object the {% for%} already marks me an error because it is not a list. I do not know if this is the correct way to do it.
This is running Mysql, django 1.11 and python 2.7.15
views.py
def administrador(request):
alumno = Alumnos.objects.all()
mapa = mapas.objects.all()
competencias = Competencias.objects.all()
context = {
'alumno': alumno,
'mapa': mapa,
'competencias': competencias
}
return render(request, 'competencias_app/competencias.html', context)
def seleccion(request):
alumno = Alumnos.objects.get(pk=request.POST['Nombre'])
context = {'alumno': alumno}
return render(request, 'competencias_app/competencias.html', context)
competencias.html
<form action="/seleccion" method="POST">
{% csrf_token %}
<div>
<select id="carrera" name="Carrera">
<option value="1">TICS</option>
<option value="2">Carrera</option>
<option value="3">Carrera</option>
<option value="4">Carrera</option>
<option value="5">Carrera</option>
</select>
</div>
<div>
<select id="Alumno" name="Nombre">
{% for alumno in alumno %}
<option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option>
{% endfor %}
<input type="submit" name="Seleccionar">
</select>
</div>
<label for="ID">ID</label>
<input type="input" name="id" disabled value="{{alumno.idAlumnos}}"><br>
<label for="apellidos">Apellidos</label>
<input type="input" name="apellidos" disabled value="{{alumno.apellidos}}"><br>
<label for="Correo">Correo</label>
<input type="input" name="Correo" disabled value="{{alumno.correo}}"><br>
</form>
the output when press "seleccionar" is
Request Method: POST
Request URL: http://localhost:8000/seleccion
Django Version: 1.11.21
Exception Type: TypeError
Exception Value:
'Alumnos' object is not iterable
Images for more details
I solve my problem with one if, i don't know if is the correct solution but works!
competencias.html
<form action="/seleccion" method="POST">
{% csrf_token %}
<div>
<select id="carrera" name="Carrera">
<option value="1">TICS</option>
<option value="2">Carrera</option>
<option value="3">Carrera</option>
<option value="4">Carrera</option>
<option value="5">Carrera</option>
</select>
</div>
<div>
<select id="Alumno" name="Nombre">
{% if alumno|length > 1 %}
{% for alumno in alumno %}
<option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option>
{% endfor %}
{% else %}
<option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option>
{%endif%}
<input type="submit" name="Seleccionar">
</select>
</div>
<label for="ID">ID</label>
<input type="input" name="id" disabled value="{{alumno.idAlumnos}}"><br>
<label for="apellidos">Apellidos</label>
<input type="input" name="apellidos" disabled value="{{alumno.apellidos}}"><br>
<label for="Correo">Correo</label>
<input type="input" name="Correo" disabled value="{{alumno.correo}}"><br>
</form>
views.py
def administrador(request):
alumno = Alumnos.objects.all()
mapa = mapas.objects.all()
context = {
'alumno': alumno
}
return render(request, 'competencias_app/competencias.html', context)
def seleccion(request):
lstCompetencias = []
alumno = Alumnos.objects.get(pk=request.POST['Nombre'])
for p in Competencias.objects.raw('Select * from test_app_competencias where idmapasfk_id = %s', [request.POST['Nombre']]):
lstCompetencias.append(p)
context = {
'alumno' : alumno,
'competencias' : lstCompetencias
}
return render(request, 'competencias_app/competencias.html', context)

Django Login using user class redirecting to the same page

I am new to Django and I am developing a website that has some functions like Login and Register. I have already tried the register function (registrarUsuario) and I think it is working properly but when I try to Log In using the account created it redirects me to the same page and the user does not Log In (I checked this with request.user.is_authenticated). I have researched a lot and I haven't found a solution yet.
Note: the login used to work with predefined users that I created with django (just username and password)... but I am using my own model WITH THE User Class
I will post the register User code just in case the problem is there.
VIEWS
def registroUsuarios(request): #REGISTER USER FUNCTION
form=RegistrarUsuario(request.POST)
if form.is_valid():
data=form.cleaned_data
regDB=User.objects.create_user(data.get("username"),data.get("password"))
usuario=Usuario(user=regDB,correo=data.get("correo"),nombreCompleto=data.get("nombreCompleto"),direccionUsuario=data.get("direccionUsuario"),perfil=data.get("perfil"))
regDB.save()
usuario.save()
usuarios=Usuario.objects.all()
form=RegistrarUsuario()
titulo="Mis Perris | Registro Usuarios"
return render(request,"registroUsuarios.html",{'titulo':titulo,'form':form,'usuarios':usuarios})
def ingresar(request): #LOG IN FUNCTION
titulo="Mis Perris | Login"
form=Login(request.POST or None)
if form.is_valid():
data=form.cleaned_data
user=authenticate(username=data.get("username"),password=data.get("password"))
if user is not None:
login(request,user)
return redirect('inicio')
return render(request,"login.html",{'form':form,'titulo':titulo})
MODELS
class Usuario(models.Model): #USER CLASS
user=models.OneToOneField(User,on_delete=models.CASCADE)
#username=models.CharField(primary_key=True, max_length=20)
#password=models.CharField(max_length=20)
correo=models.EmailField(max_length=30)
nombreCompleto=models.CharField(max_length=30)
direccionUsuario=models.CharField(max_length=30)
perfil=models.CharField(max_length=20,default="Guest")
FORMS
perfiles=(
('Administrador','Administrador'),
('Guest','Guest'),
('Usuario','Usuario'),
)
class RegistrarUsuario(forms.Form): #REGISTER USER
username=forms.CharField(widget=forms.TextInput(),label="Nombre de Usuario")
password=forms.CharField(widget=forms.PasswordInput(),label="Contraseña")
correo=forms.EmailField(widget=forms.EmailInput(),label="Correo")
nombreCompleto=forms.CharField(widget=forms.TextInput(),label="Nombre Completo")
direccionUsuario=forms.CharField(widget=forms.TextInput(),label="Dirección")
perfil=forms.ChoiceField(choices=perfiles)
class Login(forms.Form):
username=forms.CharField(widget=forms.TextInput(),label="Nombre de Usuario")
password=forms.CharField(widget=forms.PasswordInput(),label="Contraseña")
LOGIN.HTML
{% extends "master.html" %}
{% load static %}
{% block Login %}
<section class="login-block">
<div class="logincontainer">
<div class="row">
<div class="col-md-4 register-sec">
<h2 class="text-center">Iniciar Sesión</h2>
<form method="POST" class="login-form">
<div class="col-10">
{% csrf_token %}
{{form.as_p}}
</div>
<div class="form-check col-md-11">
<button type="submit" class="btn btn-login float-left">Iniciar Sesión</button>
<input class="btn btn-login float-right" type="button" value="Registrarse" onclick="location.href = '{% url 'registro' %}';"></button>
</div>
</form>
<div class="copy-text">¿Olvidaste tu Contraseña? Clic AQUÍ</div>
</div>
</div>
</div>
</section>
{% endblock %}
REGISTROUSUARIOS.HTML (Register user)
{% extends "master.html" %}
{% load static %}
{% block RegistroUsuarios %}
<section class="register-block">
<div class="registercontainer">
<div class="row">
<div class="col-md-12 register-sec">
<h2 class="text-center">Registro Usuarios</h2>
<form method="POST" class="register-form">
<div class="col-6">
{% csrf_token %}
{{form.as_p}}
</div>
<div class="form-check col-md-6">
<button type="submit" class="btn btn-register float-right">Registrarse</button>
</div>
</form>
</section>
{% endblock %}
P.S: Sorry if the code is in spanish
EDIT: I have already tried deleting the DB and migrations files and doing makemigrations and migrate again
EDIT 2: I listed all the users I have registered and they are being registered correctly so it seems that the problem is in the login. I also created a superuser using django commands and it works! But I still can not find the error

How to display the content on the form in django

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 %}