To make it clearer, I want to create an e-commerce app for installment stores
I prepared a short HTML template at the bottom of the question
I have the following model:
class App_form(models.Model): #This is the head model
id_customer = models.CharField(max_length=200)
name = models.CharField(max_length=150, unique=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,12}$', message="Phone number must be entered in the format: '998981234567'. Up to 12 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=13, unique=True)
#Models which I should combine and which will be named as: products_with_period model and it should belong only and only to this App_form model
warehouse = models.ManyToManyField(Warehouse)
product_period = models.OneToOneField(Product_period, on_delete=models.CASCADE)
def __str__(self):
return self.surname
#Product period
class Product_period(models.Model):
product_period = models.CharField(max_length=200, unique=True)
product_percent = models.FloatField()
product_periodvalue = models.FloatField()
def __str__(self):
return self.product_period
#Warehouse model
class Warehouse(models.Model):
category_product = models.ForeignKey(Category_product, on_delete=models.CASCADE)
product_name = models.CharField(max_length=200, unique=True)
condition = models.BooleanField(default=False)
amount = models.IntegerField()
barcode = models.BigIntegerField()
f_price = models.CharField(max_length=255, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.product_name
What I want to achieve in my Rest Api out only from combined products_with_period model
products_with_period = [{
id: 1,
product_name: " ",
product_fprice: " ",
product_period: {
"id": 2,
"product_period_name": " ",
"product_period_percent": " ",
},
{
id: 2,
product_name: " ",
product_fprice: " ",
product_period: {
"product_period": " ",
"product_period_percent": " ",
},
}],
Here is the HTML template, which explains the essence
function addProduct() {
var table = document.getElementById("ProductTable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = `
<div class="form-group">
<select class="form-control" >
<option value="1">Smartphone</option>
<option value="2">Smart TV</option>
<option value="3">Laptop</option>
<option value="4">Desktop</option>
<option value="5">Sofa</option>
<option value="6">Bicycle</option>
</select>
</div>
`;
cell2.innerHTML = `
<div class="form-group">
<select class="form-control" >
<option value="1">3 months</option>
<option value="2">6 months</option>
<option value="3">12 months</option>
<option value="4">24 months</option>
</select>
</div>
`;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<div class="container">
<div class="row">
<div class="col-md-12 p-4">
<div class="form-group">
<label for="c_name">Customer name:</label>
<input class="form-control" id="c_name" type="text">
</div>
<div class="form-group">
<label for="c_phone">Customer phone:</label>
<input class="form-control" id="c_phone" type="tel">
</div>
</div>
<table class="table table-bordered" id="ProductTable">
<thead>
<tr>
<th>Product name:</th>
<th>Installment period:</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group">
<select class="form-control">
<option value="1">Smartphone</option>
<option value="2">Smart TV</option>
<option value="3">Laptop</option>
<option value="4">Desktop</option>
<option value="5">Sofa</option>
<option value="6">Bicycle</option>
</select>
</div>
</td>
<td>
<div class="form-group">
<select class="form-control">
<option value="1">3 months</option>
<option value="2">6 months</option>
<option value="3">12 months</option>
<option value="4">24 months</option>
</select>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2" class="text-center">
<button class="btn btn-success" onclick="addProduct()">add new product</button>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
You could try something like this (which is not using Django-rest and there is probably a way to do this with serializers, but this is what I came up with off the top of my head):
from django.http import JsonResponse
def product_api(request):
app_forms = App_form.objects.filter(product_period__isnull=False).all()
products_with_period = []
data = {}
for form in app_forms:
data['id'] = form.id
data['product_name'] = form.name
...
data['product_period']['id'] = form.product_period.id
data['product_period']['product_period_name'] = form.product_period.product_period
...
products_with_period.append(data)
data = {}
if request.is_ajax():
return JsonResponse(products_with_period)
else:
return HttpBadRequest()
This can then be injested by an AJAX function in the template:
<script type="text/javascript">
$("#button_or_object_id").click(function(){
$.ajax({
url: '{% url 'product_api' %}',
type: "GET",
dataType: "json",
cache: false
}).done(function(products_with_period) {
// do something with the products_with_period data
});
});
});
</script>
Otherwise, you can also render it in the context:
def product_api(request):
app_forms = App_form.objects.filter(product_period__isnull=False).all()
products_with_period = []
data = {}
for form in app_forms:
data['id'] = form.id
data['product_name'] = form.name
...
data['product_period']['id'] = form.product_period.id
data['product_period']['product_period_name'] = form.product_period.product_period
...
products_with_period.append(data)
data = {}
return render(request, 'template.html', context={'products_with_period':products_with_period})
And then render the array of dicts in your template manually.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 days ago.
Improve this question
Basically I have this screen and according to the value selected in “metodo_pagamento” I want to display the amount of inline form, example if I select “2 Parcelas”, it shows 2 forms inline, but I wanted to do this dynamically how do I do that too to update and delete?formlike this:
models.py
class Despesas(models.Model):
METODO = (
("1", "1 Parcela"),
("2", "2 Parcelas"),
("3", "3 Parcelas"),
("4", "4 Parcelas"),
)
descricao = models.CharField(max_length=100)
metodo_pagamento = models.CharField(max_length=50, choices=METODO, default="A vista")
def __str__(self):
return self.descricao
class Parcelas(models.Model):
despesa = models.ForeignKey(Despesas, on_delete=models.CASCADE)
data_pagamento = models.DateField(null=True)
valor = models.FloatField(null=True)
def __str__(self):
return str(self.despesa.id)
forms.py
class DespesasForm(forms.ModelForm):
METODO = (
("1", "1 Parcela"),
("2", "2 Parcelas"),
("3", "3 Parcelas"),
("4", "4 Parcelas"),
)
metodo_pagamento = forms.CharField(max_length=50, widget= forms.Select(choices=METODO, attrs = {'onchange': "updateInlineForm();", 'default':""}))
views.py
class CadastrarDespesa(LoginRequiredMixin, GroupRequiredMixin, CreateView):
group_required = u"Admin"
login_url = 'login'
template_name = "formularios/form_cadastro_despesa.html"
def get(self, *args, **kwargs):
form = DespesasForm()
context = {
'form': form,
'titulo':"Cadastrar despesa"
}
return self.render_to_response(context)
form_cadastro_despesa.html
<div class="row">
<div class="col-lg-3">
<div class="container text-center" style="margin-top: 70px; margin-left:650px; text-align:center">
<form method="POST" action="">
{% csrf_token %}
{{form|crispy}}
<div id="inline-form-section">
<!-- Inline form fields will be added here dynamically -->
</div>
<button type="submit" class="btn btn-success" style="margin-top:20px;margin-bottom: 20px;">{{titulo}}</button>
</form>
</div>
</div>
</div>
function updateInlineForm() {
var method = document.getElementById("id_metodo_pagamento").value;
var inlineFormSection = document.getElementById("inline-form-section");
inlineFormSection.innerHTML = ""; // Clear the existing fields
for (var i = 1; i <= method ; i++) {
if (method == 1){
inlineFormSection.innerHTML +=
`
<br>
<label for="parcela1">Data pagamento:</label>
<input class="form-control" type="date" id="parcela1" name="parcela1" required="true">
<br>
<label for="valor1">Status do pagamento</label>
<select class="form-control" id="status" name="status1">
<option value="Pendente">Pendente</option>
<option value="Pago">Pago</option>
</select>
<br>
<label for="parcela1">Valor do pagamento:</label>
<input type="number" class="form-control" id="valorparcela1" value="${total}" name="valorparcela1" required="true" onchange="validacao_parcela(this.id,${valor_parcela});">
`;
} else {
inlineFormSection.innerHTML +=
`
<br>
<label for="parcela${i}">Data ${i}° parcela:</label>
<input class="form-control" type="date" id="parcela${i}" name="parcela${i}" required="true">
<br>
<label for="valor${i}">Status ${i}° parcela</label>
<select class="form-control" id="status" name="status${i}">
<option value="Pendente">Pendente</option>
<option value="Pago">Pago</option>
</select>
<br>
<label for="parcela${i}">Valor da ${i}° parcela:</label>
<input class="form-control" type="number" value="${valor_parcela}" id="valorparcela${i}" name="valorparcela${i}" required="true" onchange="validacao_parcela(this.id,${valor_parcela});">
<br>
`;
}
}
}
In this way that i did in using javascript onchange, but its dificult make update when user select other “Metodo pagamento”, anyone can help me?
To dynamically display the number of inline forms based on the selected value in the "metodo_pagamento" field, you can use JavaScript and update the HTML dynamically based on the selected value
Hello Iam new in django and i try to same my form input to database without form.py just from views but iam getting name error please help me to short out the problem
This is my html form code
<form class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin" method="post" action="/test_submit/" id='myForm'>
{% csrf_token %}
<div class="w3-row-padding">
<div class="w3-half">
<p><label>Item Name</label></p>
<p><input class="w3-input" type="text" name="item_name" required></p>
</div>
<div class="w3-half">
<p><label>Brand Name</label></p>
<p><input class="w3-input" type="text" name="brand_name" required></p>
</div>
</div>
<div class="w3-row-padding">
<div class="w3-half">
<p><label>Item Size</label></p>
<p><select class="w3-select" name="item_size" required>
<option value="" disabled selected>Select Size</option>
<option value="5k-7k">5k-7k</option>
<option value="7k-10k">7k-10k</option>
<option value="11-13">11-13</option>
<option value="1-3">1-3</option>
<option value="4-5">4-5</option>
<option value="6-9">6-9</option>
<option value="10-11">10-11</option>
</select></p>
</div>
<div class="w3-half">
<p><label>Item Color</label></p>
<p><input class="w3-input" type="text" name="item_color" required></p>
</div>
<div class="w3-half">
<p><label>Item Unit</label></p>
<p><select class="w3-select" name="item_unit" required>
<option value="" disabled selected>Select Unit</option>
<option value="Number">Number</option>
<option value="Number">Number</option>
<option value="Boxes">Boxes</option>
</select></p>
</div>
<div class="w3-half">
<p><label>Quantity</label></p>
<p><input class="w3-input" type="number" name="item_quantity" placeholder="0" required></p>
</div>
</div>
<div class="w3-row-padding">
<div class="w3-half">
<p><label>Purchase Price</label></p>
<p><input class="w3-input" type="number" name="purchase_price" placeholder="0.0" required></p>
</div>
<div class="w3-half">
<p><label>Selling Price</label></p>
<p><input class="w3-input" type="number" name="selling_price" placeholder="0.0" required></p>
</div>
<div class="w3-half">
<p><label>MRP</label></p>
<p><input class="w3-input" type="number" name="mrp" placeholder="0.0" required></p>
</div>
<div class="w3-half">
<p><label>Date</label></p>
<p><input class="w3-input" type="date" name="date" required></p>
</div>
</div>
<div class="w3-bar">
<button class="w3-btn w3-blue w3-round">Save</button>
<button class="w3-btn w3-blue w3-round">Save & Generate Barcode</button>
<button class="w3-btn w3-gray w3-round" onclick="clearFun()">Cancle</button>
</div>
<p></p>
</form>
This is my views.py code
from django.shortcuts import render
from .models import Items_Tb
from django.contrib import messages
# Create your views here.
def items_views(request):
return render(request,'itemapp/items.html')
def items_submit_views(request):
print('----------------test my submit form-----------------')
itemname = request.POST[item_name]
brandname = request.POST[brand_name]
itemsize = request.POST[item_size]
itemcolor = request.POST[item_color]
itemunit = request.POST[item_unit]
itemquantity = request.POST[item_quantity]
purchaseprice = request.POST[purchase_price]
sellingprice = request.POST[selling_price]
mrp = request.POST[mrp]
item_date = request.POST[date]
item_info = Items_Tb(item_name=itemname,brand_name=brandname,item_size=itemsize,
item_color=itemcolor,item_unit=itemunit,item_quantity=itemquantity,purchase_price=purchaseprice,
selling_price=sellingprice,mrp=mrp,item_date=item_date)
item_info.save()
messages.success(request,'Items save successfully!')
return render(request,'itemapp/items.html')
This is models.py Code
from django.db import models
# Create your models here.
class Items_Tb(models.Model):
item_name = models.CharField(max_length=64)
brand_name = models.CharField(max_length=64)
item_size = models.CharField(max_length=64)
item_color = models.CharField(max_length=64)
item_unit = models.CharField(max_length=64)
item_quantity = models.IntegerField()
purchase_price = models.FloatField()
selling_price = models.FloatField()
mrp = models.FloatField()
item_date = models.DateField()
def __str__(self):#show tabel name on admin
return self.item_name
This is my Urls.py Code
from django.contrib import admin
from django.urls import path
from dashboardapp import views as d_views
from itemapp import views as i_views
from userapp import views as u_views
urlpatterns = [
path('admin/', admin.site.urls),
path('dashboard/', d_views.dash_views),
path('test/', d_views.test_views),
path('items/', i_views.items_views, name='items'),
path('test_submit/', i_views.items_submit_views, name='test_submit'),
path('users/', u_views.users_views),
]
when i sumbit my form iam getting this error
bellowenter image description here
item_name should be in quotes:
itemname = request.POST["item_name"]
I have a booking system in which i enter dates and timeslots available to book.
the form gets the timeslots from the date and converts it to the user timezone time.
i want the client to select a date and an available timeslot before continuing the form but even with required it doesnt work.
i have a model for timeslots and one for event, date+timeslot
then a form to make client select available date+timeslot, with a html to find timeslot available for each day
html
<option value="">{% if time_slots %}Available Slots{% else %}No Slot Available{% endif %}</option>
{% for time_set in time_slots %}
<option value="{{ time_set.pk }}">{{ time_set.start }} - {{ time_set.end }}</option>
{% endfor %}
models
class TimeSlots(models.Model):
start = models.TimeField(null=True, blank=True)
end = models.TimeField(null=True, blank=True)
class Meta:
ordering = ['start']
def __str__(self):
return '%s - %s' % (self.start.strftime("%I:%M %p"), self.end.strftime("%I:%M %p"))
class Event(models.Model):
event_date = models.DateField()
start = models.ForeignKey(TimeSlots, on_delete=models.CASCADE, verbose_name='Slot Time', null=True)
available = models.BooleanField(default=True)
class Meta:
verbose_name = u'Event'
verbose_name_plural = u'Event'
def __str__(self):
return str(self.event_date)
def get_absolute_url(self):
url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.pk])
return u'%s' % (url, str(self.start))
form
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ('patient_name', 'patient_country','phone_number', 'email', 'event_date','start', 'timestamp', 'datestamp')
widgets = {
'event_date': DateInput(),
'patient_country': CountrySelectWidget(),
}
def __init__(self, *args, **kwargs):
super(PatientForm, self).__init__(*args, **kwargs)
self.fields['start'].queryset = TimeSlots.objects.none()
if 'event_date' in self.data:
try:
event_id = self.data.get('event_date')
# event = Event.objects.get(pk=event_id)
self.fields['start'].queryset = TimeSlots.objects.filter(event__event_date=event_id, event__available=True)
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['start'].queryset = self.instance.timeslot_set
views
class PatientCreate(CreateView):#was CreateView
form_class = PatientForm
template_name = 'appointment/index.html'
def get_context_data(self, **kwargs): # new
context = super(PatientCreate, self).get_context_data(**kwargs)
context['key'] = settings.STRIPE_PUBLISHABLE_KEY
return context
def load_time_slots(request):
event_date = request.GET.get('event_date')
client_timezone = request.GET.get('timezone')
client_timezone = pytz.timezone(client_timezone)
event_date, original_date = get_original_event_date_by_timezone(client_timezone, event_date)
time_slots = TimeSlots.objects.filter(event__event_date= event_date, event__available=True)
final_time_slots = []
for time_slot in time_slots:
start_time = time_slot.start
original_start_date_time = original_date.replace(hour=start_time.hour, minute=start_time.minute,
second=start_time.second,
tzinfo=original_time_zone)
timezone_start_date_time = original_start_date_time.astimezone(client_timezone)
end_time = time_slot.end
original_end_date_time = original_date.replace(hour=end_time.hour, minute=end_time.minute,
second=end_time.second,
tzinfo=original_time_zone)
timezone_end_date_time = original_end_date_time.astimezone(client_timezone)
final_time_slots.append({'pk': time_slot.pk, 'start': timezone_start_date_time.time,
'end': timezone_end_date_time.time})
return render(request, 'appointment/dropdown_list_options.html', {'time_slots': final_time_slots})
def get_original_event_date_by_timezone(client_timezone, event_date):
client_date = datetime.datetime.strptime(event_date, '%Y-%m-%d')
client_date = client_date.replace(tzinfo=client_timezone)
original_date = client_date.astimezone(original_time_zone)
original_date = original_date.replace(hour=0, minute=0, second=0, microsecond=0)
event_date = original_date.strftime('%Y-%m-%d')
return event_date, original_date
def create_event(request, start_time, day_date):
time_slot = TimeSlots.objects.get(start=start_time)
Event.objects.create(event_date=day_date, start=time_slot)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
form page html
<div class="container" style="margin-top:50px;margin-bottom:50px;">
<div class="stepwizard col-md-offset-3">
<div class="stepwizard-row setup-panel">
<div class="stepwizard-step">
1
<p>Date & Time</p>
</div>
<div class="stepwizard-step">
2
<p>Information</p>
</div>
<div class="stepwizard-step">
3
<p>Calling Method</p>
</div>
<div class="stepwizard-step">
4
<p>Payment Method</p>
</div>
</div>
</div>
<form role="form" action="{% url 'charge' %}" method="POST" id="patientForm" data-times-url="{% url 'ajax_load_time_slots' %}">
<div class="row setup-content" id="step-1">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<h3> Appointments date and time</h3>
<div class="form-group">
<label class="control-label" for="id_event_date">Event Date:</label>
<input class="form-control" type="date" name="event_date" id="id_event_date" required="required" />
</div>
<div class="form-group">
<label class="control-label" for="id_start">{% trans "Time:"%}</label>
<p><select required="required" class="form-control" name="start" style="display:inline;" id="id_start">
<option value="">---------</option></select></p><input type="hidden" name="timezone">
<script>$("#patientForm input[name='timezone']").val(Intl.DateTimeFormat().resolvedOptions().timeZone);</script>
</select></p>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<h3> Step 2</h3>
<div class="form-group">
<label for="id_patient_fname" class="control-label">First Name:</label>
<input name="patient_name" id="id_patient_name" required="required" maxlength="100" type="text" class="form-control" placeholder="Enter First Name" />
</div>
<div class="form-group">
<label class="control-label">Last Name:</label>
<input required="required" maxlength="100" type="text" class="form-control" placeholder="Enter Last Name" />
</div>
<div class="form-group">
<label for="id_phone_number" class="control-label">Phone Number:</label>
<input name="phone_number" id="id_phone_number" required="required" maxlength="100" type="text" class="form-control" placeholder="Enter Phone Number" />
</div>
<div class="form-group">
<label for="id_emal" class="control-label">Email:</label>
<input name="email" id="id_email" maxlength="100" type="text" required="required" class="form-control" placeholder="Enter Email" />
</div>
<div class="form-group">
<label class="control-label">City</label>
<textarea required="required" class="form-control" placeholder="Enter your address"></textarea>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Choose The Way You Want to Receive The Video Call:</label>
<label class="radio-inline"><input class="form-control" type="radio" name="optradio" checked>Skype</label>
<label class="radio-inline"><input class="form-control" type="radio" name="optradio">Whatsapp</label>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-4">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_KPSQTmUOl1DLP2eMc7zlvcnS"
data-description="Buying a 30mn Skype Session" data-amount="3000" data-locale="auto"></script>
</div>
</div>
</div>
</form>
</div>
in the html of the form page, i add required to select but it doesnt work
i need client to select lets say 29/01/2019, then if there is availability choose a timeslote lets say 5.30pm-6.00pm, and then only the next arrow will appear
With CreateView it's a little bit tricky when you want to initialize your ModelForm data. So, instead of doing initialization under your ModelForm, do it under the CreateView class like this example:
Your form:
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ('patient_name', 'patient_country','phone_number', 'email', 'event_date','start', 'timestamp', 'datestamp')
widgets = {
'event_date': DateInput(),
'patient_country': CountrySelectWidget(),
}
Your view:
class PatientCreate(CreateView):
form_class = PatientForm
template_name = 'appointment/index.html'
initial = {}
def get_initial(self):
base_initial = super().get_initial() # it's a simple dict
# initialize your form's data here
# Your logic ...
return base_initial
# The rest of your logic
...
And, in order to know why you need to do this. CreateView inherits from FormMixin which has initial and get_initial() thus will initialize your form's data instead of doing it under your form.
See this links for more details: CreateView MRO and FormMixin
I have a form in my site to get a report about some "collective payment". It has 3 main field: Value, date of payment and who paid.
The field "who paid" is a table containing the name of all users and a checkbox.
Currently I'm looping over all users, adding their full names to the table with a single checkbox. But I don't know how to get this data in my form associating it with each user name (just the text).
How can I get multiple BooleanFields in my form ? Is there a way of associate each BooleanField with an user's name?
model.py
from django.db import models
#created_date attibute needs it
from django.utils import timezone
# This Model is a super class "Financial Transaction"
class GroupTransaction(models.Model):
name = models.CharField(max_length=257, default='')
who_paid = models.CharField(max_length=257, default='')
value = models.DecimalField(max_digits=6, decimal_places=2)
justification = models.CharField(max_length=257, default='')
created_date = models.DateTimeField(default=timezone.now)
date = models.CharField(max_length=257, default='')
receipt = models.FileField(upload_to='comprovantes', blank=True, null=True)
its_type = models.CharField(max_length=257, default='')
def __str__(self):
#INCOMPLETOreturn "%s fez a movimentação financeira de %d para %s no dia " % (self.name, self.restaurant)
return "%s - %s" % (self.name , self.who_paid)
view.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from deposit.forms import DepositForm,MonthlyDepositForm
from django.contrib.auth.models import User
# Create your views here.
#login_required
def deposito(request):
if request.method == 'POST':
form = DepositForm(request.POST, request.FILES)
if form.is_valid():
form.save()
HttpResponseRedirect('/historico/')
else:
print (str(form.errors.as_data()))
else:
form = DepositForm()
groupForm = MonthlyDepositForm()
return render(request, 'shell/app_shell.html', {
'is_deposit' : True,
'title' : 'Deposit',
'transaction' : form,
'groupTransaction' : groupForm,
'users': User.objects.all()
})
form.py
class MonthlyDepositForm(forms.ModelForm):
value = forms.DecimalField()
date = forms.CharField(widget=forms.TextInput(attrs={
'class':'datepicker picker__input',
'readonly':'',
'tabindex':'54',
'aria-haspopup':'True',
'aria-expanded':'false',
'aria-readonly':'false',
'aria-owns':'birthdate_root'
}))
who_paid = forms.BooleanField()
its_type = forms.CharField(widget=forms.HiddenInput(attrs={'readonly':True}),
initial='Deposito Mensal')
class Meta:
model = GroupTransaction
fields = ('value', 'date','who_paid','its_type')
template.html:
<form class="col s12">
{% csrf_token %}
{{ groupTransaction.its_type }}
<div class="row"></div>
<!-- Nome do evento -->
<div class="row">
<div class="input-field col s6">
<!-- <input id="nome_evento" type="number" value="10" step="any" min="0.05" max="400" class="validate" required> -->
{{ groupTransaction.value }}
<label for="nome_evento">Value</label>
</div>
<div class="input-field col s6">
<!-- <input type="text" class="datepicker picker__input" readonly="" tabindex="54" aria-haspopup="true" aria-expanded="false" aria-readonly="false" aria-owns="birthdate_root" required> -->
{{ groupTransaction.date }}
<label for="data-mensal" data-error="Data inválida">Date</label>
</div>
</div>
<!-- Petianos que irão para o evento -->
<table class="striped">
<thead>
<!-- Cabeçalho tabela -->
<tr>
<th>Who Paid</th>
<th>
<div class="switch">
<b class="center-align">Default</b>
<label>
<input type="checkbox">
<span class="lever"></span>
</label>
</div>
</th>
</tr>
<!-- ============= -->
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.get_full_name }}</td>
<td>
<div class="switch">
<label>
<!-- <input type="checkbox"> -->
{{ groupTransaction.who_paid }}
<span class="lever"></span>
</label>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="row"></div>
<div class="row"></div>
<!-- Botão de registrar saque (submit) -->
<div class="row">
<button class="btn waves-effect waves-light col s6 m3 offset-s6 offset-m9 blue" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
How the form is:
You need to make who_paid a ManyToManyField(User). Then in the form you can set its widget like this:
class Meta:
model = GroupTransaction
fields = ('value', 'date','who_paid','its_type')
widgets = {
'who_paid': forms.CheckboxSelectMultiple(),
}
That will give you the right structure. Then you can render it manually if you want to change the display.
i want to auto increament for car_id field which is primary key but after saving registration data the car_id field should automaticaly increament so please anyone can suggest me for this.and my code is as follow.
models.py
class car(models.Model):
car_id = models.IntegerField(max_length=400, primary_key=True)
plate_no = models.IntegerField(max_length=400)
brand = models.CharField(max_length=400)
model = models.CharField(max_length=400)
Condition = models.CharField(max_length=400)
daily_price = models.IntegerField()
def __str__(self):
return ' '.join([
self. ordering,
])
views.py
def display_car(request):
carid_query = car.objects.values('car_id')
plate = car.objects.values('plate_no')
brand = car.objects.values('brand')
model = car.objects.values('model')
price = car.objects.values('daily_price')
condition = car.objects.values('Condition')
query_all = car.objects.all()
data={
'carid_query': carid_query,
'plate': plate,
'brand': brand,
'model': model,
'price': price,
'condition': condition,
'query_all': query_all,
}
return render(request, 'view_car.html', data)
HTML
<body>
<div class="center">
Home  Car Registration  Rent
</div>
<form action="/car/" id="form_id" method="post">
{% csrf_token %}
<div id="head_div">
<h3>car Registration</h3></div>
<table class="center">
<tr><td>
Car_id:<input type="text" name="car_id"><td>
<td>plate no:<input type="text" id="plate_id" name="plate_id"></td></tr>
<tr><td>Brand:<input type="text" id="brand_id" name="brand_id"><td>
<td>Model:<input type="text" name="model_id"></td></tr>
<tr><td>
Daily Price:<input type="text" id="price_id" name="price_id"></td>
<td>
Condition:<select name="select_id"><option value="Good">simple</option>
<option value="middle">A/C</option>
<option value="bad">good</option></select></td>
</tr>
<tr>
<td><input type="submit" id="sub_id" onclick="demo(this.form)"> <input type="button" id="cancel_id" VALUE="Cancel"></td>
</tr>
</table>
</form>
</body>