Django: Checkboxes are not saved while FormValidationError - python

I am working with a CreateView. When sending my form with all fields properly filled out, the field tickets (ManyToMany field) is also saved. However if I POST my form with some validation error (e.g. required field empty), then all the pre-filled fields are still field through request.POST. However, my pre-checked fields are not selected anymore. Do you know why?
Demonstration
view.py
class DiscountCreate(AdminPermissionRequiredMixin, SuccessMessageMixin,
FormValidationMixin, BaseDiscountView, CreateView):
form_class = DiscountForm
template_name = 'discounts/admin/create.html'
success_message = _("Discount Code has been successfully created.")
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['event'] = self.request.event
return kwargs
def get_success_url(self):
return reverse('discounts:admin:detail', kwargs={
'organizer': self.request.organizer.slug,
'event': self.request.event.slug,
'discount': self.instance.pk
})
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['type_fixed'] = Discount.TYPE_FIXED
context['type_percentage'] = Discount.TYPE_PERCENTAGE
return context
def form_valid(self, form):
self.instance = form.save(commit=False)
self.instance.event = self.request.event
self.instance.status = Discount.STATUS_ACTIVE
return super().form_valid(form)
Template
<div class="card">
<div class="card-header">
<h4 class="card-header-title">
{% trans "Creating Discount Code" %}
</h4>
</div>
<div class="card-body">
<form method="post" autocomplete="off" novalidate>
{% csrf_token %}
<div class="form-group">
<label for="{{ form.code.id_for_label }}">
{{ form.code.label }}
</label>
{{ form.code }}
{% if form.code.errors %}
<div class="invalid-feedback d-block">
{{ form.code.errors|first }}
</div>
{% endif %}
</div>
<div class="form-group">
<label for="{{ form.type.id_for_label }}">
{{ form.type.label }}
</label>
{{ form.type }}
{% if form.type.errors %}
<div class="invalid-feedback d-block">
{{ form.type.errors|first }}
</div>
{% endif %}
</div>
<div class="form-group fixed{% if form.type.value != type_fixed %} d-none {% endif %}">
{{ form.value.label_tag }}
<div class="input-group">
{{ form.value }}
<div class="input-group-append">
<span class="input-group-text text-dark">{{ request.event.currency }}</span>
</div>
</div>
{% if form.value.errors %}
<div class="invalid-feedback d-block">
{{ form.value.errors|first }}
</div>
{% endif %}
</div>
<div class="form-group percentage{% if form.type.value != type_percentage %} d-none {% endif %}">
{{ form.percentage.label_tag }}
<div class="input-group">
{{ form.percentage }}
<div class="input-group-append">
<span class="input-group-text text-dark">%</span>
</div>
</div>
{% if form.percentage.errors %}
<div class="invalid-feedback d-block">
{{ form.percentage.errors|first }}
</div>
{% endif %}
</div>
<div class="form-group">
{{ form.available_amount.label_tag }}
{{ form.available_amount }}
{% if form.available_amount.errors %}
<div class="invalid-feedback d-block">
{{ form.available_amount.errors|first }}
</div>
{% endif %}
</div>
<div class="form-group">
<label for="{{ form.tickets.id_for_label }}">
{{ form.tickets.label }}
<span class="badge badge-light">{% trans "Optional" %}</span>
</label>
<small class="form-text text-muted mt--2">{{ form.tickets.help_text }}</small>
{% for ticket_id, ticket_label in form.tickets.field.choices %}
<div class="custom-control custom-checkbox">
<input
type="checkbox"
name="{{ form.tickets.html_name }}"
value="{{ ticket_id }}"
class="custom-control-input"
id="id_{{ form.tickets.html_name }}_{{ forloop.counter }}"
{% if ticket_id in form.tickets.value %}checked{% endif %}>
<label class="custom-control-label" for="id_{{ form.tickets.html_name }}_{{ forloop.counter }}">{{ ticket_label }}</label>
</div>
{% endfor %}
{% if form.tickets.errors %}
<div class="invalid-feedback d-block">
{{ form.tickets.errors|first }}
</div>
{% endif %}
</div>
<div class="form-group">
<label for="{{ form.valid_from.id_for_label }}">
{{ form.valid_from.label }}
<span class="badge badge-light">{% trans "Optional" %}</span>
</label>
<small class="form-text text-muted mt--2">{{ form.valid_from.help_text }}</small>
{{ form.valid_from }}
{% if form.valid_from.errors %}
<div class="invalid-feedback d-block">
{{ form.valid_from.errors|first }}
</div>
{% endif %}
</div>
<div class="form-group">
<label for="{{ form.valid_until.id_for_label }}">
{{ form.valid_until.label }}
<span class="badge badge-light">{% trans "Optional" %}</span>
</label>
<small class="form-text text-muted mt--2">{{ form.valid_until.help_text }}</small>
{{ form.valid_until }}
{% if form.valid_until.errors %}
<div class="invalid-feedback d-block">
{{ form.valid_until.errors|first }}
</div>
{% endif %}
</div>
<div class="form-group">
<label for="{{ form.comment.id_for_label }}">
{{ form.comment.label }}
<span class="badge badge-light">{% trans "Optional" %}</span>
</label>
<small class="form-text text-muted mt--2">{{ form.comment.help_text }}</small>
{{ form.comment }}
{% if form.comment.errors %}
<div class="invalid-feedback d-block">
{{ form.comment.errors|first }}
</div>
{% endif %}
</div>
<button type="submit" class="btn btn-primary btn-block">{% trans "Create Discount Code" %}</button>
</form>
</div>
</div> {# / .card #}
<a class="btn btn-block btn-link text-muted mb-4" href="{% url 'discounts:admin:index' request.organizer.slug request.event.slug %}">
{% trans "Cancel discount code creation" %}
</a>
forms.py
class DiscountForm(forms.ModelForm):
# Remove required attribute from HTML elements
use_required_attribute = False
value = forms.DecimalField(decimal_places=2, required=False)
percentage = forms.DecimalField(max_digits=4, decimal_places=2, required=False)
class Meta:
model = Discount
fields = (
'code',
'type',
'value',
'percentage',
'available_amount',
'tickets',
'valid_from',
'valid_until',
'comment',
)
def __init__(self, *args, **kwargs):
self.event = kwargs.pop('event')
super().__init__(*args, **kwargs)
for visible_field in self.visible_fields():
visible_field.field.widget.attrs['class'] = 'form-control'
self.fields['tickets'].queryset = self.event.tickets.all()
self.fields['code'].widget.attrs['autofocus'] = True
self.fields['valid_from'].widget.attrs['class'] = 'form-control start-date picker'
self.fields['valid_until'].widget.attrs['class'] = 'form-control end-date picker'
self.fields['valid_from'].widget.format = settings.DATETIME_INPUT_FORMATS[0]
self.fields['valid_until'].widget.format = settings.DATETIME_INPUT_FORMATS[0]
self.fields['valid_from'].widget.attrs['data-lang'] = get_lang_code()
self.fields['valid_until'].widget.attrs['data-lang'] = get_lang_code()
def clean(self):
cleaned_data = super().clean()
discount_type = cleaned_data.get('type')
if discount_type:
if discount_type == Discount.TYPE_FIXED:
value = cleaned_data.get('value')
cleaned_data['percentage'] = None
if not value:
message = _("Please enter how much discount you want to give.")
self.add_error('value', forms.ValidationError(message))
if discount_type == Discount.TYPE_PERCENTAGE:
percentage = cleaned_data.get('percentage')
cleaned_data['value'] = None
if not percentage:
message = _("Please enter how much discount you want to give.")
self.add_error('percentage', forms.ValidationError(message))
def clean_value(self):
value = self.cleaned_data['value']
if value:
value = smallest_currency_unit_converter(
value,
self.event.currency,
)
return value
def clean_percentage(self):
percentage = self.cleaned_data['percentage']
if percentage:
percentage /= 100 # convert 19 to 0.19
return percentage
def clean_valid_until(self):
valid_until = self.cleaned_data['valid_until']
if valid_until and valid_until > self.event.end_date:
valid_until = self.event.end_date
return valid_until
def clean_valid_from(self):
valid_from = self.cleaned_data['valid_from']
if valid_from and valid_from > self.event.end_date:
raise forms.ValidationError(_("Discount code should become valid \
before the event starts."), code='valid_from')
return valid_from
def clean_code(self):
code = self.cleaned_data['code']
code_check = self.event.discounts.filter(
code=code
).exclude(pk=self.instance.pk).exists()
if code_check:
raise forms.ValidationError(_("The code you chose as your discount code \
already exists for this event. Please change it."), code='code_exists')
return code

After I broke the problem down, the final solution that helped me can be found here: Django template: {% if 5 in ['4', '3', '5'] %} doesn't work

Related

Django Adding Pagination To Search Form Page

How do I add pagination to this form's search functionality?
By default, on page refresh, the HTML template for loop shows all the results for all the courses. When the user types in criteria into the form, the form filters the course results template for loop based on what the user typed. Is there a way on page refresh to show only a set limit of course results on the page instead of all of them? Then when a user searches/filters, that pagination limit of X number of course results on a page will still need to show but still applied to the search criteria/filter.
HTML:
<form id='courseform' action="." method="get">
<div class="form-row">
<div class="form-group col-12"> {{ form.title__icontains }} </div>
<div class="form-group col-md-2 col-lg-2"> {{ form.visited_times__gte.label_tag }} {{ form.visited_times__gte }} </div>
<div class="form-group col-md-2 col-lg-2"> {{ form.visited_times__lte.label_tag }} {{ form.visited_times__lte }} </div>
<div class="form-group col-md-2 col-lg-2"> {{ form.created_at__gte.label_tag }} {{ form.created_at__gte }} </div>
<div class="form-group col-md-2 col-lg-2"> {{ form.created_at__lte.label_tag }} {{ form.created_at__lte }} </div>
<div class="form-group col-md-2"> {{ form.skill_level.label_tag }} {{ form.skill_level }} </div>
<div class="form-group col-md-2"> {{ form.subjects.label_tag }} {{ form.subjects }} </div>
</div>
<script src='https://www.google.com/recaptcha/api.js?render=6LeHe74UAAAAAKRm-ERR_fi2-5Vik-uaynfXzg8N'></script>
<div class="g-recaptcha" data-sitekey="6LeHe74UAAAAAKRm-ERR_fi2-5Vik-uaynfXzg8N"></div>
<button type="submit" class="btn btn-primary form-control">Search</button>
<p>This site is protected by reCAPTCHA and the Google
<a target="_blank" rel="noopener noreferrer" href="https://policies.google.com/privacy">Privacy Policy</a> and
<a target="_blank" rel="noopener noreferrer" href="https://policies.google.com/terms">Terms of Service</a> apply.
</p>
</form>
<!--Used to have {{ object.subjects }} next to -->
{% for object in object_list %}
<a class="course_list_link" href="{{ object.get_absolute_url }}"> <p class = "course_list_border"> <strong> {{ object }} </strong> <br/> <br/> {{ object.description }} <br/><br/> {{ object.skill_level }}   {{ object.created_at }}   Views: {{ object.visited_times }}  
{% for sub in object.subjects.all %}
{{ sub.name }}
{% endfor %} </p> </a>
{% endfor %}
Views.py:
class CourseListView(ListView):
template_name = 'courses/course_list.html'
​
def get_queryset(self):
return Course.objects.all()
​
def get(self, request, *args, **kwargs):
form = CourseForm(request.GET)
queryset = self.get_queryset()
if form.is_valid():
queryset = queryset.filter(**{k: v for k, v in form.cleaned_data.items() if v})
self.object_list = queryset
return self.render_to_response(self.get_context_data(form=form,object_list=queryset,))
Forms.py:
class CourseForm(forms.Form):
title__icontains = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control col-12', 'autocomplete':'off', 'id':'title_contains', 'type':'search', 'placeholder': 'Course Name'}), required=False)
visited_times__gte = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off','id':'view_count_max', 'type':'number', 'min':'0', 'placeholder': '0'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)])
visited_times__lte = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'view_count_min', 'type':'number', 'min':'0', 'placeholder': '1000000'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)])
created_at__gte = forms.DateField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'date_max','type':'date', 'placeholder': 'mm/dd/yyy'}), required=False)
created_at__lte = forms.DateField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'date_min', 'type':'date', 'placeholder': 'mm/dd/yyy'}), required=False)
skill_level = forms.ChoiceField(widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off','id':'skill_level'}), choices = ([('',''), ('Beginner','Beginner'), ('Intermediate','Intermediate'),('Advanced','Advanced'), ]), required=False)
subjects = forms.ModelChoiceField(queryset=Subject.objects.all().order_by('name'), empty_label="", widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off', 'id':'subjects'}), required=False)
# the new bit we're adding
def __init__(self, *args, **kwargs):
super(CourseForm, self).__init__(*args, **kwargs)
self.fields['title__icontains'].label = "Course Name:"
self.fields['visited_times__gte'].label = "Min Views:"
self.fields['visited_times__lte'].label = "Max Views:"
self.fields['created_at__gte'].label = "Min Date:"
self.fields['created_at__lte'].label = "Max Date:"
self.fields['skill_level'].label = "Skill Level:"
self.fields['subjects'].label = "Subject:"
self.fields['subjects'].queryset = Subject.objects.filter()
Models.py:
class Subject(models.Model):
SUBJECT_CHOICES = ()
name = models.CharField(max_length=20,choices=SUBJECT_CHOICES)
def __str__(self):
return self.name
​
class Meta:
ordering = ('name',)
​
class Course(models.Model):
​
SKILL_LEVEL_CHOICES = (
('Beginner', 'Beginner'),
('Intermediate', 'Intermediate'),
('Advanced', 'Advanced'),
)
​
slug = models.SlugField()
title = models.CharField(max_length=120)
description = models.TextField()
allowed_memberships = models.ManyToManyField(Membership)
created_at = models.DateTimeField(auto_now_add=True)
subjects = models.ManyToManyField(Subject)
skill_level = models.CharField(max_length=20,choices=SKILL_LEVEL_CHOICES, null=True)
visited_times = models.PositiveIntegerField(default=0)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('courses:detail', kwargs={'slug': self.slug})
#property
def lessons(self):
return self.lesson_set.all().order_by('position')
​
class Meta:
ordering = ('title',)
I tried following some tutorials Django docs one but not sure how to embed that pagination code to mine.
https://docs.djangoproject.com/en/3.0/topics/pagination/
I would appreciate if anyone could help me with this.
Please edit to include your code.
In the page you linked to, read this section:
https://docs.djangoproject.com/en/3.0/topics/pagination/#paginating-a-listview
You just need to add this to your ListView
paginate_by = N
then add
<div class="pagination">
<span class="step-links">
{% if contacts.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
</span>
{% if contacts.has_next %}
next
last »
{% endif %}
</span>
</div>
to course_list.html.
Serach form (html) :
<!-- Search Form -->
<form class="navbar-search navbar-search-dark form-inline mr-3 d-none d-md-flex ml-lg-auto" action="{% url 'search' %}" method="get">
<div class="form-group mb-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search Tasks" aria-label="Search" name="q">
<button class="btn btn-outline-white my-2 my-sm-0" type="submit">Search</button>
</div>
</form>
views.py
class SearchView(ListView): # taskları arama sonucu listeliyoruz
model = Task
template_name = 'task/search.html'
paginate_by = 5
context_object_name = 'task'
def get_queryset(self):
query = self.request.GET.get("q")
if query:
return Task.objects.filter(
Q(title__icontains=query) | Q(content__icontains=query) | Q(tag__title__icontains=query)).order_by(
'id').distinct()
return Task.objects.all().order_by('id')
In whichever field you want to use pagination, write the code there (example category_detail.html) :
<div class="card-footer py-4">
{% if is_paginated %}
<nav aria-label="...">
<ul class="pagination justify-content-end mb-0">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}" tabindex="-1">
<i class="fas fa-angle-left"></i>
<span class="sr-only">Previous</span>
</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1">
<i class="fas fa-angle-left"></i>
<span class="sr-only">Previous</span>
</a>
</li>
{% endif %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="page-item active">
<a class="page-link" href="#"> {{ i }} </a>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="?page={{ i }}">{{ i }}<span class="sr-only">(current)</span></a>
</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}">
<i class="fas fa-angle-right"></i>
<span class="sr-only">Next</span>
</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#">
<i class="fas fa-angle-right"></i>
<span class="sr-only">Next</span>
</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
I hope the examples worked for you.

Django formtools with custom template

I have the following custom wizard
<div class="container">
<div id="smartwizard">
<ul>
<li>Engagement Setup<br /><small>Basic info</small></li>
<li>File Upload<br /><small>Upload files</small></li>
<li>Business Rules<br /><small>rules</small></li>
<li>Documentation<br /><small>documentation</small></li>
</ul>
<div>
<div id="step-1" class="">
<div id="form-step-0" role="form" data-toggle="validator">
<div class="form-group">
<label for="text">Code <span class="tx-danger">*</span></label>
<input type="text" class="form-control" name="code" id="code" placeholder="Write your code" required>
<div class="help-block with-errors"></div>
</div>
</div>
<hr />
</div>
....
</div>
</div>
<br />
</div>
I have setup the django form as such
class PageOne(forms.Form):
ibs_code = forms.CharField(max_length=100)
engagement_name = forms.CharField(max_length=100)
engagement_manager = forms.CharField(max_length=100)
engagement_partner = forms.CharField(max_length=100)
solution = forms.CharField(label='What solution would you like to use?', widget=forms.Select(choices=FRUIT_CHOICES))
And of course the views..
class TestWizard(SessionWizardView):
file_storage = FileSystemStorage(
location=os.path.join(settings.MEDIA_ROOT, 'temp_uploads'))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.is_done = False
def get_template_names(self):
if self.is_done:
# return [self.templates['done']]
return [TEMPLATES['done']]
else:
return [TEMPLATES[self.steps.current]]
.....
......
Now I want to use the custom template with the form. Meaning, I want to generate the form fields the way the html/style looks with form-group and such. How can I achieve this?
I tried the documentation but they weren't any sources for custom templating
Update #1: Doing something like this is not sufficient
<div id="form-step-0" role="form">
<div class="form-group">
{% if wizard.form.forms %}
{{wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{form}}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</div>
</div>
I need it to look just like the html I put together
First, you can specify the class to be used for your form fields, for example:
class PageOne(forms.Form):
ibs_code = forms.CharField(
max_length=100,
widget=forms.TextInput(
attrs={'class' : 'YourClassName'}
)
)
Second, you can put the individual fields within the template as you want
<div class="container">
<div id="smartwizard">
<ul>
<li>Engagement Setup<br /><small>Basic info</small></li>
<li>File Upload<br /><small>Upload files</small></li>
<li>Business Rules<br /><small>rules</small></li>
<li>Documentation<br /><small>documentation</small></li>
</ul>
<form>
{{ wizard.form.management_form }}
{% csrf_token %}
<div>
<div id="step-1" class="">
<div id="form-step-0" role="form" data-toggle="validator">
<div class="form-group">
<label for="text">Code <span class="tx-danger">*</span></label>
{{ form.ibs_code }}
{{ form.ibs_code.errors }}
</div>
</div>
<hr />
</div>
....
</div>
</form>
</div>
<br />
</div>
EDIT - ACTUAL LIVE EXMAPLE
<form id="" class="max-width-800px margin-center" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ wizard.management_form }}
{{ wizard.form.media }}
<input name="job-is_user" type="checkbox" hidden {% if request.user.is_authenticated %}checked{% endif %}>
<input name="job-is_company" type="checkbox" hidden {% if request.user.company_user %}checked{% endif %}>
<div class="form-group">
<label for="id_job-plan_"PLANS[0].id >Job Listing Type</label>
{{ wizard.form.plan }}
<div class="alert alert-primary top-3">Jobs are subscription-based and are active until you've filled the position. At the end of your recurring billing cycle you will be charged and your listing will be moved back to the top of its category.</div>
</div>
<div class="form-group row">
<div class="col-6">
<label for="id_job-title">Job Title</label>
{{ wizard.form.title }}
</div>
<div class="col-6">
<label for="id_job-category">Job Category</label>
<span class="form-select">
{{ wizard.form.category }}
</span>
</div>
</div>
<div class="form-group">
<label for="">Job Type</label>
<div class="row">
{% for employment in EMPLOYMENTS %}
<div class="col-4">
<span class="form-radio form-radio-lg">
<input type="radio" id="id_job-employment_{{employment.id}}" name="job-employment" value="{{ employment.id }}" required {% if job.employment.id == employment.id or wizard.form.employment.value|add:"0" == employment.pk %}checked{% endif %}>
<label for="id_job-employment_{{employment.id}}">{{ employment }}</label>
</span>
</div>
{% endfor %}
</div>
</div>
<div class="form-group row">
<div class="col-6">
<label for="id_job-job_level">Job Level</label>
<span class="form-select">
{{ wizard.form.job_level }}
</span>
</div>
<div class="col-6">
<label for="id_job-salary_range">Job Compensation</label>
<span class="form-select">
{{ wizard.form.salary_range }}
</span>
</div>
</div>
<div id="job-location-groupX" class="form-group">
<label for="id_job-office_base">Job Location</label>
<div class="row">
{% for office in OFFICE_BASE %}
<div class="col-6">
<span class="form-radio form-radio-lg">
<input type="radio" id="id_job-office_base_{{office.id}}" name="job-office_base" value="{{ office.id }}" {% if job.office_base.id == office.id or wizard.form.office_base.value|add:"0" == office.pk %}checked{% endif %}>
<label for="id_job-office_base_{{office.id}}">{{ office.name }}</label>
</span>
</div>
{% endfor %}
</div>
<div id="new-job-location-details" class="hidden top-1">
{{ wizard.form.outside_location }}
{{ wizard.form.outside_location.errors }}
<ul class="list-unstyled list-increase-spacing">
<li>
<span class="form-checkbox">
{{ wizard.form.relocation_assistance }}
<label id="label-id_job-relocation_assistance" for="id_job-relocation_assistance">Relocation assistance provided</label>
{{ wizard.form.relocation_assistance.errors }}
</span>
</li>
<li>
<span class="form-checkbox">
{{ wizard.form.visa_sponsorship }}
<label for="id_job-visa_sponsorship">Visa sponsorship provided</label>
{{ wizard.form.visa_sponsorship.errors }}
</span>
</li>
</ul>
</div>
</div>
<div class="form-group">
<label for="id_job-description">Job Description</label>
<div class="col-12">
{{ wizard.form.description }}
{{ wizard.form.description.errors }}
</div>
</div>
<div id="job-how-to-apply-groupX" class="form-group">
<label>How to Apply to This Job</label>
<div class="row">
<div class="col-6">
<span class="form-radio form-radio-lg">
<input type="radio" required id="new-job-apply-us" value="4" name="job-apply_online" {% if job.apply_online == 4 or wizard.form.apply_online.value|add:"0" == 4 %}checked {% endif %}>
<label for="new-job-apply-us">Through us <em class="float-right tablet-hide">(recommended)</em></label>
</span>
</div>
<div class="col-6">
<span class="form-radio form-radio-lg">
<input type="radio" id="new-job-apply-you" name="job-apply_online" value="3" {% if job.apply_online == 3 or wizard.form.apply_online.value|add:"0" == 3 %}checked {% endif %}>
<label for="new-job-apply-you">Through you <em class="float-right tablet-hide">(external URL)</em></label>
</span>
</div>
</div>
<div id="new-job-apply-details" class="hidden top-1">
{{ wizard.form.apply_url }}
{{ wizard.form.howto_apply }}
</div>
</div>
<div id="job-extras" class="form-group">
<h6>Additional Extras <span class="optional-field">(optional)</span></h6>
{{ wizard.form.addons }}
</div>
<button type="submit" class="btn btn-lg btn-solid-teal">{% if request.user.company_user %}Preview Your Listing{% elif request.user.is_authenticated %}Enter Company Details{% else %}User Details{% endif %} →</button>
</form>
forms.py
class JobPostWizardForm1(forms.ModelForm):
error_css_class = "alert alert-error"
category = forms.ModelChoiceField(Category.objects.all(), empty_label='Choose one...', required=False)
job_level = forms.ModelChoiceField(JobLevel.objects.all(), empty_label='Choose one...', required=False)
salary_range = forms.ModelChoiceField(Salary.objects.active(), empty_label='Choose one...', required=False)
plan = forms.ModelChoiceField(Plan.objects.all(), empty_label=None, required=True, widget=PlanSelect)
is_user = forms.BooleanField(required=False)
is_company = forms.BooleanField(required=False)
class Meta:
model = Job
fields = [
'plan','title','category','employment','job_level','salary_range','office_base', 'outside_location',
'relocation_assistance','visa_sponsorship','description','apply_online','howto_apply','addons', 'is_user',
'is_company', 'apply_url'
]
def __init__(self, is_active= False, edit_mode=False, plan=0, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['plan'].initial = Plan.objects.all()[plan]
if is_active : self.fields['plan'].widget.attrs['disabled'] = True
self.fields['description'].required = True
self.fields['apply_url'].widget.attrs['placeholder'] = 'External URL'
self.fields['howto_apply'].widget = forms.Textarea()
self.fields['howto_apply'].widget.attrs['rows']=10
self.fields['howto_apply'].widget.attrs['placeholder']="Additional instructions..."
self.fields['relocation_assistance'].widget = AuthenticJobsCheckbox()
self.fields['visa_sponsorship'].widget = AuthenticJobsCheckbox()
self.fields['addons'].widget = AddOnCheckboxSelectMultiple()
self.fields['addons'].queryset = AddOnItem.objects.filter(active=True)
#if edit_mode : self.fields['addons'].widget.attrs['disabled'] = True
if is_active : self.fields['addons'].widget.attrs['onclick'] = "return false;"
self.error_class = DivErrorList

Flask Form Handling in Jinja2 For Loop

I have a blog-type application where the homepage displays posts with some information and with an Add Comment form. The form is intended to write to my Comments() model in models.py for that specific post.
The Problem: is that because I am looping through the posts in home.html, the post.id is not available to the home function in routes.py. So, when the form is validated, the comment is applied to all the posts, not just the one in which the comment is added.
The question: how can I get the relevant post.id in the home function from the Jinja forloop and have the comment be applied to the specific post, not just all the posts on the homepage?? I'm not seeing my logic/syntax error - what am I missing here? Thanks
The resulting error: AttributeError: 'function' object has no attribute 'id'
which of course makes sense because the application has no clue what post we are referencing in the Jinja2 forloop in home.html.
here is the Comments db model in models.py:
class Comments(db.Model):
comment_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, nullable=True, primary_key=False)
post_id = db.Column(db.Integer, nullable=True, primary_key=False)
comment = db.Column(db.String(2000), unique=False, nullable=True)
comment_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
class Meta:
database = db
def fetch_post_comments(self, post_id):
comments = Comments.query.filter(Comments.post_id==post_id)
return comments
def fetch_user(self, user_id):
user = User.query.filter(User.id==user_id).first_or_404()
return user.username
def __repr__(self):
return f"Comments ('{self.user_id}', '{self.post_id}', '{self.comment}', '{self.comment_date}')"
And here is my home function in routes.py:
#app.route("/")
#app.route("/home", methods=['GET', 'POST'])
#login_required
def home():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
comment_form = CommentForm()
def add_comment(post_id):
if comment_form.validate_on_submit():
new_comment = Comments(user_id=current_user.id,
post_id=post_id,
comment=comment_form.comment_string.data)
db.session.add(new_comment)
db.session.commit()
flash('HOT TAKE! Posted your comment.', 'success')
# return redirect(url_for('post', post_id=post.id))
def get_upvote_count(post_id):
count = Vote.query.filter(Vote.post_id==post_id).count()
return count
def get_flag_count(post_id):
count = Flag.query.filter(Flag.post_id == post_id).count()
return count
def get_comment_count(post_id):
count = Comments.query.filter(Comments.post_id == post_id).count()
return count
def get_favorite_count(post_id):
count = Favorites.query.filter(Favorites.post_id == post_id).count()
return count
def get_youtube_id_from_url(url):
video_id = url.split('v=')[1]
if '&' in video_id:
video_id = video_id.split('&')[0]
base_url = "https://www.youtube.com/embed/"
return base_url + video_id
def get_spotify_embed_url(url):
track_or_playlist = url.split('https://open.spotify.com/')[1].split('/')[0]
base_url = f"https://open.spotify.com/embed/{track_or_playlist}/"
spotify_id = url.split('https://open.spotify.com/')[1].split('/')[1]
embed_url = base_url + spotify_id
return embed_url
return base_url + video_id
return render_template('home.html',
posts=posts,
get_upvote_count=get_upvote_count,
get_comment_count=get_comment_count,
get_flag_count=get_flag_count,
get_favorite_count=get_favorite_count,
comment_form=comment_form,
add_comment=add_comment,
get_youtube_id_from_url=get_youtube_id_from_url,
get_spotify_embed_url=get_spotify_embed_url)
And here is my home.html
{% extends "layout.html" %}
{% block content %}
{% for post in posts.items %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ url_for('static', filename='profile_pics/' + post.author.image_file) }}">
<div class="media-body">
<div class="article-metadata">
<div align="left">
<a class="mr-2 text-secondary" href="{{ url_for('user_posts', username=post.author.username) }}">{{ post.author.username }}</a>
</div>
<div align="left">
<small class="text-muted">Posted on: {{ post.date_posted.strftime('%Y-%m-%d') }}</small>
</div>
<div align="right">
<a class="mr-2 text-secondary" href="{{ url_for('flag', post_id=post.id, user_id=current_user.id) }}">Flag Post</a>
</div>
<div align="right">
<a class="mr-2 text-secondary" href="{{ url_for('add_favorite', post_id=post.id, user_id=current_user.id) }}">Favorite Post ({{ get_favorite_count(post.id) }})</a>
</div>
<div align="right">
<a class="mr-2 text-secondary" href="{{ url_for('post', post_id=post.id) }}">Comments ({{ get_comment_count(post.id) }})</a>
</div>
</div>
<h3><a class="article-title" href="{{ url_for('post', post_id=post.id) }}">{{ post.title }}</a></h3>
<p class="article-content justify-content-center">{{ post.content }}</p>
<br>
{% for url in post.urls.split('||') %}
{% if 'youtube.com' in url %}
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item"
src="{{ get_youtube_id_from_url(url) }}" allowfullscreen="" frameborder="0">
</iframe>
</div>
Link
{% elif 'soundcloud.com' in url %}
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" scrolling="no" frameborder="no"
src="{{ 'https://w.soundcloud.com/player/?url=' + url }}">
</iframe>
</div>
Link
{% elif 'spotify.com' in url %}
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item"
src="{{ get_spotify_embed_url(url) }}" allowfullscreen allow="encrypted-media">
</iframe>
</div>
Link
{% elif 'vimeo.com' in url %}
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" scrolling="no" frameborder="no"
src="{{ 'https://player.vimeo.com/video/' + url.split('https://vimeo.com/')[1] }}">
</iframe>
</div>
Link
{% elif 'tumblr.com' in url %}
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item"
src="{{ url }}" frameborder="0">
</iframe>
</div>
Link
{% else %}
Link
<br>
{% endif %}
{% endfor %}
<br>
<br>
<p class="text-muted"><strong>Tags:</strong></p>
{% for tag in post.tags.replace(' ', ' ').strip(',').split(' ') %}
<a class="btn btn-light" href="{{url_for('tag_posts', tag=tag)}}">{{tag.strip('#').strip(' ').lower() }}</a>
{% endfor %}
<br>
<form method="POST" action="" enctype="multipart/form-data">
{{ comment_form.hidden_tag() }}
<fieldset class="form-group">
<br>
<br>
<p class="text-muted"><strong>Add a comment:</strong></p>
<div class="form-group">
{% if comment_form.comment_string.errors %}
{{ comment_form.comment_string(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in comment_form.comment_string.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ comment_form.comment_string(class="form-control form-control-lg") }}
<!-- {{ add_comment(post_id=post.id) }}-->
{% endif %}
</div>
</fieldset>
<div class="form-group">
{{ comment_form.submit(class="btn btn-secondary") }}
</div>
</form>
<br>
<p class="text-muted mt-4"><strong>Street Cred: </strong>{{ get_upvote_count(post.id) }}</p>
<a class="btn btn-secondary mb-4" href="{{url_for('upvote', user_id=post.author.id, post_id=post.id)}}">Upvote</a>
</div>
</article>
{% endfor %}
{% for page_num in posts.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
{% if page_num %}
{% if posts.page == page_num %}
<a class="btn btn-secondary mb-4" href="{{ url_for('home', page=page_num) }}">{{ page_num }}</a>
{% else %}
<a class="btn btn-outline-info mb-4" href="{{ url_for('home', page=page_num) }}">{{ page_num }}</a>
{% endif %}
{% else %}
...
{% endif %}
{% endfor %}
{% endblock content %}
A couple of options:
Add the post.id to the url as a parameter or arg, here's the arg method:
Add the url to the form and set the post.id as the arg:
<form method="POST" action="{{url_for('home', post_id=post.id)}}" enctype="multipart/form-data">
And in the route:
new_comment = Comments(user_id=current_user.id,
post_id=request.args.get('post_id', type=int),
comment=comment_form.comment_string.data)
OR
Add a hidden field to your form, and set the value of that to be the post.id:
Add a hidden field onto your form:
post_id = HiddenField()
You'll need to replace the CSRF render (hidden_tag()) to prevent auto rendering of the post_id field:
{{ comment_form.csrf_token }}
Next, set the value of your hidden field data (credit to this answer for this function):
{% set p = comment_form.post_id.process_data(post.id) %}
{{ comment_form.post_id() }}
and finally, in the route, (remove the add_comment declaration):
def home():
# Omitted ...
if comment_form.validate_on_submit():
new_comment = Comments(user_id=current_user.id,
post_id=comment_form.post_id.data,
comment=comment_form.comment_string.data)
db.session.add(new_comment)
# etc...
Hope this helps, note it's not tested

Saving edited data via formsets

I am trying to edit multiple rows of data in a model via formsets. In my rendered form, I use javascript to delete (hide and assign DELETE) rows, and then save changes with post.
My view:
def procedure_template_modification_alt(request, cliniclabel, template_id):
msg = ''
clinicobj = Clinic.objects.get(label=cliniclabel)
template_id = int(template_id)
template= ProcedureTemplate.objects.get(templid = template_id)
formset = ProcedureModificationFormset(queryset=SectionHeading.objects.filter(template = template))
if request.method == 'POST':
print(request.POST.get)
# Create a formset instance with POST data.
formset = ProcedureModificationFormset(request.POST)
if formset.is_valid():
print("Form is valid")
instances = formset.save(commit=False)
print(f'instances:{instances}')
for instance in instances:
print(f'Instance: {instance}')
instance.template = template
instance.save()
msg = "Changes saved successfully."
print("Deleted forms:")
for form in formset.deleted_forms:
print(form.cleaned_data)
else:
print("Form is invalid")
print(formset.errors)
msg = "Your changes could not be saved as the data you entered is invalid!"
template= ProcedureTemplate.objects.get(templid = template_id)
headings = SectionHeading.objects.filter(template = template)
return render(request, 'procedures/create_procedure_formset_alt.html',
{
'template': template,
'formset': formset,
'headings': headings,
'msg': msg,
'rnd_num': randomnumber(),
})
My models:
class ProcedureTemplate(models.Model):
templid = models.AutoField(primary_key=True, unique=True)
title = models.CharField(max_length=200)
description = models.CharField(max_length=5000, default='', blank=True)
clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
def __str__(self):
return f'{self.description}'
class SectionHeading(models.Model):
procid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=200)
default = models.CharField(max_length=1000)
sortorder = models.IntegerField(default=1000)
fieldtype_choice = (
('heading1', 'Heading1'),
('heading2', 'Heading2'),
)
fieldtype = models.CharField(
choices=fieldtype_choice, max_length=100, default='heading1')
template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, null=False)
def __str__(self):
return f'{self.name} [{self.procid}]'
My forms:
class ProcedureCrMetaForm(ModelForm):
class Meta:
model = SectionHeading
fields = [
'name',
'default',
'sortorder',
'fieldtype',
'procid'
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class': 'form-control'})
self.fields['default'].widget.attrs.update({'class': 'form-control'})
self.fields['sortorder'].widget.attrs.update({'class': 'form-control'})
self.fields['fieldtype'].widget.attrs.update({'class': 'form-control'})
ProcedureCreationFormset = formset_factory(ProcedureCrMetaForm, extra=3)
ProcedureModificationFormset = modelformset_factory(SectionHeading, ProcedureCrMetaForm,
fields=('name', 'default', 'sortorder','fieldtype', 'procid'),
can_delete=True,
extra=0
# widgets={"name": Textarea()}
)
The template:
{% block content %} {% load widget_tweaks %}
<div class="container">
{% if user.is_authenticated %}
<div class="row my-1">
<div class="col-sm-2">Name</div>
<div class="col-sm-22">
<input type="text" name="procedurename" class="form-control" placeholder="Enter name of procedure (E.g. DNE)"
value="{{ template.title }}" />
</div>
</div>
<div class="row my-1">
<div class="col-sm-2">Description</div>
<div class="col-sm-22">
<input type="text" name="proceduredesc" class="form-control" placeholder="Enter description of procedure (E.g. Diagnostic Nasal Endoscopy)"
value="{{ template.description }}" />
</div>
</div>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %} {{ formset.management_form }}
<div class="row mt-3">
<div class="col-sm-1">Select</div>
<div class="col-sm-6">Heading</div>
<div class="col-sm-8">Default (Normal description)</div>
<div class="col-sm-2">Sort Order</div>
<div class="col-sm-4">Type</div>
<div class="col-sm-2">Action</div>
</div>
{% for form in formset %}
<div class="row procrow" id="row{{ forloop.counter0 }}">
<div class="" style="display: none;">{{ form.procid }}</div>
<div class="col-sm-6">
{{ form.name }}
</div>
<div class="col-sm-8">
<div class="input-group">
{{ form.default }}
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
{{ form.sortorder }}
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
{{ form.fieldtype }}
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<div class="input-group-append">
<button id="add{{ forloop.counter0 }}" class="btn btn-success add-row">+</button>
</div>
<div class="input-group-append">
<button id="del{{ forloop.counter0 }}" class="btn btn-danger del-row">-</button>
</div>
</div>
</div>
</div>
{% endfor %} {% endif %}
<div class="row my-3">
<div class="col-sm-8"></div>
<div class="col-sm-8">
<div class="input-group">
<div class="input-group-append mx-1">
<button id="save_report" type="submit" class="btn btn-success"><i class="fal fa-shield-check"></i>
Save Report Format</button>
</div>
<div class="input-group-append mx-1">
<button id="save_report" type="button" class="btn btn-danger"><i class="fal fa-times-hexagon"></i>
Cancel</button>
</div>
</div>
</div>
<div class="col-sm-8"></div>
</div>
<div>
{% for dict in formset.errors %} {% for error in dict.values %} {{ error }} {% endfor %} {% endfor %}
</div>
</form>
</div>
{% endblock %}
My data is displayed as below (Screenshot). I make changes with javascript when the delete button is pressed, so that the html becomes like this:
<div class="row procrow" id="row2" style="display: none;">
<div class="" style="display: none;"><input type="hidden" name="form-2-procid" value="25" id="id_form-2-procid"></div>
<div class="col-sm-6">
<input type="text" name="form-2-name" value="a" maxlength="200" class="form-control" id="id_form-2-name">
</div>
<div class="col-sm-8">
<div class="input-group">
<input type="text" name="form-2-default" value="v" maxlength="1000" class="form-control" id="id_form-2-default">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<input type="number" name="form-2-sortorder" value="1000" class="form-control" id="id_form-2-sortorder">
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
<select name="form-2-fieldtype" class="form-control" id="id_form-2-fieldtype">
<option value="heading1" selected="">Heading1</option>
<option value="heading2">Heading2</option>
</select>
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<div class="input-group-append">
<button id="add2" class="btn btn-success add-row">+</button>
</div>
<div class="input-group-append">
<button id="del2" class="btn btn-danger del-row">-</button>
</div>
</div>
</div>
<input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE" checked=""></div>
On submitting the data, I get the following output, and data does not reflect the deletion I did. It displays the same thing again. There are no errors. But my edited data is not being saved.
Output:
<bound method MultiValueDict.get of <QueryDict: {'csrfmiddlewaretoken': ['ka3avICLigV6TaMBK5a8zeVJlizhtsKW5OTDBLlYorKd7Iji9zRxCX2vvjBv6xKu'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-procid': ['23'], 'form-0-name': ['External ear canal'], 'form-0-default': ['Bilateral external ear canals appear normal. No discharge.'], 'form-0-sortorder': ['100'], 'form-0-fieldtype': ['heading1'], 'form-1-procid': ['24'], 'form-1-name': ['Tympanic membrane'], 'form-1-default': ['Tympanic membrane appears normal. Mobility not assessed.'], 'form-1-sortorder': ['500'], 'form-1-fieldtype': ['heading1'], 'form-2-procid': ['25'], 'form-2-name': ['a'], 'form-2-default': ['v'], 'form-2-sortorder': ['1000'], 'form-2-fieldtype': ['heading1'], 'form-2-DELETE': ['on']}>>
Form is valid
instances:[]
Deleted forms:
{'name': 'a', 'default': 'v', 'sortorder': 1000, 'fieldtype': 'heading1', 'procid': <SectionHeading: a [25]>, 'DELETE': True}
You actually need to delete the instances: Loop through the formsets' deleted_objects property after you called saved(commit=False) and delete them.

data did'nt validate error django

Can anyone please help me..... I keep on getting "data didn't validate" error when saving data from a ModelForm. Everything worked fine for me until I added some CSS and JS for the frontend, used form widgets and manually displayed the form field on the template.
Here are the codes:
forms.py
from django import forms
from .models import List_of_Res
class fordtp(forms.Form):
month_choices=(
('JAN','January'),
('FEB','February'),
('MAR','March'),
('APR','April'),
('MAY','May'),
('JUN','June'),
('JUL','July'),
('AUG','August'),
('SEP','September'),
('NOV','November'),
('DEC','December'),
)
day_choices=[]
for ddd in range(1,32):
day_toS=(str(ddd),str(ddd))
day_choices.append(day_toS)
year_choices=[]
for yyy in range(1990,2100):
year_toS=(str(yyy),str(yyy))
year_choices.append(year_toS)
month = forms.ChoiceField(choices = month_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'}))
year = forms.ChoiceField(choices = year_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'}))
day = forms.ChoiceField(choices = day_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'}))
class ResearchForm(forms.ModelForm):
class Meta:
model = List_of_Res
fields={
'prog_title',
'proj_title',
'stud_title',
'prog_lead',
'stud_lead',
'co_res',
'res_site',
'campus',
'category_res',
'classif_res',
'amt_granted',
'date_started',
'res_status',
'date_completed',
'res_SF',
'res_pubstat',
'res_JN',
'res_JV',
'date_pub',
'res_iprstat',
'apptype',
'date_appl',
'date_pprv',
'app_pending',
'res_abs'
}
widgets = {
'prog_title': forms.TextInput(attrs={'class':'form-control'}),
'proj_title': forms.TextInput(attrs={'class':'form-control'}),
'stud_title': forms.TextInput(attrs={'class':'form-control'}),
'prog_lead': forms.TextInput(attrs={'class':'form-control'}),
'stud_lead': forms.TextInput(attrs={'class':'form-control'}),
'co_res': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter 1 name per line'}),
'res_site': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter 1 site per line'}),
'campus': forms.Select(attrs={'class':'form-control'}),
'category_res': forms.RadioSelect(attrs={'class':'form-check-input'}),
'classif_res': forms.Select(attrs={'class':'form-control'}),
'amt_granted': forms.TextInput(attrs={'class':'form-control'}),
'date_started': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}),
'res_status': forms.RadioSelect(attrs={'class':'form-check-input'}),
'date_completed': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}),
'res_SF': forms.CheckboxSelectMultiple(attrs={'class':'form-check-input'}),
'res_pubstat': forms.RadioSelect(attrs={'class':'form-check-input'}),
'res_JN': forms.TextInput(attrs={'class':'form-control'}),
'res_JV': forms.TextInput(attrs={'class':'form-control'}),
'date_pub': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}),
'res_iprstat':forms.RadioSelect(attrs={'class':'form-check-input'}),
'apptype':forms.RadioSelect(attrs={'class':'form-check-input'}),
'date_appl':forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}),
'date_pprv':forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}),
'app_pending': forms.RadioSelect(attrs={'class':'form-check-input'}),
'res_abs': forms.Textarea(attrs={'class':'form-control'})
}
(views.py):
from django.shortcuts import render
from django.http import HttpResponse
from .forms import ResearchForm
from .models import List_of_Res
def RIS_Home(request):
return render(request,'RIS/RIS_Home.html')
def Add_Res(request):
if request.method=='POST':
form = ResearchForm(request.POST)
if form.is_valid():
resAdd=form.save(commit=False)
resAdd.save()
else:
form = ResearchForm()
args = {'form':form}
return render(request,'RIS/RIS_Add-Edit.html',args)
(models.py)
from django.db import models
class List_of_Res(models.Model):
Yes_no_Choices = (('YES','YES'),('NO','NO'))
Stat_choices = (("COMPLETED","Completed"),("ON_GOING","On-Going"))
Campus_choices = (
("APARRI","Aparri"),
("LASAM","Lasam"),
("LALLO","Lal-lo"),
("SANCHEZ_MIRA","Sanchez Mira"),
("CARIG","Carig"),
("ANDREWS","Andrews"),
("PIAT","Piat")
)
Category_choices = (
("BASIC","Basic"),
("APPLIED","Applied"),
("PILOT_TESTING","Pilot Testing"),
("TECHNOLOGY_PROMOTION_COMMERCIALIZATION","Technology Promotion / Commercialization")
)
Classification_choices = (
("AGRICULTURE","Agriculture"),
("BIOTECHNOLOGY","Biotechnology"),
("ICT","ICT"),
("HEALTH_PRODUCTS","Health Products"),
("ALTERNATIVE_ENERGY","Alternative Energy"),
("CLIMATE_CHANGE","Climate Change"),
("ENVIRONMENT","Environment"),
("SOCIO_ECONOMIC","Socio-economic"),
("NATURAL_PRODUCTS","Natural Products"),
("OTHER","Other")
)
Source_fund_choices = (
("CSU","CSU"),
("CHED","CHED"),
("DA_BAR","DA-BAR"),
("DOST","DOST"),
("PCCARRD","PCCARRD"),
("PCIERD","PCIERD"),
("PCHRD","PCHRD"),
("DA","DA"),
("OTHER","Other")
)
IPR_Type_choices = (
("PATENT","Patent"),
("UTILITY_MODEL","Utility Model"),
("TRADEMARK_TRADENAME","Trademark/Tradename"),
("COPYRIGHT","Copyright"),
("OTHER","Other")
)
prog_title = models.CharField(max_length=1000)
proj_title = models.CharField(max_length=1000)
stud_title = models.CharField(max_length=1000)
prog_lead = models.CharField(max_length=300)
stud_lead = models.CharField(max_length=300)
co_res = models.TextField()
res_site = models.TextField()
campus = models.CharField(max_length=50,choices=Campus_choices,default='ANDREWS')
category_res = models.CharField(max_length=50,choices=Category_choices,default='BASIC')
classif_res = models.CharField(max_length=50,choices=Classification_choices,default='ICT')
amt_granted = models.TextField()
date_started = models.TextField()
res_status = models.CharField(max_length=10, choices=Stat_choices, default='COMPLETED')
date_completed = models.TextField()
res_SF = models.TextField(choices=Source_fund_choices,default='CSU')
res_pubstat = models.CharField(max_length=5,choices=Yes_no_Choices, default='YES')
res_JN = models.TextField()
res_JV = models.CharField(max_length=100)
date_pub = models.TextField()
res_iprstat = models.CharField(max_length=10, choices=Yes_no_Choices, default='YES')
apptype = models.CharField(max_length=100,choices=IPR_Type_choices,default='PATENT')
date_appl = models.TextField()
date_pprv = models.TextField()
app_pending = models.CharField(max_length=10, choices=Yes_no_Choices, default='YES')
res_abs = models.CharField(max_length=1000)
end this is the html template
{% extends 'RIS/RIS_Home.html' %}
{% block body %}
<div class="container">
<form method="post">
<div>
{% csrf_token %}
<div>
<div class="row"><div class="boxed_content">Title of Research</div></div>
<br>
<div class="row">
<label class="label_style_AEform">Program Title</label>
<br>
{{ form.prog_title }}
</div>
<div class="row">
<label class="label_style_AEform">Project Title</label>
<br>
{{ form.proj_title }}
</div>
<div class="row">
<label class="label_style_AEform">Study Title</label>
<br>
{{ form.stud_title }}
</div>
</div>
<br>
<div>
<br>
<div class="row"><div class="boxed_content">Researcher/s</div></div>
<br>
<div class="row">
<div class="col">
<div class="row">
<label class="label_style_AEform">Program Leader</label>
<br>
{{ form.prog_lead }}
</div>
<br><br><br>
<div class="row">
<label class="label_style_AEform">Study Leader</label>
<br>
{{ form.stud_lead }}
</div>
</div>
<div class="col">
<label class="label_style_AEform">Co-Researcher/s</label>
<br>
{{ form.co_res }}
</div>
</div>
</div>
<div>
<br>
<div class="row"><div class="boxed_content">Site / Location of study</div></div>
<br>
<div class="row">
{{ form.res_site }}
</div>
</div>
<div>
<br>
<div class="row"><div class="boxed_content">Category of Research</div></div>
{% for rdo in form.category_res %}
<div class="form-check form-check-inline">
{{ rdo }}
</div>
{% endfor %}
</div>
<br>
<div>
<div class="row">
<div class="col">
<div class="row"><div class="boxed_content">Classification of Research<br>
{{ form.classif_res }}
</div></div>
</div>
<div class="col">
<div class="row"><div class="boxed_content">Campus<br>
{{ form.campus }}
</div></div>
</div>
</div>
</div>
<br>
<div>
<div class="row">
<div class="col">
<div class="row"><div class="boxed_content">Source of Fund</div></div>
{% for chk in form.res_SF %}
<div class="form-check form-check-inline">
{{ chk }}
</div>
{% endfor %}
</div>
<div>
<div class="col">
<div class="row"><div class="boxed_content">Amount Granted<br>{{ form.amt_granted }}</div></div>
</div>
</div>
</div>
</div>
<br>
<div>
<div class="row">
<div class="col">
<div class="row"><div class="boxed_content">Status of Research</div></div>
{% for rdo in form.res_status %}
<div class="form-check form-check-inline">
{{ rdo }}
</div>
{% endfor %}
</div>
<div class="col">
<div class="row"><div class="boxed_content">Date Started<br>
<div class="form-check form-check-inline">
{{ form.date_started }}
</div>
</div></div>
</div>
<div class="col">
<div class="row"><div class="boxed_content">Date Completed<br>
<div class="form-check form-check-inline">
{{ form.date_completed }}
</div>
</div></div>
</div>
</div>
</div>
<br>
<div class="row">
<div class="boxed_content">Is the research published?
{% for rdo in form.res_pubstat %}
<div class="form-check form-check-inline">
{{ rdo }}
</div>
{% endfor %}
</div>
<br>
<div class="row">
<div class="col">
<label class="label_style_AEform">If Yes,</label>
</div>
<div class="col">
<label class="label_style_AEform">Name of Journal</label>
{{ form.res_JN }}
</div>
<div class="col">
<label class="label_style_AEform">Volume</label>
{{ form.res_JV }}
</div>
<div class="col">
<label class="label_style_AEform">Date Published</label>
<div class="form-check form-check-inline">
{{ form.date_pub }}
</div>
</div>
</div>
</div>
<br>
<div class="row">
<div class="boxed_content">Does the research have IPR application?
{% for rdo in form.res_iprstat %}
<div class="form-check form-check-inline">
{{ rdo }}
</div>
{% endfor %}
</div>
<br>
<div class="row">
<div class="col">
<label class="label_style_AEform">If Yes, Application Type: </label>
{% for rdo in form.apptype %}
<div class="form-check form-check-inline">
{{ rdo }}
</div>
{% endfor %}
</div>
</div>
<div class="row">
<div class="col">
<label class="label_style_AEform">Date of Application</label>
<div class="form-check form-check-inline">
{{ form.date_appl }}
</div>
</div>
<div class="col">
<label class="label_style_AEform">Date of Approval of application</label>
<div class="form-check form-check-inline">
{{ form.date_pprv }}
</div>
</div>
<br>
<div class="col">
<label class="label_style_AEform">Is the application Pending? </label>
{% for rdo in form.app_pending %}
<div class="form-check">
{{ rdo }}
</div>
{% endfor %}
</div>
</div>
</div>
<div class="row">
<div class="boxed_content">Abstract of the study</div>
<br>
{{ form.res_abs }}
</div>
</div>
<div class="row"><button type="submit" class="btn btn-primary mb-2">SAVE</button></div>
</form>
</div>
{% endblock %}
You should use MultipleChoiceField in your forms as a widget.
'res_SF': forms.MultipleChoiceField(attrs={'class':'form-check-input'}),

Categories