Django RadioSelect field not rendering correctly - django

I'm using Django FilterSet to enable the user to filter a list of products on my website. Everything is working perfectly, I'm using standard html code to display a form. However there is a RadioSelect field that is not rendering correclty and I don't understand why. I provide you below the relevant parts of my code as well as a screenshot of the rendering problem. Does anyone know how I can solve that ?
filters.py
class PlatFilter(django_filters.FilterSet):
titre = django_filters.CharFilter(
field_name='titre', label='Mot clé :', lookup_expr='icontains',
widget=forms.TextInput(attrs={'class': 'form-control'}),
)
prix_min = django_filters.NumberFilter(
field_name='prix', label='Prix minimum :', lookup_expr='gte',
widget=forms.NumberInput(attrs={'class': 'form-control'}),
)
prix_max = django_filters.NumberFilter(
field_name='prix', label='Prix maximum :', lookup_expr='lte',
widget=forms.NumberInput(attrs={'class': 'form-control'}),
)
nb_portions = django_filters.NumberFilter(
field_name='nb_portions', label='Nombre de portions minimum :', lookup_expr='gte',
widget=forms.NumberInput(attrs={'class': 'form-control'}),
)
date_prep = django_filters.DateFilter(
field_name='date_prep__date', label='Date de préparation (format JJ/MM/AAAA)', lookup_expr='exact',
widget=forms.DateTimeInput(attrs={'class': 'form-control'}),
)
CHOICES = ((True, 'Oui'), (False, 'Non'))
is_delivering = django_filters.BooleanFilter(
field_name='chef__is_delivering', label='Livraison comprise',
widget=forms.RadioSelect(attrs={'class': 'form-control'}, choices=CHOICES),
)
class Meta:
model = Plat
fields = ['titre', 'nb_portions', 'date_prep']
html file (using Bootstrap)
<div class="col-md-3">
<div class="filters shadow-sm rounded bg-white mb-4">
<div class="filters-header border-bottom pl-4 pr-4 pt-3 pb-3">
<h5 class="m-0" style="font-size: 200%">Filtrer par</h5>
</div>
<div class="filters-body">
<form method="get">
<div class="well">
<div class="row">
<div class="col-md-12 pl-5 pb-4 pt-4 pr-5">
{% csrf_token %}
{% for field in filter.form %}
<div class="fieldWrapper form-group" style="font-size: 150%">
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span> Rechercher
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
Screenshot of the problem :

Related

Getting the error: This field is required when update user

I'm trying to update a user profile using two forms the problem is that when I click to update I get the following error:
“<ul class="errorlist">
<li>username<ul class="errorlist"><li>This field is required.</li>
</ul>
”
My model module is the following:
# user.models
from django.contrib.auth.models import AbstractUser
from django.db import models
from model_utils.models import TimeStampedModel
from localflavor.br.models import BRPostalCodeField, BRStateField, BRCNPJField, BRCPFField
class User(AbstractUser):
class Roles(models.IntegerChoices):
SUPER = 0
COMPANY = 1
UNITY = 2
STAFF = 3
picture = models.ImageField(blank=True, null=True)
role = models.IntegerField(choices=Roles.choices, default=Roles.STAFF)
class Staff(TimeStampedModel):
user: User = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
unity = models.ForeignKey(Unity, related_name="staff", on_delete=models.CASCADE)
cpf = BRCPFField("CPF")
class Meta:
verbose_name: str = 'Staff'
verbose_name_plural: str = 'Staff'
ordering = ("-created",)
def __str__(self):
if f"{self.user.first_name} {self.user.last_name}".strip():
return f"{self.user.first_name} {self.user.last_name}"
return str(self.user.username)
And my user forms looks like:
#user.forms
class UserModelForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'is_active']
class StaffModelForm(forms.ModelForm):
class Meta:
model = Staff
fields = ['cpf', 'unity']
widget = {
'cpf': forms.TextInput(attrs={'class': "form-control", 'placeholder': 'Primeiro Nome', }),
'unity': forms.EmailInput(attrs={'class': "form-control", 'placeholder': 'meu#email.com', }),
}
with the following view:
#views
…
def update_staff(request: HttpRequest, pk: int) -> HttpResponse:
instance: Staff = get_object_or_404(Staff, pk=pk) # get staff instance
template_name = 'pages/staff_update_form.html' # use this template
if request.method == "POST":
profile_form = user_forms.StaffModelForm(request.POST, instance=instance)
user_form = user_forms.UserModelForm(request.POST, request.FILES, instance=instance.user)
print(user_form.is_valid())
print(user_form.errors)
print(profile_form.is_valid())
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, 'Your profile is updated successfully')
return redirect(to='pages:dashboard')
context = dict(profile_form=user_forms.StaffModelForm(instance=instance),
user_form=user_forms.UserModelForm(instance=instance.user))
return render(request, template_name=template_name, context=context)
Print output:
False
<ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul
></li></ul>
True
and HTML:
{% load crispy_forms_tags %}
{% if user_form.errors %}
<div class="alert alert-danger alert-dismissible" role="alert">
<div id="form_errors">
{% for key, value in user_form.errors.items %}
<strong>{{ value }}</strong>
{% endfor %}
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
<div class="py-5 text-center">
<span class="material-icons" style="height: 48px; width: auto; font-size: 48px;">people_alt</span>
<h1 class="h3 mb-3 fw-normal">Atualize aqui os dados do usuário!</h1>
</div>
<form class="form-signin" method="POST" enctype="multipart/form-data">
<div class="form-group">
<div class="row g-8 my-auto mx-auto" style="padding-left: 12%; padding-right: 12%;">
<div class="col-md-8 col-lg-12">
{% crispy profile_form %}
</div>
</div>
<div class="row g-8 my-auto mx-auto" style="padding-left: 12%; padding-right: 12%;">
<div class="col-md-8 col-lg-12">
{% crispy user_form %}
</div>
</div>
<div class="col-md-12 col-lg-12">
<br>
<div class="modal-footer">
Cancel
<button class="btn btn-primary mb-2" type="submit">Update</button>
</div>
</div>
</div>
</form>
<div class="py-5 text-center">
<p class="mt-5 mb-3 text-muted">© 2022-2023</p>
</div>
So I have no idea what the source of this problem is. Everything seems fine to me, can anyone help me?

|as_crispy_field got passed an invalid or inexistent field while passing context from my django form

Help!!! I'm lost on this error: while trying to submit this form and pass it content as a context:
I see that the indentation of my view is correct as well as the definitions of my form
View
def costm_questions(request):
if request.method == 'POST':
form = labor_questions(request.POST)
if form.is_valid():
cost_dict= dict()
cost_dict['Union_PWR']= form.cleaned_data['Union_PWR']
cost_dict['UnionLabor_area']= form.cleaned_data['UnionLabor_area']
cost_dict['After_Hours_Req']= form.cleaned_data['After_Hours_Req']
cost_dict['infectious_control_Req']=form.cleaned_data['infectious_control_Req']
cost_dict['No_Core_Drills']= form.cleaned_data['No_Core_Drills']
cost_dict['Armored_fiber_req']= form.cleaned_data['Armored_fiber_req']
cost_dict['cost_dict']= cost_dict
context = {
'cost_dict': cost_dict,
}
return render(request, 'building_form.html', context)
else:
form = labor_questions()`enter code here`
return render(request, 'cost_questions_form.html', {'form': form})
Forms
class labor_questions(forms.Form):
BOOL_CHOICES = ((True, 'Yes'), (False, 'No'))
LABOR_AREA_CHOICES= ((1, '1) Chicago'), (2 ,'2) Manhattan'), (3 ,'3) NYC Metro'), (4 ,'4) Los
Angeles'),
(4 ,'5) San Francisco'), (5 ,'6) Philadelphia'), (5 ,'6) Other'))
AFTER_HOURS_CHOICES= ((1, '1) No'), (2, '2) Yes, Mon-Fri'), (3,'3) Yes, weekends only'))
Union_PWR = forms.ChoiceField(choices = BOOL_CHOICES, label="Is Union Labor or Prevailing Wage Required?",
initial='', widget=forms.Select(), required=True) #Is Union Labor or Prevailing Wage Required?
UnionLabor_area= forms.ChoiceField(choices = LABOR_AREA_CHOICES, label="if yes please choose union area",
initial='', widget=forms.Select(), required=True)
After_Hours_Req= forms.ChoiceField(choices = AFTER_HOURS_CHOICES, label="Is after-hours work required?",
initial='', widget=forms.Select(), required=True)
infectious_control_Req= forms.ChoiceField(choices = BOOL_CHOICES, label="Is tenting required for infectious control?",
initial='', widget=forms.Select(), required=True)
No_Core_Drills = forms.IntegerField(label='How many core drills will be required?', required=True)
Armored_fiber_req= forms.ChoiceField(choices = BOOL_CHOICES, label="Is armored fiber cabling required?",
initial='', widget=forms.Select(), required=True)
My html code is calling for crispy but I see the format are correct
html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %}Cost Questions form{% endblock %}
{% block body %}
<br>
<div class="container">
<form method="POST" action = {% url 'cost_info' %}>
{% csrf_token %}
{{ form.non_field_errors }}
<div class="container">
<div>
<div class="card w-100">
<div class="card-header"><h6>Project Cost Questions</h6></div>
<div class="card-body">
<div class="row">
<div class="col">{{ form.Union_PWR|as_crispy_field }}</div>
<div class="col">{{ form.UnionLabor_area|as_crispy_field }}</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col">{{form.After_Hours_Req|as_crispy_field}}</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col">{{form.infectious_control_Req|as_crispy_field}}</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col">{{form.No_Core_Drills|as_crispy_field}}</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col">{{form.Armored_fiber_req|as_crispy_field}}</div>
</div>
</div>
</div>
</div>
</div>
<button type="submit" name="CostInfo" class="btn btn-secondary">Submit</button>
<br/>
</div>
</form>
</div>
{% endblock %}
trace back
first check your model's fields
then your view, that you bring essential fields into 'fields tags'
class ArticleCreate(CreateView):
model = Article
fields = ['title', 'slug', .....]

Issue with CreateView ,object not created in model on submit

I have issue might missed something , i have created CreateView view for submitting objects in db , all seems to ok , but when i try to submit i don't get anything happen no error at all except
"POST /create_task/ HTTP/1.1" 200 12972 ,
MY code goes as follows , please advice
Thanks
models.py
class MainTask(models.Model):
task_title = models.CharField(max_length=200)
global_task_info = models.TextField(max_length=500,default=None)
complete = models.BooleanField(default=False)
overall_precent_complete = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(default=datetime.datetime.now())
updated_at = models.DateTimeField(default=datetime.datetime.now())
due_date = models.DateTimeField(default=datetime.datetime.now())
task_location = models.CharField(max_length=400, blank=True, null=True)
global_task_assign = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="global_task_assign",default=1)
TASK_STATUS_CHOICES = [
('ST', 'STARTED'),
('NS', 'NOT STARTED'),
('IP', 'IN PROGRESS'),
('PA', 'PAUSED'),
('CO', 'COMPLETED'),
]
task_status = models.CharField(max_length=2,choices=TASK_STATUS_CHOICES,default='NOT STARTED')
def __str__(self):
return self.task_title
forms.py
class TaskCraetionForm(forms.ModelForm):
TASK_STATUS_CHOICES = [
('ST', 'STARTED'),
('NS', 'NOT STARTED'),
('IP', 'IN PROGRESS'),
('PA', 'PAUSED'),
('CO', 'COMPLETED'),
]
task_title = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Task Title'}))
global_task_info = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Task Description'}))
due_date = forms.DateTimeField(widget=forms.DateTimeInput(attrs={
'class': 'form-control',
'id': 'picker'
}))
global_task_assign = forms.ModelChoiceField(queryset= UserProfile.objects.all(), widget=forms.Select(attrs={'class':'form-control'} ))
task_status = forms.ChoiceField(label='', choices=TASK_STATUS_CHOICES, widget=forms.Select(attrs={'class':'form-control'}))
class Meta:
model = MainTask
fields = ['task_title',
'global_task_info',
'due_date',
'global_task_assign',
'task_status',
]
views.py
class CreatTaskView(CreateView):
model = MainTask
template_name = "create_newtask.html"
form_class = TaskCraetionForm
success_url = None
def form_valid(self, form):
f = form.save(commit=False)
f.save()
return super(CreatTaskView, self).form_valid(form)
Thank you very much Alasdair you're comment gave me the direction and more added the following to my HTML template shown below and found out i have issue with my datetime picker format needed to added the following
Thanks
INPUTֹTIMEֹFORMATS = [
'%Y/%m/%d %H:%M']
due_date = forms.DateTimeField(input_formats=INPUTֹTIMEֹFORMATS, widget=forms.DateTimeInput(attrs={
'class': 'form-control',
'id': 'picker'
}))
html temaplate
<form action="" method="POST">
<h3 class="mt-3 text-left">Create New Task</h3>
<hr>
<p class="text-muted text-left">Creat New Itom task</p>
{% csrf_token %}
{% if form.errors %}
<!-- Error messaging -->
<div id="errors">
<div class="inner">
<p>There were some errors in the information you entered. Please correct the following:</p>
<ul>
{% for field in form %}
{% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
{% endfor %}
</ul>
</div>
</div>
<!-- /Error messaging -->
{% endif %}
<div class="input-group mt-3 mb-3 mr-auto">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i class="fas fa-book-medical"></i></span>
</div>
{{ form.task_title}}
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-pen"></i></span>
</div>
{{form.global_task_info}}
</div>
<!---date time picker-->
<h6 class="text-left">Task Due Date</h6>
<div class="input-group date mb-3 col-3">
<div class="input-group-append">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
{{ form.due_date }}
</div>
<!--end of date time picker-->
<!---user assign-->
<h6 class="text-left">Assign Task to IT member</h6>
<div class="input-group mb-3 mt-3 col-8">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-user-tie"></i></div>
{{form.global_task_assign}}
</div>
</div>
<!--End Of User Assign-->
<h6 class="text-left">Set Task Status</h6>
<div class="input-group mb-3 mt-3 col-4">
<div class="input-group-prepend">
<div class="input-group-text"><i class="far fa-caret-square-right"></i></div>
</div>
{{form.task_status}}
</div>
<div class="col text-left">
<button type="submit" value="Save" class="btn btn-primary btn-lg text-white mt-2"><span><i class="fas fa-database"></i></span> Create Task</button>
</div>
</form>
</div>
</div>

How to count objects in django

Thank you all for always sharing your knowledge here.
I have an issue with counting an object in Django. I am currently learning and working on a basic HR system and already have my views, models, et al set up. I plan to have an interface whereby I can print out employees count based on gender. The one I currently have set up is increasing the counts for both male and female any time I create a new employee. Please how do I correct this anomaly?
views.py
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render
from django_tables2 import RequestConfig
from django_tables2.export import TableExport
from .models import Employee
from .models import EmployeeFilter
from .tables import EmployeeTable
#login_required()
def employees(request):
filter = EmployeeFilter(request.GET, queryset=Employee.objects.all())
table = EmployeeTable(filter.qs)
RequestConfig(request, paginate={"per_page": 15}).configure(table)
count = Employee.objects.all().count()
male_count = Employee.objects.filter(gender__contains='Male').count()
female_count = Employee.objects.filter(gender__contains='Female').count()
user_count = User.objects.all().count()
export_format = request.GET.get("_export", None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, table)
return exporter.response("table.{}".format("csv", "xlsx"))
return render(request, "employees/employees.html", {
"table": table,
"filter": filter,
"count": count,
"male_count": male_count,
"female_count": female_count,
"user_count": user_count,
})
template.html
{% extends "employees/base.html" %}
{% load render_table from django_tables2 %}
{% load django_tables2 %}
{% load querystring from django_tables2 %}
{% block content %}
<!--Data overview-->
<div class="container data overview">
<div class="row">
<div class="col-md-3">
<div class="container-fluid bg-warning data-ov-container">
<div class="row">
<div class="col-8">
<h6 class="data-heading font-weight-bold">Total Employees</h6>
<p class="data-text ">{{ count }}</p>
</div>
<div class="col-4">
<i class="fas fa-users data-icon"></i>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container-fluid bg-dark data-ov-container">
<div class="row">
<div class="col-9">
<h6 class="data-heading text-white font-weight-bold">Male Employees</h6>
<p class="data-text text-white">{{ male_count }}</p>
</div>
<div class="col-3">
<i class="fas fa-male data-icon text-white"></i>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container-fluid bg-danger data-ov-container">
<div class="row">
<div class="col-9">
<h6 class="data-heading text-white font-weight-bold">Female Employees</h6>
<p class="data-text text-white">{{ female_count }}</p>
</div>
<div class="col-3">
<i class="fas fa-female data-icon text-white"></i>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container-fluid bg-secondary data-ov-container">
<div class="row">
<div class="col-8">
<h6 class="data-heading text-white font-weight-bold">Active Users</h6>
<p class="data-text text-white">{{ user_count }}</p>
</div>
<div class="col-4">
<i class="fas fa-users-cog data-icon text-white"></i>
</div>
</div>
</div>
</div>
</div>
</div>
<!--Employees data-->
<div class="filter-container container-fluid">
<div class="row">
<div class="col-md-9">
<!--filter form-->
<form action="" class="form form-inline employee-filter-form" method="get">
<legend class="mb-2">Filter employee records</legend>
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ filter.form.first_name.errors }}
{{ filter.form.first_name }}
</div>
<div class="fieldWrapper">
{{ filter.form.last_name.errors }}
{{ filter.form.last_name }}
</div>
<button aria-expanded="false" aria-haspopup="true"
class="ml-2 btn btn-danger filter-btn" type="submit">
Filter
</button>
</form>
</div>
<div class="col-md-3 download-btn-col">
<button aria-expanded="false" aria-haspopup="true"
class="mr-3 btn btn-success" type="submit">
<i class="fas fa-upload"></i> Import
</button>
<div class="btn-group download-btn">
<button aria-expanded="false" aria-haspopup="true"
class="btn btn-warning dropdown-toggle"
data-toggle="dropdown" type="button">
<i class="fas fa-file-export"></i> Export
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="{% querystring '_export'='csv' %}">csv</a>
<a class="dropdown-item" href="{% querystring '_export'='xlsx' %}">xlsx</a>
</div>
</div>
</div>
</div>
</div>
<!-- data rendered here -->
{% render_table table 'django_tables2/bootstrap.html' %}
<!-- data rendered here -->
{% endblock content %}
models.py
...
GENDER_CHOICES = (
('FEMALE', 'Female'),
('MALE', 'Male'),
("DWTS" "Don't want to say"),
)
...
#python_2_unicode_compatible
class Employee(models.Model):
# basic information of employee
first_name = models.CharField(_('first name'), max_length=40)
last_name = models.CharField(_('last name'), max_length=40)
emp_photo = models.ImageField(_('passport'))
date_of_birth = models.DateField(_('birthday'))
gender = models.CharField(_('gender'), max_length=15, choices=GENDER_CHOICES, default=['MALE', 'Male'])
house_address = models.CharField(_('house address'), max_length=100)
city_of_residence = models.CharField(_('city'), max_length=100)
state_of_residence = models.CharField(_('state'), max_length=100, choices=NIGERIAN_STATE_CHOICES)
country_of_residence = models.CharField(_('country'), max_length=100, choices=COUNTRY_CHOICES,
default=[156, 'Nigeria'])
state_of_origin = models.CharField(_('state of origin'), max_length=100, choices=NIGERIAN_STATE_CHOICES)
class Meta:
verbose_name = _('Employee')
verbose_name_plural = _('Employees')
def __str__(self):
return "{} {}".format(self.first_name, self.last_name)
#python_2_unicode_compatible
class EmployeeFilter(django_filters.FilterSet):
first_name = django_filters.CharFilter(lookup_expr='iexact', widget=TextInput(
attrs={'placeholder': 'First name', 'class': 'input_search'}))
last_name = django_filters.CharFilter(lookup_expr='iexact',
widget=TextInput(attrs={'placeholder': 'Last name', 'class': 'input_search'}))
class Meta:
model = Employee
fields = ["first_name", "last_name", ]
I think you need to remove contains from your filter:
male_count = Employee.objects.filter(gender='Male').count()
female_count = Employee.objects.filter(gender='Female').count()
Or make a single request:
male_femail_count = Employee.objects.values('gender').annotate(count=Count('id'))
# result
# [{'gender': 'Male', 'count': 2}, {'gender': 'Female', 'count': 3}]

Change a field on change another field using django-autocomplete-light

Basically I want to change value of company id and company name if your company field is changed.
Here I have used django-autocomplete-light for your company field. Code for this form:
class PartnerAddForm(forms.ModelForm):
company_id = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'disabled': ''}), required=False)
company_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'disabled': ''}), required=False)
class Meta:
model = CompanyCompanyMap
fields = ('your_company',)
widgets = {
'your_company': autocomplete.ModelSelect2(url='url_company_autocomplete',
attrs={'class': 'form-control',
'data-placeholder': 'Type for getting available companies'})
}
Code for autocomplete view of your company field:
class CompanyAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = CompanyAccess(self.request).get_non_partners()
if self.q:
qs = qs.filter(company_name__istartswith=self.q)
return qs
And code for template of this form
<form class="form-horizontal" role="form" action="." method="POST">
{% csrf_token %}
{% for f in form %}
<div class="form-group">
<label for="id_{{ f.name }}" class="col-sm-2 control-label">{{ f.label|capfirst }}</label>
<div class="col-sm-7">
{{ f }}
</div>
</div>
{% endfor %}
<div class="form-group">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-7">
<button type="submit" class="btn btn-default btn-primary">
Add Company as Friend
</button>
</div>
</div>
<!-- /.table-responsive -->
</form>
Is there any way to change it using js or other mechanism?