Django Form issue - python-3.x

I am using Django to select language. One option works fine, but the other won't work
Option (1) Works fine .
<select name="language"
onchange="this.form.submit()" >
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% for lang in LANGUAGES %}
<option value="{{ lang.0 }}" {% if lang.0 == LANGUAGE_CODE %} selected="selected"{% endif %} >{{ lang.1 }} ({{ lang.0 }})</option>
{% endfor %}
</select>
Option 1 : Not working using (form Submit Button )
<form action="{% url 'set_language' %}" method="post" id="LanForm" name="LanForm">
{% csrf_token %}
<input class="lang" id="language" name="language" type="hidden" value="ar">
<input class="lang" id="setl" name="setl" type="submit" value="Go">
</form>
The select option works fine and change the language and redirect properly . But if I use the "Go" button , nothing is changing . I am wondering what is issue.

Firstly you do not set more than one node with the same id.
Secondly, you have kept the name of both submit and hidden inputs same i.e, 'language'.
Use the below snippet and test again
<form action="{% url 'set_language' %}" method="post" id="LanForm" name="language">
{% csrf_token %}
<input class="lang" id="language" name="language" type="hidden" value="ar">
<input class="lang" type="submit" value="Go">
</form>

I managed to fix this issue by modfing the form as follows,
<form action="{% url 'set_language' %}" method="post" id="LanForm" name="LanForm">
{% csrf_token %}
<input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }}" />
<input name="language" type="hidden" value="ar" />
<input class="lang" name="language2" type="button" value="Go" onclick=" document.getElementById('LanForm').submit();" >
</form>
No ids no names in the input field

Related

Not sure why im getting a (CSRF token missing or incorrect.) error in django

HTML:
{% extends 'generic.html' %}
{% load static %}
{% block title %}
<title>Projects - Login</title>
{% endblock %}
{% block content %}
<form action='#', method='post'>
{% csrf_token %}
<label for="username">Username</label>
<input type="text" name="username" id="username">
<label for="password">Password</label>
<input type="password" name="password" id="password">
<input type='submit' value='Login!'>
</form>
{% endblock %}
views.py:
def login(request):
return render(request, 'login.html')
urls.py:
urlpatterns = [
path('login/', views.login, name='login')
]
I have tried putting a #csrf_protect decorator on the login function. however I still get the same error.
Change the form in your template:
<form action="{% url 'your_app_name:login' %}" method="post">
{% csrf_token %}
...
</form>
or,
<form action="login/" method="post">
{% csrf_token %}
...
</form>

Django - Form is not saving to Db

I'm using for authentication extended AbstractUser and ModelForm. When I write on HTML page only {{ form }} everything works fine, the form is submitting, but in the following case I've added some stylings, but now nothing works. Please, help me find the reason.
HTML:
<form method='POST'>
{% csrf_token %}
<div class="sign-up-user">
<div class="sign-up-user-container">
<div class="sign-up-user-left">
<label for="">{{form.username.label}}</label>
{{form.username}}<br>
<label for="">{{form.password.label}}</label>
{{form.password}}<br>
<label for="">{{form.branch.label}}</label><br>
{{form.branch}}<br>
<label for="">{{form.license_number.label}}</label>
{{form.license_number}}<br>
<label for="">{{form.fin_number.label}}</label>
{{form.fin_number}}<br>
<label for="">{{form.voen_number.label}}</label>
{{form.voen_number}}<br>
</div>
</div>
<input type="submit" value="Register User" class="sign-up-btn">
</div>
</form>
Include two lines to your HTML to understand whats going wrong:
{{ form.errors }}
{{ form.non_field_errors }}
This will display any errors that are associated with the form. If they dont then in your views do the following:
form = YourForm()
if form.is_valid():
// Do things
else:
print (form.errors)
print(form.non_field_errors)
This will display some other errors that you are missing.

How can I get the value of an input in twig and reuse in an url that exists in the same page twig without the use jquery

<div class="product-btns">
<div class="qty-input">
<span class="text-uppercase">QTY: </span>
<input name="quantite" class="input" type="number">
</div>
{% if app.user != null %}
<a id="test" href="{{path('commande'{'id_product':listProduct.id ,'id_user':app.user.id,'quantite': })}}" class="primary-btn add-to-cart">
<i class="fa fa-shopping-cart"></i>
Add to Cart
</a>
{% else %}
I want to get value of input name="quantite" and reuse in path of parameter 'quantite'.
Have you tried ?
{{ form.vars.value.quantite }}

wrap checkboxes with custom html in Twig template using form entity fieldtype (Symfony3)

I would like to wrap the checkboxes with custom HTML in twig template when Symfony3 renders the form.
Instead of this:
<input type="checkbox" id="form_role_1" name="form[role][]" value="1" />
<label for="form_role_1">ROLE 1</label>
<input type="checkbox" id="form_role_2" name="form[role][]" value="2" />
<label for="form_role_2">ROLE 2</label>
<input type="checkbox" id="form_role_3" name="form[role][]" value="3" />
<label for="form_role_3">ROLE 3</label>
I would like to get something like this:
<div class="input-group">
<input type="checkbox" id="form_role_1" name="form[role][]" value="1" />
<label for="form_role_1">ROLE 1</label>
</div>
<div class="input-group">
<input type="checkbox" id="form_role_2" name="form[role][]" value="2" />
<label for="form_role_2">ROLE 2</label>
</div>
<div class="input-group">
<input type="checkbox" id="form_role_3" name="form[role][]" value="3" />
<label for="form_role_3">ROLE 3</label>
</div>
in the controller action:
$form = $this->createForm(RolesFormType::class, $roles);
$form->handleRequest($request);
return $this->render(
'role/edit_roles.html.twig',
array(
'form' => $form->createView()
)
);
in the form type:
class RolesFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('role', EntityType::class, array(
'label' => 'form.elements.roles',
'class' => 'RoleBundle\Entity\Role',
'choice_label' => 'role_name',
'expanded' => true,
'multiple' => true
));
}
}
the classic template looks like this:
<div class="container-fluid">
<div class="row">
{{ form_start(form, {'method': "POST"}) }}
<div class="col-md-12">
<div class="form-group">
{{ form_errors(form.role) }}
{{ form_widget(form.role, {}) }}
</div>
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
</div>
</div>
I tried it this way in the twig template, but only the labels were rendered:
<div class="container-fluid">
<div class="row">
{{ form_start(form, {'method': "POST"}) }}
<div class="col-md-12">
{% for role in form.role %}
<div class="input-group">
{{ form_label(role) }}
{{ form_widget(role) }}
</div>
{% endfor %}
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
</div>
</div>
Is ii possible without creating a new field type?
solution
concerning #xabbuh's answer I found the solution at How to Customize Form Rendering in Symfony 3
I created a folder in my Bundle:
src/RoleBundle/Resources/views/form
and I put a new file (fields.html.twig) into it with this content
{%- block choice_widget_expanded -%}
<div {{ block('widget_container_attributes') }}>
{%- for child in form %}
<div class="input-group">
{{- form_widget(child) -}}
{{- form_label(child, null, {translation_domain: choice_translation_domain}) -}}
</div>
{% endfor -%}
</div>
{%- endblock choice_widget_expanded -%}
In the meantime I found another question which deals with this problem:
Overriding symfony radio widget
You can customise the rendering of your form using a custom form theme. You can so either on the project level or even do that just for a particular form (see How to Customize Form Rendering and How to Work with Form Themes for more information).
Your example looks like you need to override the choice_widget and choice_label
When I play with symfony is not very skilled, I don't often use this accepted solution to solve it
view:
<label class="layui-form-label">所属地市:</label>
<div class="layui-inline">
<select name="{{ form.cityId.vars.full_name }}" lay-verify="" id="{{ form.cityId.vars.id }}" lay-filter="case_city">
<option value="0">请选择</option>
{% if citylist is not empty %}
{% for list in citylist %}
<option value="{{ list.id is defined ? list.id : 0 }}">{{ list.areaName is defined ? list.areaName : '' }}</option>
{% endfor %}
{% endif %}
</select>
</div>
controller:
$caseReg = new CaseRegister();
$form = $this->createForm('Alarm\Component\Form\CaseRegisterType', $caseReg);
$form->handleRequest($request);
$citylist = $this->getDoctrine()->getRepository('AlarmComponent:OfficeArea')->findBy(array('pid'=>0,'status'=>0));
$caseType = $this->getDoctrine()->getRepository('AlarmComponent:CaseType')->findBy(array('status'=>0));
if ($form->isSubmitted()) {
$em = $this->getDoctrine()->getManager();
$param = $request->request->get('alarm_component_caseregister');
if($param['receiveId'] == 0)
{
$case = new CaseType();
$case->setCaseName($param['receiveName']);
$em->persist($case);
$em->flush($case);
$caseReg->setReceiveId($case->getId());
$caseReg->setReceiveName($case->getCaseName());
}
if($param['cityId'] != 0)
{
$city = $this->getDoctrine()->getRepository('AlarmComponent:OfficeArea')->find($param['cityId']);
$caseReg->setCityId($city);
}
if($param['subofficeId'] != 0)
{
$suboffice = $this->getDoctrine()->getRepository('AlarmComponent:OfficeArea')->find($param['subofficeId']);
$caseReg->setSubofficeId($suboffice);
}
$em->persist($caseReg);
$em->flush($caseReg);
return $this->redirectToRoute('case_register_index');
}
return $this->render('AlarmWebBundle:BackendBat\CaseRegister:new.html.twig', array(
'caseReg' => $caseReg,
'form' => $form->createView(),
'citylist' => $citylist,
'casetype' => $caseType
));
It is also can solve my problem, but when I was late to optimize this or they must be altered. But I hope this answer can solve your current problem.

symfony request returns only one request

i am working with symfony 3 and twig. I take DNS info from a API. But i can never know how many rows it will be. So here is the problem lets say domain www.example.com has 3 DNS's when i request get form my controller i only get the last DNS back from the form.
twig:
{% if dnsinfo is defined %}
<form class="form-inline" method="post" action="/setdns">
{% if dnsinfo is not empty %}
{% for dns in dnsinfo %}
<div class="row " >
<div class="input-group col-xs-3">
<input type="text" id="dns" name="dns" value="{{ dns.1 }}" class="form-control">
</div>
<div class="col-xs-2 input-group">
<select class="form-control" id="type" name="type" style="width:100%;">
<option value="notselected" selected disabled>* Select a type</option>
<option value="A"{% if dns.2 == 'A' %} selected{% endif %}>A</option>
<option value="AAAA"{% if dns.2 == 'AAAA' %} selected{% endif %}>AAAA</option>
<option value="CNAME"{% if dns.2 == 'CNAME' %} selected{% endif %}>CNAME</option>
<option value="MX"{% if dns.2 == 'MX' %} selected{% endif %}>MX</option>
<option value="SOA"{% if dns.2 == 'SOA' %} selected{% endif %}>SOA</option>
<option value="TXT"{% if dns.2 == 'TXT' %} selected{% endif %}>TXT</option>
<option value="SRV"{% if dns.2 == 'SRV' %} selected{% endif %}>SRV</option>
</select>
</div>
<div class="col-xs-3">
<input type="text" id="content" name="content" value="{{ dns.3 }}" class="form-control">
</div>
<div class="col-xs-1">
<input type="text" id="ttl" name="ttl" value="{{ dns.4 }}" class="form-control">
</div>
<div class="col-xs-3">
<input type="text" id="prio" name="prio" value="{{ dns.5 }}" class="form-control">
</div>
</div>
<hr class="divider" style="">
{% endfor %}
{% endif %}
<input type="submit" class="btn btn-success" value="Save">
Cancel
</form>
{% endif %}
symfony controller:
$this->pre($request->request->get('dns'));
$API = $this->connect();
$dns = array(
'domain' => $request->request->get('domain'),
'extension' => $request->request->get('ext'),
'dnsdata' => serialize( array(
1 => array(
'name' => $request->request->get('dns'),
'type' => $request->request->get('type'),
'content' => $request->request->get('content'),
'ttl' => $request->request->get('ttl'),
'prio' => $request->request->get('prio')
)
))
);
$API->prepare('dns', $dns);
Of course i know a solution. Working with numbers behind the fields name1 name2 etc. But there must be a better way to do this right? What i am trying to get is if i print my request:
[dns] => array (array with all the DNS's i send in my form)
this is what is inside form data
https://gyazo.com/ebd558ba7f1ef8e1bfbe86e115bbb1e
as you can see it hold all the data i need yet with $request->request->get() i can only take the last one.
So my question is how to get all the data out?
vardump and the form that returns all the fields https://gyazo.com/0b9725ba8e298c6f59f343d3d5a548c7
sollution:
I ended up working with numbers so i can know how many fields are send from the api. And then looping to all of the fields
{% if dnsinfo is defined %}
{% set i=0 %}
<form class="form-inline" method="post" id="form" action="/setdns">
<input value="{{ domain }}" hidden name="domain" id="domain">
<input value="{{ ext }}" hidden name="ext" id="ext">
{% if dnsinfo is not empty %}
{% for dns in dnsinfo %}
<div class="row " >
<div class="input-group col-xs-3">
<input type="text" id="dns{{ i }}" name="dns{{ i }}" value="{{ dns.1 }}" class="form-control">
</div>
<div class="col-xs-2 input-group">
<select class="form-control" id="type{{ i }}" name="type{{ i }}" style="width:100%;">
<option value="notselected" selected disabled>* Select a type</option>
<option value="A"{% if dns.2 == 'A' %} selected{% endif %}>A</option>
<option value="AAAA"{% if dns.2 == 'AAAA' %} selected{% endif %}>AAAA</option>
<option value="CNAME"{% if dns.2 == 'CNAME' %} selected{% endif %}>CNAME</option>
<option value="MX"{% if dns.2 == 'MX' %} selected{% endif %}>MX</option>
<option value="SOA"{% if dns.2 == 'SOA' %} selected{% endif %}>SOA</option>
<option value="TXT"{% if dns.2 == 'TXT' %} selected{% endif %}>TXT</option>
<option value="SRV"{% if dns.2 == 'SRV' %} selected{% endif %}>SRV</option>
</select>
</div>
<div class="col-xs-3">
<input type="text" id="content{{ i }}" name="content{{ i }}" value="{{ dns.3 }}" class="form-control">
</div>
<div class="col-xs-1">
<input type="text" id="ttl{{ i }}" name="ttl{{ i }}" value="{{ dns.4 }}" class="form-control">
</div>
<div class="col-xs-3">
<input type="text" id="prio{{ i }}" name="prio{{ i }}" value="{{ dns.5 }}" class="form-control">
</div>
</div>
<hr class="divider" style="">
{% set i = i + 1 %}
{% endfor %}
{% endif %}
<input type="submit" class="btn btn-success" onclick="$('#form').attr('action','/setdns{{ i }}')" value="Save">
Cancel
</form>
{% endif %}
as you can see in my button i use jquery to send the number to my controller
/**
* #Route("/setdns{i}", name="setdns", requirements={"i": "\d+"})
*/
public function setdns(Request $request, $i = false) {
$API = new Whoisdomainmodify();
$API = $API->connect();
for ($x=0; $x < $i; $x++) {
$dns = array(
'domain' => $request->request->get('domain'),
'extension' => $request->request->get('ext'),
'dnsdata' => serialize(array(
1 => array(
'name' => $request->request->get('dns'.$x),
'type' => $request->request->get('type'.$x),
'content' => $request->request->get('content'.$x),
'ttl' => $request->request->get('ttl'.$x),
'prio' => $request->request->get('prio'.$x)
)
))
);
echo '<pre>';
print_r($dns);
$API->prepare('dns', $dns);
// $API->execute();
// $API->fetch();
}
$this->addFlash('Success', 'DNS successfully changed');
return $this->redirectToRoute('registereddomain');
}
if there is a better way to do this please tell me. Because i send all my form data see gyazo.
Did you know that the for loop in Twig has variables:
http://twig.sensiolabs.org/doc/tags/for.html#the-loop-variable
for example you could use:
{{ dns.loop.index0 }}
or something along those lines. Try it out. Twig is very powerful, if you get familiar with it, it might save you a lot of coding. I'm not sure if this is an answer, but it might help you out.

Resources