I'm working on a project using Python(3.7) and Django(2) in which I need to create a multi-select field inside one of my form.
Here's what I have tried:
from models.py:
class ExperimentModel(models.Model):
user = models.ForeignKey(User, related_name='experiments',
on_delete=models.CASCADE)
name = models.CharField(max_length=255)
start_date = models.DateField()
change_date = models.DateField()
end_date = models.DateField()
assets = models.CharField(max_length=450, choices=choices)
goals = models.CharField(max_length=255, blank=True)
comments = models.TextField(max_length=1000)
created_at = models.DateTimeField(auto_now=True)
From forms.py:
class ExperimentForm(forms.ModelForm):
choices = (
('CO2 SCRUBBER', 'CO2 SCRUBBER'),
('CORN OIL', 'CORN OIL'),
('DRYERS', 'DRYERS'),
('ENVIRONMENTAL', 'ENVIRONMENTAL'),
('UTILITIES', 'UTILITIES'),
('LAB', 'LAB'),
('SIEVES', 'SIEVES'),
('GRAINS & MILLING', 'GRAINS & MILLING'),
('SEPARATION', 'SEPARATION'),
('AIR & GAS', 'AIR & GAS'),
('COOK', 'COOK'),
('EVAPORATION', 'EVAPORATION'),
('WATER', 'WATER'),
('STORAGE', 'STORAGE'),
('BOILER', 'BOILER'),
('FERMENTATION', 'FERMENTATION'),
('DISTILLATION', 'DISTILLATION'),
('BUILDING AND FACILITIES', 'BUILDING AND FACILITIES'),
('CHEMICAL', 'CHEMICAL'),
)
assets = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=choices)
class Meta:
model = ExperimentModel
fields = ('user', 'name', 'start_date', 'change_date', 'end_date', 'assets',
'goals', 'comments')
From template.html:
<form method="POST" action="{% url 'new-experiment' %}">
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
{% csrf_token %}
<h2> Create new Experiment:</h2>
{# {{ form|crispy }}#}
<div class="form-group">
<input type="text" name="name" id="name" class="form-control input-lg"
placeholder="experiment name" tabindex="3" required>
</div>
<div class="form-group">
<label for="start_date"> Start Date </label>
<input type="date" name="start_date" id="start_date" class="form-control input-lg"
placeholder="start_date" tabindex="4" required>
</div>
<div class="form-group">
<label for="change_date"> Change Date </label>
<input type="date" name="change_date" id="change_date" class="form-control input-lg"
placeholder="change date" tabindex="4" required>
</div>
<div class="form-group">
<label for="end_date"> End Date </label>
<input type="date" name="end_date" id="end_date" class="form-control input-lg"
placeholder="end date" tabindex="4" required>
</div>
<div class="form-group">
<label for="assets"> Assets </label>
{# <input type="text" name="assets" id="assets" class="form-control input-lg"#}
{# placeholder="Assets" tabindex="3" required>#}
<select name="assets" class="form-control" id="assets" multiple>
<option value="CO2 SCRUBBER">CO2 SCRUBBER</option>
<option value="CORN OIL">CORN OIL</option>
<option value="DRYERS">DRYERS</option>
<option value="ENVIRONMENTAL">ENVIRONMENTAL</option>
<option value="UTILITIES">UTILITIES</option>
<option value="LAB">LAB</option>
<option value="SIEVES">SIEVES</option>
<option value="GRAINS & MILLING">GRAINS & MILLING</option>
<option value="SEPARATION">SEPARATION</option>
<option value="AIR & GAS">AIR & GAS</option>
<option value="COOK">COOK</option>
<option value="EVAPORATION">EVAPORATION</option>
<option value="WATER">WATER</option>
<option value="STORAGE">STORAGE</option>
<option value="BOILER">BOILER</option>
<option value="FERMENTATION">FERMENTATION</option>
<option value="BUILDING AND FACILITIES">BUILDING AND FACILITIES</option>
<option value="CHEMICAL">CHEMICAL</option>
</select>
</div>
<div class="form-group">
<label for="assets"> Goals </label>
<input type="text" name="goals" id="goals" class="form-control input-lg"
placeholder="Goals" tabindex="3" required>
</div>
<div class="form-group">
<label for="comments"> Comments </label>
<textarea name="comments" id="comments" class="form-control input-lg"
rows="5" required>
</textarea>
</div>
<hr class="colorgraph">
<div class="row">
<div class="col-md-12 float-right">
<input type="submit" value="Create" class="btn btn-primary btn-block btn-lg float-right"
tabindex="7" style="background-color: #7386D5; color: white">
</div>
{# <div class="col-xs-12 col-md-6"><a href="{% url 'register' %}"#}
{# class="btn btn-success btn-block btn-lg">Create New Account</a>#}
{# </div>#}
</div>
</form>
And here's the views.py:
def post(self, request, *args, **kwargs):
if request.method == 'POST':
post_data = request.POST.copy()
post_data.update({'user': request.user.pk})
form = ExperimentForm(post_data)
print('req submitted')
if form.is_valid():
print('form valid')
form.save(commit=False)
form.user = request.user
form.save()
return HttpResponseRedirect(reverse_lazy('all-experiments'))
else:
return HttpResponseRedirect(reverse_lazy('new-experiment'))
When I select the only one option from multiple assets, the experiment has been created but when select multiple options the request failed, what's can wrong here?
How can I achieve the multi-select functionality for assets for experiment Model?
Also, no error is displaying in the template, even though I have printed the errors in the template, but doesn't any error is displaying on the template.
Thanks in advance!
Related
I need to make it so that the select from the form is displayed in the database, None appears in its place in the database
everything is added except categories and stocks
I was told that I need to add value to option, but nothing happened
what's wrong
Here is my views.py :
def create_product(request):
user = request.user
category = user.category_set.all()
stock = user.stock_set.all()
if request.method == 'POST':
product = Product()
product.title = request.POST.get('title')
product.categories = user.category_set.get(id=request.POST.get('categories'))
product.price = request.POST.get('price')
product.user = request.POST.get('user')
product.amount = request.POST.get('amount')
product.stock = Stock.objects.get(id=request.POST.get('stock'))
product.user = request.user
product.save()
return redirect('index')
return render(request, 'main/create.html', {'category':category,'stocks':stock})
Here is my models.py :
class Product(models.Model):
title = models.CharField(verbose_name="Название товара", max_length=250)
categories = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
price = models.IntegerField(verbose_name="Цена")
user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='products')
amount = models.CharField(max_length=250,verbose_name='Количество')
user = models.ForeignKey(User, on_delete=models.PROTECT)
stock = models.ForeignKey(Stock, on_delete=models.PROTECT, blank=True, null=True)
def get_absolute_url(self):
return reverse("post_detail",kwargs={'pk':self.pk})
class Meta:
verbose_name = 'Товар'
verbose_name_plural = 'Товары'
def __str__(self):
return self.title
My create template :
<div class="" style="width: 600px; margin:0 auto; transform: translate(0, 10%);">
<h1 class="display-6">Создайте товар</h1>
<form action="{% url 'create_product' %}" method="POST" class="form-control" style="background:rgba(0, 0, 0, 0.1); height: 500px;">
{% csrf_token %}
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Название</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Название товара" name="title">
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Цена</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Цена товара" name="price">
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Количество товара</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Кол-во" name="amount">
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Категория</label>
<select class="form-select" aria-label="Default select example" name="category">
{% for categories in categories %}
<option value="">{{ categories.title }}</option>
{% endfor %}
</select>
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Склад</label>
<select class="form-select" aria-label="Default select example" name="stock">
{% for stocks in stocks %}
<option value="{{ stocks.pk }}" >{{ stocks.title }}</option>
{% endfor %}
</select>
</div>
<div class="mb-3">
<button class="btn btn-success">Создать</button>
Выйти
</div>
</form>
</div>
I am trying to retrieve data from a form using the Post method and store it in the database. However, when I click on the submit button,I keep on getting the following error:
NOT NULL constraint failed: posts_subscribe.firstname
Here is my views.py:
def subscribe(request):
if request.method == 'POST':
firstname=request.POST.get('firstname')
secondname=request.POST.get('secondname')
email=request.POST.get('email')
phonenumber=request.POST.get('phonenumber')
en= Subscribe(firstname=firstname, secondname=secondname, email = email, phonenumber = phonenumber)
en.save()
return redirect('/')
return render(request, 'subscribe.html')
My models.py:
class Subscribe(models.Model):
firstname = models.CharField(max_length=30, blank = True)
secondname = models.CharField(max_length=30, blank = True)
email = models.CharField(max_length=30)
phonenumber = models.IntegerField()
Here is my template:
{% extends 'index.html' %}
{% block subscribe %}
<div class="card mx-5">
<h1 class="mx-5 mt-3"> Subscribe</h1>
<form method="POST" enctype="multipart/form-data" action="subscribe">
{% csrf_token %}
<div class="mb-3 mx-5">
<label for="firstname" class="form-label ">First Name</label>
<input type="text" class="form-control form-control-lg" id="firstname" placeholder="firstname">
</div>
<div class="mb-3 mx-5">
<label for="secondname" class="form-label">Second Name (Optional)</label>
<input type="text" class="form-control form-control-lg" id="secondname" placeholder="secondname">
</div>
<div class="mb-3 mx-5">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control form-control-lg" id="email" placeholder="example#example.com">
</div>
<div class="mb-3 mx-5">
<label for="phonenumber" class="form-label">Phonenumber</label>
<input type="number" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678">
</div>
<div class="mb-3 mx-5">
<button type="submit" class="btn-primary"> Subscribe</button>
</div>
</form>
</div>
{% endblock %}
And my url patterns:
urlpatterns= [
path('', views.index, name='index'),
path('subscribe', views.subscribe, name ='subscribe'),
path('allposts', views.allposts, name='allposts'),
path('political', views.political, name='political'),
path('religion', views.religion, name='religion'),
path('trending', views.trending, name='treniding'),
path('<str:pk>', views.post, name='post'),
]
You should add a name="…" attribute [mdn] to the <input> elements, so:
<input type="text" name="firstname" class="form-control form-control-lg" id="firstname" placeholder="firstname">
…
<input type="text" name="secondname" class="form-control form-control-lg" id="secondname" placeholder="secondname">
…
<input type="email" name="email" class="form-control form-control-lg" id="email" placeholder="example#example.com">
…
<input type="number" name="phonenumber" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678">
I am working on a small django-python project which has two models "staff_type" and "staff". In the staff_type model, only designation and date fields are populated. And in the staff model, there is OneToOneField relation of staff_type. Means whenever a user want to add staff first he/she will have to add staff_type and then in the staff module, user will choose the staff type (designation) from a select menu in which all the staff_type are shown respectively.
Now, whenever a user select any designation (staff_type) and fill the entire form, I want to store the selected staff_type id in the staff model/table.
Note: I have tried this from django admin, and it works perfectly but I want to do the same work in my own designed templates.
Modles.py
class staff_type(models.Model):
designation = models.CharField(max_length=50)
salary = models.IntegerField()
datetime = models.DateTimeField()
entrydatetime = models.DateTimeField( auto_now=False, auto_now_add=False)
class staff(models.Model):
staff_type = models.OneToOneField(staff_type, on_delete=models.CASCADE)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
fathername = models.CharField(max_length=50)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
state = models.CharField(max_length=50)
zip = models.IntegerField(blank=True)
address = models.CharField(max_length=100)
contact =models.CharField(max_length=20)
cnic = models.CharField(max_length=14)
photo = models.ImageField()
cv = models.ImageField()
otherfiles = models.ImageField()
views.py
def add_staff_type(request):
if request.method == 'POST':
designation = request.POST.get('designation')
salary = request.POST.get('salary')
datetime = request.POST.get('datetime')
add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime, entrydatetime = dt.now())
add_staff_type.save()
messages.info(request, "Staff type has been Added.")
return redirect('add_staff_type')
else:
#fetching records from the database table
display_staff_type = staff_type.objects.all()
return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type})
#this view is for fetching the designation column and displaying in the select tag
#and rendering add_staff html form
def add_staff(request):
staff = staff_type.objects.all()
return render(request, 'staff/add_staff.html', {'staff':staff})
#this view is for adding the staff
def add_staff_view(request):
if request.method == 'POST':
staff_type = request.POST.get('stafftype')
firstname = request.POST.get('firstname')
lastname = request.POST.get('lastname')
fathername = request.POST.get('fathername')
city = request.POST.get('city')
country = request.POST.get('country')
state = request.POST.get('state')
zipcode = request.POST.get('zip')
contact = request.POST.get('contact')
cnic = request.POST.get('cnic')
address = request.POST.get('address')
photo = request.FILES.get('photo')
cv = request.FILES.get('cv')
otherfiles = request.FILES.get('photo')
add_staff = staff.objects.create(firstname=firstname, lastname=lastname, fathername=fathername, city=city,country=country, state=state, contact=contact, cnic=cnic, zip=zipcode, address=address, photo=photo, cv=cv, otherfiles=otherfiles, staff_type=staff_type)
add_staff.save()
messages.info(request, "Staff has been Added.")
return redirect('add_staff')
else:
return render(request, 'staff/add_staff.html')
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("staff/add_staff_type", views.add_staff_type, name="add_staff_type"),
path("staff/add_staff", views.add_staff, name="add_staff"),
path("staff/add_staff_view", views.add_staff_view, name="add_staff_view"),
]
add_staff.html
<form class="needs-validation" action="add_staff_view" method="POST" enctype="multipart/form-data" novalidate>
{% csrf_token %}
<div class="card-body">
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom01">Staff Type</label>
<select class="form-control" id="validationCustom01" name="stafftype">
{% for staff in staff %}
<option name="stafftype" value="{{ staff.id }}" required>{{staff.designation}}</option>
{% endfor %}
</select>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom02">First name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="First name" name="firstname" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom03">Last name</label>
<input type="text" class="form-control" id="validationCustom03" placeholder="Last name" name="lastname" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom04">Father Name</label>
<input type="text" class="form-control" id="validationCustom04" placeholder="Father Name" name="fathername" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom05">City</label>
<input type="text" class="form-control" id="validationCustom05" placeholder="City" name="city" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom06">Country</label>
<input type="text" class="form-control" id="validationCustom06" value="Pakistan" name="country" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom07">State</label>
<input type="text" class="form-control" id="validationCustom07" placeholder="State" name="state" >
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom08">Zip</label>
<input type="number" class="form-control" id="validationCustom08" value="0000" name="zip">
</div>
</div>
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom09">Contact</label>
<input type="text" class="form-control" id="validationCustom09" placeholder="Phone Number" name="contact" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom10">CNIC</label>
<input type="number" class="form-control" id="validationCustom10" placeholder="xxxxx-xxxxxxx-x" name="cnic" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-6 mb-3">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="Current Address" name="address">
</div>
</div>
<div class="form-row">
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile01">Photo</label>
<input type="file" class="form-control" id="customFile01" name="photo"/>
</div>
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile02">CV</label>
<input type="file" class="form-control" id="customFile02" name="cv"/>
</div>
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile03">Other Files/Photos</label>
<input type="file" class="form-control" id="customFile03" name="otherfiles"/>
</div>
</div>
<div classs="form-row">
<button class="btn btn-primary" type="submit">Add Staff</button>
</div>
</div>
</div>
</form>
I tried my best at the above code but it gives me the error.
Error
Exception Value:
Cannot assign "'1'": "staff.staff_type" must be a "staff_type" instance.
staff_type in staff model must be staff_type model instance so first get model instance
s_type = staff_type.objects.get(id=request.POST.get('stafftype'))
staff.objects.create(...,staff_type=s_type)
Or you can also assign fk directly like this.
staff.objects.create(staff_type_id=request.POST.get('stafftype'))
And please try to follow PEP8 standards for writing python codes.
Note: It's better using django forms and Also you can use built-in generic class-based views which will make your things easier.
The problem is that you are sending number to Staff model into the field "staff_type". You either need to cast it to staff_type, or put an instance there
I have one Boolean model field payment_received which as default value set to False. From the frontend dropdown it as coming as 0 or 1 form.No matter what value from the dropdown I select it is always saved as 1(True) in the table.
I am trying to debug it & I can verify that proper value is coming from the HTML form but after cleaning is done by Django form it is always results in True value.
My Model
class InvoiceHeader(models.Model):
class Meta:
db_table = 'invoice_hdr'
invoice_no = models.CharField(max_length=50)
client = models.ForeignKey(Client, on_delete=models.DO_NOTHING)
campaign = models.ForeignKey(CampaignHeader, on_delete=models.DO_NOTHING, null=True)
invoice_date = models.DateField()
invoice_amount = models.DecimalField(max_digits=11, decimal_places=2)
cgst = models.DecimalField(max_digits=11, decimal_places=2)
sgst = models.DecimalField(max_digits=11, decimal_places=2)
igst = models.DecimalField(max_digits=11, decimal_places=2)
total_amount = models.DecimalField(max_digits=11, decimal_places=2)
payment_received = models.BooleanField(default=False)
def __str__(self):
return self.invoice_no
My Form
class InvoiceHeaderForm(forms.ModelForm):
class Meta:
fields = ('invoice_no','invoice_date','campaign','client', 'invoice_amount','cgst','sgst','igst','total_amount','payment_received')
model = InvoiceHeader
invoice_no = forms.CharField(max_length=50)
invoice_date = forms.DateField()
client = forms.ModelChoiceField(queryset=Client.objects.all())
campaign = forms.ModelChoiceField(queryset=CampaignHeader.objects.all())
invoice_amount = forms.DecimalField(max_digits=11, decimal_places=2)
cgst = forms.DecimalField(max_digits=11, decimal_places=2)
igst = forms.DecimalField(max_digits=11, decimal_places=2)
sgst = forms.DecimalField(max_digits=11, decimal_places=2)
total_amount = forms.DecimalField(max_digits=11, decimal_places=2)
payment_received = forms.BooleanField()
def clean_payment_received(self):
val = self.cleaned_data['payment_received']
print('TEST1', val) #<---- always True
return val
def clean_invoice_no(self):
invoice_no = self.cleaned_data.get('invoice_no')
if InvoiceHeader.objects.filter(invoice_no=invoice_no).exists() and not str(self.instance):
raise forms.ValidationError('Invoice no. already exist!')
return invoice_no
Template
<form action="{{ url }}" method="POST" id="invoice_form">
<input type="hidden" name="edit_mode" value="{% if invoice %}{{'1'}}{% else %}{{'0'}}{% endif %}">
{% csrf_token %}
<div class="card shadow py-2">
<div class="card-body">
<div class="row ">
<div class="col-md-6">
<div class="form-group">
<label for="invoice_no">Invoice No.<sup class="text-danger">*</sup></label>
<input type="text" tabindex="1" class="form-control" id="invoice_no"
name="invoice_no" placeholder="Enter campaign name"
value="{% if invoice %}{{invoice.invoice_no}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="client">Client<sup class="text-danger">*</sup></label>
<select tabindex="3" class="form-control selectpicker" data-live-search="true"
id="client" name="client">
{% for client in clients %}
<option data-state="{{client.state}}" id="client" value="{{ client.id }}"
{% if invoice and invoice.client_id == client.id %}{{'selected'}}{% endif %}>
{{ client }}</option>
{% endfor %}
</select>
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="invoice_amount">Invoice Amount<sup class="text-danger">*</sup></label>
<input type="text" data-type='currency' tabindex="5" class="form-control" id="invoice_amount"
name="invoice_amount" placeholder="Enter invoice amount"
value="{% if invoice %}{{invoice.invoice_amount}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="igst">IGST<sup class="text-danger">*</sup></label>
<input type="text" data-type='currency' tabindex="7" class="form-control" id="igst"
name="igst" placeholder="Enter invoice amount"
value="{% if invoice %}{{invoice.igst}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="payment_received">Payment Received?<sup class="text-danger">*</sup></label>
<select tabindex="9" class="form-control selectpicker" data-live-search="true"
id="payment_received" name="payment_received">
<option value="0" {% if invoice and not invoice.payment_received %}{{'selected'}}{% endif %}>NO</option>
<option value="1" {% if invoice and invoice.payment_received %}{{'selected'}}{% endif %}>YES</option>
</select>
<small class="error-msg form-text text-danger"></small>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="invoice_date">Invoice Date<sup class="text-danger">*</sup></label>
<input type="text" tabindex="2" class="form-control datepicker" id="invoice_date"
name="invoice_date" placeholder="Enter invoice date"
value="{% if invoice %}{{invoice.invoice_date|date:'d/m/Y'}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="campaign">Campaign<sup class="text-danger">*</sup></label>
<select tabindex="4" class="form-control selectpicker" data-live-search="true"
id="campaign" name="campaign">
{% if invoice %}
{% for campaign in campaigns %}
<option value="{{campaign.id}}" {% if campaign == invoice.campaign %}{{'selected'}}{% endif %}>{{campaign}}</option>
{% endfor %}
{% endif %}
</select>
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="cgst">CSGT<sup class="text-danger">*</sup></label>
<input type="text" data-type='currency' tabindex="6" class="form-control" id="cgst"
name="cgst" placeholder="Enter invoice amount"
value="{% if invoice %}{{invoice.cgst}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="sgst">SGST<sup class="text-danger">*</sup></label>
<input type="text" data-type='currency' tabindex="8" class="form-control" id="sgst"
name="sgst" placeholder="Enter invoice amount"
value="{% if invoice %}{{invoice.sgst}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="total_amount">Total Amount<sup class="text-danger">*</sup></label>
<input type="text" data-type='currency' tabindex="10" class="form-control" id="total_amount" readonly
name="total_amount" placeholder="Enter invoice amount"
value="{% if invoice %}{{invoice.total_amount}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
</div>
</div>
</div>
</div>
<br>
</form>
Any help would be appreciated....
This might work (in forms.py). Also can you tell which django version you are using?
[...]
payment_received = forms.BooleanField(widget=CheckboxInput(default=False), required=False)
[...]
the 'selected' value of the html template will render the booleanfield to True.
Because usually a booleanfield on html-side is a checkbox, which is True if it is selected.
I'm trying to make the create form look better but it just doesn't work. It shows fine but when I try to submit it doesn't do anything. I've already tried with different forms of one field, I think I can't make it work because this has file fields and foreign keys, etc.
Why it doesn't work?
forms.py
class Lcreate(forms.ModelForm):
class Meta:
model = Auction
fields = ('name', 'img', 'description', 'category', 'starting_bid')
widgets = {
'description' : forms.Textarea(attrs={
'rows': '5',
'cols': '90',
'maxlength': '500',
}),
'name' : forms.Textarea(attrs={
'rows': '1',
'cols': '100',
'maxlength': '30',
}),
}
views.py
#login_required(login_url="login")
def create(request):
if request.method == "POST":
form = Lcreate(request.POST or None, request.FILES or None)
if form.is_valid():
user = request.user
starting_bid = form.cleaned_data["starting_bid"]
description = form.cleaned_data["description"]
name = form.cleaned_data["name"]
img = form.cleaned_data["img"]
category = form.cleaned_data["category"]
listing = Auction(user=user, starting_bid=starting_bid, description=description, name=name, img=img, category=category)
listing.save()
return redirect('index')
else:
form = Lcreate()
return render(request, "auctions/create.html", {
"form": Lcreate,
"categories": Category.objects.all()
})
html
<div class="space"></div>
<div class="create-form">
<h1>Create Listing</h1>
<form method="POST" enctype="multipart/form-data">
{%csrf_token%}
<div class="form-group">
<label for="name">Title</label>
<input autofocus class="form-control" id="name" type="text" name="name" placeholder="Title">
<div class="space"></div>
<label for="img">Image</label>
<input type="file" id="img" name="img" class="form-control-file">
<div class="space"></div>
<label for="description">Description</label>
<textarea class="form-control" name="description" id="description" rows="3" placeholder="description"></textarea>
<div class="space"></div>
<label for="category">Category</label>
<select class="form-control" id="category" name="category">
{% for category in categories %}
<option name="category">{{category.category_list}}</option>
{%endfor%}
</select>
<div class="space"></div>
<label for="starting_bid">Bid</label>
<input class="form-control" type="number" name="starting_bid" placeholder="Starting Bid">
</div>
<button type="submit" class="btn btn-primary">Post Auction</button>
</form>
</div>
It should be like this
views.py:
def create(request):
infos=listing.objects.all()
form = listingForm(request.POST, request.FILES)
if form.is_valid():
listing.objects.create(**form.cleaned_data)
return render(request, "auctions/index.html", {'infos':infos})
else:
return render(request, 'auctions/create.html', {'form': form})
HTML
<h2>Create Listings</h2>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}{% load widget_tweaks %}
<div class="form-group row">
<label for="{{ form.id_name}}" class="col-sm-2 col-form-label">Title</label>
<div class="col-sm-10">
{{ form.name|add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_description}}" class="col-sm-2 col-form-label">Description</label>
<div class="col-sm-10">
{{ form.description |add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_starting_bid}}" class="col-sm-2 col-form-label">Starting Bid</label>
<div class="col-sm-10">
{{ form.id_starting_bid|add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_img }}" class="col-sm-2 col-form-label">Image</label>
<div class="col-sm-10">
{{ form.img |add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_category }}" class="col-sm-2 col-form-label">Category</label>
<div class="col-sm-10">
{{ form.category|add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>