Additional fields to model with separate forms - django

I have a model Customer which has some general fields like name phone etc and some fields that are more private like ssn id tax_id etc. so it is like this
class Customer(models.Model):
#general fields
#more private staff fields
I want to have one form to create a new customer but I want them to be in different tabs (well my employer does want that). What would be the best practice? Have different models so different forms?
class Customer(models.Models):
#general fields
class PrivateFields(models.Model):
#private fields
customer = models.OneToOneField(Customer)
The above method would require the usage of two different forms to be rendered in one template. If I want one form (first method one model) would something like that stand or will it have issues:
I am using bootstrap3:
<ul class="nav nav-tabs" id="myTab">
<li>General</li>
<li>Private</li>
</ul>
<form class="inline">
<div class="tab-content">
<div class="tab-pane active" id="general-info">
<div class="row">
<div class="form-group col-md-6">
<label for="text">Home</label>
<input type="text" id="text" class="form-control input-sm" placeholder="Small">
</div>
</div>
</div>
<div class="tab-pane" id="private-details">
<div class="row">
<div class="form-group col-md-6">
<label for="profile">Profile</label>
<input type="text" id="profile" class="form-control input-sm" placeholder="profile">
</div>
</div>
</div>
</div>
<div class="row">
<input type="submit" class="btn btn-primary" value="Submit form">
</div>
</form>
bootply link

I can't see any reason to have them in separate models, or even two separate forms. Tabs are just divs that are shown/hidden by some Javascript, so you can simply put the 'public' fields in one div and the 'private' ones in the other.
<div class="tab-pane" id="general-info">
<div class="field">
{{ form.generalfield1.label_tag }}
{{ form.generalfield1 }}
{{ form.generalfield1.errors }}
</div>
... etc ...
</div>
<div class="tab-pane" id="general-info">
<div class="field">
{{ form.privatefield1.label_tag }}
{{ form.privatefield1 }}
{{ form.privatefield1.errors }}
</div>
... etc ...
</div>
If you want to do it in a more generic way, perhaps you could define a list of public/private field names in the view:
public_fields = ['name', 'address']
private_fields = ['trustworthy', 'bank_details']
and check membership as you iterate through:
<div class="tab-pane" id="general-info">
{% for field in form %}
{% if field.name in public_fields %}
<div class="field">
{{ field.label_tag }}
{{ field }}
{{ field.errors }}
</div>
{% endif %}
{% endfor %}
</div>
etc.

Related

Manually rendered form fields do not save data

I really wanted to figure this out myself and I spent over 4 hours on the subject but I give up now.
I have a form that is supposed to save data, and if I lay out the form with the {{ form }} tag everything works great. If I put in to form with individual tags like {{ form.client_email }}, the form data is not saved to the database.
I need to render these fields manually for front end purposes but I just couldn't figure out how to do it.
I appreciate your help a lot.
Here is my code.
views.py
def client_list_view(request):
if request.method == 'POST':
form = ClientModelForm(request.POST)
if form.is_valid():
client_title = form.cleaned_data["client_title"]
client_email = form.cleaned_data["client_email"]
client_turkishid_no = form.cleaned_data["client_turkishid_no"]
client_tax_no = form.cleaned_data["client_tax_no"]
client_tax_office = form.cleaned_data["client_tax_office"]
client_contactperson = form.cleaned_data["client_contactperson"]
client_phone_number = form.cleaned_data["client_phone_number"]
Client.objects.create(
client_title=client_title,
client_email=client_email,
client_turkishid_no=client_turkishid_no,
client_tax_no=client_tax_no,
client_tax_office=client_tax_office,
client_contactperson=client_contactperson,
client_phone_number=client_phone_number
).save()
return redirect("books:client-list")
else:
form = ClientModelForm()
client_list = Client.objects.all().order_by("client_title")
context = {'client_list' : client_list, "form": ClientModelForm}
return render(request, 'clients/client_list.html', context=context)
Working template
<div id="clientModal" class="modal bottom-sheet">
<div class="modal-content">
<form method="POST">
{% csrf_token %}
{{form}}
<button class="btn">Ekle</button>
</form>
</div>
</div>
Not Working Template
<div id="clientModal" class="modal bottom-sheet">
<div class="modal-content">
<div class="row">
<div class="col s12">
<ul class="tabs">
<li class="tab col m6"><a class="active" href="#gercek">Gerçek Kişi</a></li>
<li class="tab col m6"><a class="active" href="#tuzel">Tüzel Kişi</a></li>
</ul>
</div>
<div id="gercek" class="col s12">
<div class="col s12 m12 l12">
<div id="inline-form" class="scrollspy">
<div class="card-content">
<form method="POST">
{% csrf_token %}
<div class="row">
<div class="input-field col m4 s12">
<i class="material-icons prefix">email_outline</i>
{{form.client_email}}
<label for="{{ form.client_email.id_for_label }}">Müvekkilin E-Posta Adresi</label>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="tuzel" class="col s12">
<div class="col s12 m12 l12">
<div id="inline-form" class="scrollspy">
<div class="card-content">
<form method="POST">
{% csrf_token %}
<div class="row">
<div class="input-field col m4 s12">
<i class="material-icons prefix">account_circle</i>
{{form.client_title}}
<label for="{{ form.client_title.id_for_label }}">Müvekkilin Unvanı</label>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
In your "not working" template you wrap each of individually rendered field with a form tag. That's not the correct way to do what you need. Just keep one form tag like you do in the working template and render all fields inside:
<div id="clientModal" class="modal bottom-sheet">
<div class="modal-content">
<form method="POST">
{% csrf_token %}
<!-- put your fields here with any additional markup you need -->
{{ form.client_email }}
<label for="{{ form.client_email.id_for_label }}">Müvekkilin E-Posta Adresi</label>
{{ form.client_title }}
<label for="{{ form.client_title.id_for_label }}">Müvekkilin Unvanı</label>
<!-- by the way you can use form.<field>.label_tag -->
{{ form.client_phone_number }}
{{ form.client_phone_number.label_tag }}
<!-- and maybe you'd also like to render errors -->
{{ form.client_phone_number.errors }}
<button class="btn">Ekle</button>
</form>
</div>
</div>
Also, the ClientModelForm seems to be an instance of ModelForm, so you do not need to deal with form.cleaned_data manually. For new objects you can just call form.save(commit=True):
if form.is_valid():
form.save(commit=True)

Django - How to apply onlivechange on CharField / IntegerField

I want to hide the field form.name_of_parent_if_minor if the age (CharField) < 18 else show. I am not getting where to write jQuery or JS code or add separate js file. For this do I need to the html definition and add tag for age (CharField) or we can perform action on this as well.
I am new to the Django so if you find any mistakes in my code then any help would be appreciated for guidance.
forms.py
class StudentDetailsForm(forms.ModelForm):
class Meta:
model = StudentDetails
views.py
class StudentCreateView(LoginRequiredMixin, CreateView):
template_name = 'student/student_details_form.html'
model = StudentDetails
form_class = StudentDetailsForm
success_url = "/"
html
{% extends 'student/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div id="idParentAccordian" class="content-section">
<form method="POST">
{% csrf_token %}
<div class="card mt-3">
<div class="card-header">
<a class="collapsed card-link" style="display: block;" data-toggle="collapse"
href="#idPersonalInformation">Personal Information</a>
</div>
<div id="idPersonalInformation" class="collapse show" data-parent="#idParentAccordian">
<div class="card-body">
<div class="row">
<div class="col-6">
{{ form.joining_date|as_crispy_field }}
</div>
<div class="col-6">
{{ form.class|as_crispy_field }}
</div>
</div>
{{ form.student_name|as_crispy_field }}
{{ form.father_name|as_crispy_field }}
{{ form.mother_name|as_crispy_field }}
{{ form.gender|as_crispy_field }}
<div class="row">
<div class="col-6">
{{ form.date_of_birth|as_crispy_field }}
</div>
<div class="col-6">
{{ form.age|as_crispy_field }}
</div>
</div>
<div>
{{ form.name_of_parent_if_minor|as_crispy_field }}
</div>
</div>
</div>
</div>
<div class="form-group mt-3">
<button class="btn btn-outline-info" type="submit">Save</button>
<a class="btn btn-outline-secondary" href="javascript:history.go(-1)">Cancel</a>
</div>
</form>
</div>
{% endblock content %}
the easiest way but not the cleanest is to add JS script in your html
the recommanded way is to add static folder to your app and load static files in your html template using {% load static %}

Is it correct use for Django ModelForm

My question; i'm used ModelForm instead of forms.Form and i want to organize form in html file instead of forms.py file (i don't want to use attr tag because my form.html file is very complicated) Is this usage correct?
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model=Comment
fields=[
'name',
'email',
'comment',
]
html file
<form class="post-comment-form" method="POST">
{% csrf_token %}
{% if form.errors %}
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
{% endif %}
<div class="form-row">
<div class="form-item half blue">
<label for="id_name" class="rl-label" >Name</label>
{{ form.name}}
</div>
<div class="form-item half blue">
<label for="id_email" class="rl-label" >Email</label>
{{ form.email}}
</div>
</div>
<div class="form-row">
<div class="form-item blue">
<label for="id_comment" class="rl-label">Comment</label>
{{ form.comment }}
</div>
</div>
<button type="submit" class="save-button">Submit</button>
If you don't want to use the {{form}} then you have to give the input field for each model's fields like <input type="text" name = "name"> .For example
<div class="form-row">
<div class="form-item half blue">
<label for="id_name" class="rl-label" >Name</label>
**<input type="text" name = "name">**
</div>
<div class="form-item half blue">
<label for="id_email" class="rl-label" >Email</label>
<input type="text" name = "email">
</div>
</div>
<div class="form-row">
<div class="form-item blue">
<label for="id_comment" class="rl-label">Comment</label>
<input type="text" name = "comment">
</div>
</div>
<button type="submit" class="save-button">Submit</button>
On the html you can have something like this
{% csrf_token %}
{{ form.as_p }}
and then proceed with styling or better yet you can use {% crispy %} which personal I find it great based on what you want to archive, your forms.py looks ok.

Sort by ascending and descending using django-filter

I have the following code for few filterings:
from .models import ProductLaptop
import django_filters
class ProductLaptopFilter(django_filters.FilterSet):
laptops_name = django_filters.CharFilter(lookup_expr='icontains')
laptops_price = django_filters.NumberFilter()
laptops_price__gt = django_filters.NumberFilter(field_name='laptops_price', lookup_expr='gt')
laptops_price__lt = django_filters.NumberFilter(field_name='laptops_price', lookup_expr='lt')
class Meta:
model = ProductLaptop
fields = ['laptops_name', 'laptops_price', 'brand_name']
The html codes for this:
{% load widget_tweaks %}
{% block content %}
<form method="get">
<div class="well">
<h4 style="margin-top: 0">Filter</h4>
<div class="row">
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.laptops_name.label_tag }}
{% render_field filter.form.laptops_name class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.laptops_price.label_tag }}
{% render_field filter.form.laptops_price class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.brand_name.label_tag }}
{% render_field filter.form.brand_name class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.laptops_price__gt.label_tag }}
{% render_field filter.form.laptops_price__gt class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.laptops_price__lt.label_tag }}
{% render_field filter.form.laptops_price__lt class="form-control" %}
</div>
</div>
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</form>
Which gives me a view like below:
Here I want to add an option where people can sort the items in ascending and descending order.
Can anyone give me some suggestions how can I implement this?
For that, you can use OrderingFilter from django-filter. Create this filter in your FilterSet class and provide all fields that should be enabled for ordering.

How would to show form validation errors with django single fields?

I've to put in the fields of the form individually because for me its a little easier to style, my issue is that I can't seem to get it to display the error messages on validation. The form validates correctly, it just doesnt show what errors I get when I do get an error, instead it just doesnt submit. How can I fix this?
Template:
<form action="#" method="post"> {%csrf_token%} {{form.management_form}}
{%for f in form%}
{{ f.non_field_errors }}
<div class="row">
<div class="medium-3 columns ">
<label> First Name
{{ member_fname.errors }}
{{f.member_fname}}
</label>
</div>
<div class="medium-3 columns ">
<label> Last Name
{{ member_lname.errors }}
{{f.member_lname}}
</label>
</div>
<div class="medium-3 columns ">
<label> Email
{{ member_email.errors }}
{{f.member_email}}
</label>
</div>
<div class="medium-3 columns ">
<label> Phone #
{{ member_phone.errors }}
{{f.member_phone}}
</label>
</div>
</div>
<hr/>
{%endfor%}
<div class="row">
<div class="small-3 columns small-centered">
<button type="submit" class="button medium radius"> submit</button>
</div>
</div>
</div>
</form>
Syntax for rendering validation errors:
{{ form.fieldname.errors }}
This will show validation errors in a list format and if you want to render them as text then use:
{{ form.fieldname.errors.as_text }}