How to index formset input fields with list elements - django

How can I use elements from a list as formset indexes instead of the generic 0,1,2 etc?
Right now I have something like:
Sizes = ["XS", "S", "M","L", "XL"]
SizesFormSet = formset_factory(SizesForm, extra=len(Sizes))
And my formset input fields are indexed as 0,1,2... like so:
<td><input type="number" name="Jaune-0-quantité" id="id_Jaune-0-quantité"></td>
<td><input type="number" name="Jaune-1-quantité" id="id_Jaune-1-quantité"></td>
<td><input type="number" name="Jaune-2-quantité" id="id_Jaune-2-quantité"></td>
...
and I'd like to index them as "XS", "S", "M"
```html
<td><input type="number" name="Jaune-XS-quantité" id="id_Jaune-XS-quantité"></td>
<td><input type="number" name="Jaune-S-quantité" id="id_Jaune-S-quantité"></td>
<td><input type="number" name="Jaune-M-quantité" id="id_Jaune-M-quantité"></td>
The django documentation deals with renaming a formset input field prefix, but it doesn't deal with indexing.
Thanks in advance for the help!

I ended up doing it this way, not using formsets:
#views.py
formsets = []
for couleur in Couleurs:
formset=[]
for taille in Tailles:
formset.append({"name": taille+"-"+couleur, "id": "id_"+taille+"-"+couleur})
formsets.append({"formset":formset, "couleur":couleur})
return render(request, "front/nouvel-article.html", {'form': form, 'formsets': formsets, 'collection': collection, "tailles": [""]+Tailles})
and in my template:
<form action="/nouvel-article/{{ collection }}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Détails</legend>
{{ form|crispy }}
</fieldset>
<fieldset class="form-group">
<legend class="border-bottom mb-4">Quantité</legend>
<table>
<thead>
{% for taille in tailles %}
<th>{{ taille }}</th>
{% endfor %}
</thead>
<tbody>
{% for formset in formsets %}
<tr>
<td>{{formset.couleur}}</td>
{% for field in formset.formset %}
<td><input type="number" name="{{ field.name }}" id="{{ field.id }}"></td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Confirmer</button>
</div>
</form>

Related

How to display uploaded pdf file along with machine name and operation number based on select from dropdown

In this project, I want to display machine name and operation number along with uploaded pdf files based on select machine name and operation number from dropdown menu. This project is working but when I add and select another file in same machine name and operation number, it is displaying two pdf files along with previous pdf file of another machine name and operation number, exactly I don't want it. It should display machine name and operation number along with uploaded pdf file based on select from dropdown menu. And also when I upload another pdf files in same machine name and operation number, it should display two pdf files along with same machine name and operation number within same row.
This project is working fine but I want above validations.
Please anyone can help me out, this will be great for me. Please..
views.py:
def upload(request):
controlmachines = Controlmachine.objects.all()
return render(request,'usermaster/upload.html',{'machines':machines})
def save_machine(request):
if request.method == "POST":
machine_name = request.POST.get('machinename', '')
operation_no = request.POST.get('operationname','')
choiced_cmachine = Controlmachine.objects.filter(machine_name=machine_name, operation_no=operation_no)
cmachines = Controlmachine.objects.all()
return render(request,'usermaster/upload.html',{'machines':machines,'choiced_cmachine':choiced_cmachine})
def index(request):
if request.method == 'POST':
form = ControlmachineForm(request.POST, request.FILES)
if form.is_valid():
model_instance = form.save()
model_instance.save()
else:
form = ControlmachineForm()
controlmachiness = Controlmachine.objects.all()
return render(request,'usermaster/upload_file.html',{'form':form,'controlmachiness':controlmachiness})
upload.html:
<form action="{% url 'save_machine' %}" method="post">
{% csrf_token %}
<label for="machinename">Select Machine Name:</label>
<select name="machinename" id="machinename">
{% for machine in cmachines %}
<option value="{{ machine.machine_name }}">{{ machine.machine_name }}</option>
{% endfor %}
</select>
<br>
<br>
<label for="operationname">Select Operation Number:</label>
<select id="operationname" name="operationname">
{% for machine in cmachines %}
<option value="{{ machine.operation_no }}">{{ machine.operation_no }}</option>
{% endfor %}
</select>
<br>
<br>
<br>
<input type="submit" value="Save">
</form>
<tr>
{% for choice in choiced_cmachine %}
<td>{{choice.machine_name}}</td>
<td>{{choice.operation_no}}</td>
<td>
{% for file in controlmachines %}
view file
{% endfor %}
</td>
{% endfor %}
</tr>
control_uploadfile.html:
<html>
<head>
<title>Master File Upload</title>
</head>
<body>
<p><h1>Control File Upload</h1></p>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button> <br><br>
</form>
</body>
</html>
control_show.html:
{% extends "master/control_base.html" %}
{% block title %}Control File{% endblock title %}
{% block content %}
<div class="col-md-12">
<div class="table-responsive">
<table id="bootstrapdatatable" class="table table-striped table-bordered" width="90%">
<thead>
<th><input type="checkbox" id="checkall" /></th>
<th>ID</th>
<th>Machine Name</th>
<th>Operation Number</th>
<th>File</th>
<th>Delete</th>
</thead>
<tbody>
{% for control in controlmachines %}
<tr>
<td><input type="checkbox" class="checkthis" /></td>
<td>{{ control.id }}</td>
<td>{{ control.machine_name }}</td>
<td>{{ control.operation_no }}</td>
<td>{{ control.control_uploadfile }}</td>
<td><p data-placement="top" data-toggle="tooltip" title="Delete"></span></p></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock content %}
models.py:
class Controlmachine(models.Model):
machine_name = models.CharField(max_length=100)
operation_no = models.IntegerField()
control_uploadfile = models.FileField(upload_to='documents/')
class Meta:
db_table = "controlmachine"
forms.py:
class ControlForm(forms.ModelForm):
class Meta:
model = Controlmachine
fields = ['machine_name', 'operation_no', 'control_uploadfile'] #https://docs.djangoproject.com/en/3.0/ref/forms/widgets/
widgets = { 'machine_name': forms.TextInput(attrs={ 'class': 'form-control' }),
'operation_no': forms.TextInput(attrs={ 'class': 'form-control' }),
'control_uploadfile': forms.ClearableFileInput(attrs={ 'class': 'form-control' }),
}
Do this: Here I have added if condition that is used to connect machine name to uploaded file.
<form action="{% url 'save_machine' %}" method="post">
{% csrf_token %}
<label for="machinename">Select Machine Name:</label>
<select name="machinename" id="machinename">
{% for machine in cmachines %}
<option value="{{ machine.machine_name }}">{{ machine.machine_name }}</option>
{% endfor %}
</select>
<br>
<br>
<label for="operationname">Select Operation Number:</label>
<select id="operationname" name="operationname">
{% for machine in cmachines %}
<option value="{{ machine.operation_no }}">{{ machine.operation_no }}</option>
{% endfor %}
</select>
<br>
<br>
<br>
<input type="submit" value="Save">
</form>
<tr>
{% for choice in choiced_cmachine %}
<td>{{choice.machine_name}}</td>
<td>{{choice.operation_no}}</td>
<td>
{% for file in controlmachines %}
{% if file == choice and file == choice %}
view file
{% endif %}
{% endfor %}
</td>
{% endfor %}
</tr>

how to update django databsae from html?

I want to only update the brand. So I want to see if I can get the post from the input.
print(request.POST.get('brand')) didn't print anything, but I can get print(request.POST.get('url')). Does anyone know why?
Here is my base.html code.
<form action="{% url 'script' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group w-75">
<input type="text" name="url" id="url" class="form-control">
</br>
<button type="submit" class="btn btn-success btn-lg btn-block">submit</button>
</div>
</br>
{% if alldata %}
<table class="table table-striped table-sm" id="">
<thead>
<tr>
<th>Price</th>
<th>Asin</th>
<th>Rank</th>
<th>Brand</th>
<th>CPU</th>
<th>Update</th>
</tr>
</thead>
<tbody>
{% for data in alldata %}
<tr>
<td>{{ data.price }}</td>
<td> {{ data.asin }} </td>
<td>{{ data.rank }}</td>
<td>
<div>
{{ data.brand }} <input type="text" name="brand" id="brand" value="{{data.brand}}">
<button type="submit">Update</button>
</div>
</td>
<td>cpu</td>
<td><button type="submit">Update</button></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
</form>
To check All data in request.POST:
print(request.POST)
to print only one 'field'
print(request.POST['field'])

unable to update the fields in model Django

I am trying to edit user details of a specific user when admin logins its going to edit page but when I press the update button it's not updating not showing any error message. (correct me please if I am wrong).
This is my edit.html
{% extends 'base.html' %}
{% block title %}edit details{% endblock %}
{% block content %}
{% if emp %}
<form method="POST" class="form-inline my-2 my-lg-0" ">
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<h3>Update Details</h3>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee User:</label>
<div class="col-sm-4">
<input type="text" id="id_user" required maxlength="20" value="{{
emp.user }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee first_name:</label>
<div class="col-sm-4">
<input type="search" id="id_first_name" required maxlength="100"
value="{{ emp.first_name }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee last_name:</label>
<div class="col-sm-4">
<input type="text" id="id_last_name" required maxlength="100" value="{{
emp.last_name }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Email:</label>
<div class="col-sm-4">
<input type="email" id="id_email" required maxlength="254" value="{{
emp.email }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Gender:</label>
<div class="col-sm-4">
<input type="text" id="id_gender" required maxlength="15" value="{{
emp.gender }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Age:</label>
<div class="col-sm-4">
<input type="text" id="id_age" required maxlength="100" value="{{
emp.age }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee salary:</label>
<div class="col-sm-4">
<input type="text" name="ename" id="id_salary" required maxlength="100"
value="{{ emp.salary }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-success">Update</button>
</div>
</div>
</div>
</form>
{% endif %}
{% endblock %}
This is my profile.html page
{% if user.is_authenticated %}
{% if user.is_superuser %}
<table class="table table-striped table-bordered table-sm">
<thead class="thead-dark">
<tr>
<th>Employee User</th>
<th>Employee first_name</th>
<th>Employee last_name</th>
<th>Employee Email</th>
<th>Employee Gender</th>
<th>Employee Age</th>
<th>Employee Salary</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for employee in employees %}
<tr>
<td>{{ employee.user }}</td>
<td>{{ employee.first_name }}</td>
<td>{{ employee.last_name }}</td>
<td>{{ employee.email }}</td>
<td>{{ employee.gender }}</td>
<td>{{ employee.age }}</td>
<td>{{ employee.salary }}</td>
<td>
<a href="{% url 'edit' employee.id %}"><span class="glyphicon
glyphicon-pencil" >Edit</span></a>
Delete
</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
<br>
<center><a href="{% url 'signup' %}" class="btn btn-primary">Add New
Record</a></center>
{% else %}
<p>username : {{ user }}</p>
<p>firstname : {{ user.first_name }}</p>
<p>lastname : {{ user.last_name }}</p>
<p>{{user.employee.age}}</p>
<p>
Edit details
</p>
<p>
Change password
</p>
{% endif %}
{% endif %}
This is view.py of edit method
def edit(request, emp_id):
if request.method == 'POST':
emp = employee.objects.get(pk=emp_id)
form = EmployeForm(request.POST or None, instance=emp)
if form.is_valid():
form.save()
messages.success(request, ('Item has been edited'))
return HttpResponseRedirect('view_profile')
else:
emp = employee.objects.get(pk=emp_id)
return render(request, 'edit.html', {'emp': emp})
def view_profile(request):
employees = employee.objects.all()
args= {'user':request.user,'employees':employees}
return render(request,'profile.html',args)
This is my model page
class employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
gender = models.CharField(max_length=1,choices=(('M','Male'),
('F','Female')),blank=True)
age = models.PositiveIntegerField(blank=True, null=True)
salary = models.CharField(blank = True,max_length=50
def __str__(self):
return self.user.username
Please, any advice on how to troubleshoot or any documentation I can read.
You're not using the form properly. Forms are not only for validation, they are also responsible for rendering the error messages. You want to change your view to pass the form to the template:
def edit(request, emp_id):
emp = employee.objects.get(pk=emp_id)
if request.method == 'POST':
form = EmployeForm(request.POST, instance=emp)
if form.is_valid():
form.save()
messages.success(request, ('Item has been edited'))
# this one is probably not going to work
# as expected - you may want to check the
# doc for the `redirect` shortcut instead
return HttpResponseRedirect('view_profile')
else:
form = EmployeForm(instance=emp)
return render(request, 'edit.html', {'emp': emp, 'form':form})
Then in your template instead of manually writing the whole form markup, use the form for rendering so you have the validation errors correctly displayed.

how to iterate over a list of variable length in django template?

I have a list of values like:
list_of_values = ['clients':['add, view'], 'vendors': ['add', 'delete', 'change'], 'companies': ['add', 'view', 'delete', 'change']]
Using django template tags I have to make a template like:
Activities ADD | VIEW | CHANGE | DELETE
clients checkbox checkbox checkbox checkbox
vendors checkbox checkbox checkbox checkbox
companies checkbox checkbox checkbox checkbox
Kindly let me know how can I achieve this?
List of values looks more like a dictionary to me, assuming it is:
<table>
<tr>
<th>Activities</th>
<th>ADD</th>
<th>VIEW</th>
<th>CHANGE</th>
<th>DELETE</th>
</tr>
{% for key in list_of_values %}
<tr>
<td>{{ key }}</td>
<td>
{% if 'add' in list_of_values.key %}
<input type="checkbox" checked/>
{% else %}
<input type="checkbox"/>
{% endif %}
</td>
<td>
{% if 'view' in list_of_values.key %}
<input type="checkbox" checked/>
{% else %}
<input type="checkbox"/>
{% endif %}
</td>
<td>
{% if 'change' in list_of_values.key %}
<input type="checkbox" checked/>
{% else %}
<input type="checkbox"/>
{% endif %}
</td>
<td>
{% if 'delete' in list_of_values.key %}
<input type="checkbox" checked/>
{% else %}
<input type="checkbox"/>
{% endif %}
</td>
</tr>
{% endfor %}
</table>

How to customize the input element generated by django.forms?

I'm using django.forms to generate my login/signup page, part of code is as follows:
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<table>
<tr>
{# username is directed to email field in our model #}
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% else %}
<input type="hidden" name="next" value="{% url 'home' %}" />
{% endif %}
</form>
As you can see, the {{ form.username }} and {{ form.password }} will automatically generate an <input id="id_username" maxlength="254" name="username" type="text"> and an <input id="id_password" name="password" type="password"> respectively. But I want to add some extra attributes to these input fields, like placeholderand class. Where can I customize these?
Either manually:
<input type="text" name="{{ form.field.html_name }}" placeholder="foo" value="{{ form.field.value }}" />
Or via the widget attrs argument
https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs
class MyForm(forms.Form):
field = forms.CharField(widget=forms.TextInput(attrs={'placehoder': 'foo', 'title': 'baz'}))
You may use django-widget-tweaks which is a very nice library for tweaking django's widget. I've used it and it's quite simple.
From their site:
{% load widget_tweaks %}
<!-- change input type (e.g. to HTML5) -->
{% render_field form.search_query type="search" %}
<!-- add/change several attributes -->
{% render_field form.text rows="20" cols="20" title="Hello, world!" %}
<!-- append to an attribute -->
{% render_field form.title class+="css_class_1 css_class_2" %}
<!-- template variables can be used as attribute values -->
{% render_field form.text placeholder=form.text.label %}
Hope this helps!