Django form field required on condition - django

I have a Django model form where i want to make a form field required if some value is selected in another form field.
e.g
if activity_name = 'Project Planned Activities' is selected in activity_name form field the project_id field should be required = true
I have added a form validator for this but its not working
class ActivityTrackerModelForm(forms.ModelForm):
activity_name = forms.ModelChoiceField(
queryset=activity.objects.all().order_by('activity_name'),
label='',
empty_label="Select Activity",
widget=forms.Select(
attrs={
'class': 'form-control',
}
)
)
project_id = forms.CharField(
label='',
required=False,
widget=forms.TextInput(
attrs={
"placeholder": "Project ID",
'class': 'form-control'
}
)
)
class Meta:
model = activity_tracker
fields = ['activity_name', 'project_id']
def clean(self):
activity = self.cleaned_data.get('activity_name')
if re.search("^Project.*Activities$", str(activity)):
self.fields['project_id'].required = True
Tried using the form validator
if activity_name = 'Project Planned Activities' is selected in activity_name form field the project_id field should be required = true

Problem was first in my Validator itself and in my view. i was not passing the current form to the template instead i was passing the new form eveytime to my template.
Corerct Form Validator
class ActivityTrackerModelForm(forms.ModelForm):
date = forms.DateField(label='', widget=forms.DateInput(attrs={
"placeholder": "Select Date", 'id': 'datepicker', 'class': 'form-control w-100', 'autocomplete': 'off'}))
activity_name = forms.ModelChoiceField(queryset=activity.objects.all().order_by(
'activity_name'), label='', empty_label="Select Activity", widget=forms.Select(attrs={'class': 'form-control w-100'}))
system_name = forms.ModelChoiceField(queryset=system.objects.all().order_by('system_name'), label='', empty_label="Select System", widget=forms.Select(attrs={'class': 'form-control w-100'}))
client_name = forms.ModelChoiceField(queryset=client.objects.all().order_by(
'client_name'), label='', empty_label="Select Client", widget=forms.Select(attrs={'class': 'form-control w-100'}))
hour_choice = [('', 'Choose Hours'), (0, 0), (1, 1), (2, 2),(3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8)]
hours = forms.ChoiceField(label='', choices=hour_choice, widget=forms.Select(
attrs={'class': 'form-control w-100'}))
min_choice = [('', 'Choose Mins'), (0, 0), (15, 15), (30, 30), (45, 45)]
mins = forms.ChoiceField(label='', choices=min_choice, widget=forms.Select(attrs={'class': 'form-control w-100'}))
no_of_records = forms.IntegerField(label='', required=False, widget=forms.NumberInput(
attrs={"placeholder": "Enter no. of Records", 'class': 'form-control w-100', 'autocomplete': 'off'}))
project_id = forms.CharField(label='', required=False, widget=forms.TextInput(
attrs={"placeholder": "Project ID", 'class': 'form-control w-100'}))
user_comments = forms.CharField(
label='',
required=False,
widget=forms.Textarea(
attrs={
"placeholder": "Enter Your Comments Here...",
'rows': 6,
'class': 'form-control w-100',
'autocomplete': 'off'
}
)
)
class Meta:
model = activity_tracker
fields = ['date', 'activity_name', 'system_name', 'client_name',
'hours', 'mins', 'no_of_records', 'project_id', 'user_comments']
def clean(self):
cleaned_data = super(ActivityTrackerModelForm, self).clean()
activity = cleaned_data.get('activity_name')
project_1 = cleaned_data.get('project_id')
if re.search("^Project.*Activities$", str(activity)) and project_1 == "":
self.add_error('project_id', "Please Add Project ID")
return cleaned_data
Corrrect View
def MyTask(request):
form = ActivityTrackerModelForm(request.POST or None)
if request.method == 'POST':
form = ActivityTrackerModelForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.user_name = request.user
obj.approver = tascaty_user.objects.get(
username=request.user).approver
if request.user.is_team_lead:
obj.status = activity_status.objects.get(pk=3)
obj.save()
messages.success(request, 'New Entry Created')
return redirect('mytask')
queryset1_PA = activity_tracker.objects.filter(
user_name=request.user).filter(status__in=[1, 2, 4]).order_by('-id')
queryset1_AP = activity_tracker.objects.filter(
user_name=request.user).filter(status=3).order_by('-date')
paginator_RA = Paginator(queryset1_AP, 10)
paginator_PA = Paginator(queryset1_PA, 10)
page = request.GET.get('page')
context = {
'title': 'TasCaty|My Task',
'activity_form': form,
'post_page_RA': paginator_RA.get_page(page),
'post_page_PA': paginator_PA.get_page(page),
}
return render(request, "tascaty/mytask.html", context)

Related

Create view with more models

hi everyone I have a doubt with the use of forms and models.
I have to create a code that creates records in multiple tables and I don't know how to do it.
my goal is to create a page where I can enter all the data and when I save it creates the various tables filled in with the data provided by the user.
I'm a beginner I still have to learn the mechanism well =)
forms.py
from django import forms
from .models import Schede, DatiGruppi, Gruppi
class CreaSchedaForm(forms.ModelForm):
nome_scheda = forms.CharField(
required = True,
label ='Nome scheda',
widget = forms.TextInput(
attrs = {
'class': 'form-control',
'placeholder' : 'nome scheda',
'autocomplete' : 'off'
}
)
)
data_inizio = forms.DateField(
label='Data inizio',
widget = forms.DateInput(
attrs= {
'type': 'date',
'class': 'form-control',
'placeholder' : 'data inizio'
}
)
)
data_fine = forms.DateField(
label='Data fine',
widget = forms.DateInput(
attrs= {
'type': 'date',
'class': 'form-control',
'placeholder' : 'data fine'
}
)
)
class Meta:
model = Schede
fields = ['nome_scheda','data_inizio','data_fine']
class CreaDtGruppoForm(forms.ModelForm):
giorni_settimana = forms.ChoiceField(
choices = DatiGruppi.giorni_settimana_scelta
)
dati_gruppo = forms.ModelChoiceField(
queryset = Gruppi.objects.all(),
empty_label = "-",
required = True
)
class Meta:
model = DatiGruppi
fields = ['giorni_settimana', 'dati_gruppo']
views.py
#login_required
def creaScheda(request):
if request.method == "POST":
form = CreaSchedaForm(request.POST)
if form.is_valid():
scheda = form.save(commit = False)
scheda.utente = request.user
scheda.save()
else:
form = CreaSchedaForm()
context = {"form": form}
return render(request, "crea_scheda.html", context)

31/5000 how to insert a new user?

I am trying to create a new personalized user and when I click on the register button it does not register anything for me, below I show my code to help me solve this problem in advance thank you very much
This is the forms.py
class FormularioUsuario(forms.ModelForm):
password1=forms.CharField(label='Contraseña', widget=forms.PasswordInput(
attrs={
'class': 'form-control',
'placeholder':'Ingrese su Contraseña...',
'id': 'password1',
'required':'required',
}
))
password2=forms.CharField(label='Contraseña de Confirmacion', widget=forms.PasswordInput(
attrs={
'class': 'form-control',
'placeholder':'Ingrese nuevamente su Contraseña...',
'id': 'password2',
'required':'required',
}
))
class Meta:
model=Usuario
fields=('email', 'username', 'nombres', 'apellidos')
widgets ={
'email': forms.EmailInput(
attrs={
'class': 'form-control',
'placeholder': 'Correo Electronico',
}
),
'nombres': forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'Ingrese su nombre',
}
),
'apellidos': forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'Ingrese su Apellido',
}
),
'username': forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'Ingrese su Nombre de Usuario',
}
)
}
def clean_password2(self):
print(self.cleaned_data)
password1=self.cleaned_data.get('password1')
password2=self.cleaned_data.get('password2')
if password1 != password2:
raise forms.ValidationError('Contraseñas no coinciden')
return password2
def save(self, commit=True):
user=super().save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
This is the views.py
class RegistrarUsuario(CreateView):
model=Usuario
form_class=FormularioUsuario
template_name='usuario/crear_usuario.html'
success_url = reverse_lazy('usuario:listar_usuarios')
This is the models.py
class Usuario(AbstractBaseUser):
username = models.CharField('Nombre de usuario',unique = True, max_length=100)
email = models.EmailField('Correo Electrónico', max_length=254,unique = True)
nombres = models.CharField('Nombres', max_length=200, blank = True, null = True)
apellidos = models.CharField('Apellidos', max_length=200,blank = True, null = True)
imagen = models.ImageField('Imagen de Perfil', upload_to='perfil/', max_length=200,blank = True,null = True)
usuario_activo = models.BooleanField(default = True)
usuario_administrador = models.BooleanField(default = False)
objects = UsuarioManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','nombres']
def __str__(self):
return f'{self.nombres},{self.apellidos}'
def has_perm(self, perm,obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.usuario_administrador
This is the urls.py
app_name='usuario'
urlpatterns=[
#URL para el menu de inicio
path('', index),
path('usuario/index/',login_required(index), name='index'),
path('accounts/login/',Login.as_view(), name='login'),
path('logout/',login_required(logoutUsuario), name='logout'),
path('listado_usuarios/', login_required(ListadoUsuario.as_view()), name='listar_usuarios'),
path('registrar_usuario/', RegistrarUsuario.as_view(), name='registrar_usuario'),
]
if you need something else can you let me know please

Django raise forms.ValidationError not working

I am trying to add a validator to django model form such that if specific value is selected then other field in the form should be entered if not entered it should give a validation error
in the below form if the user selects "Project Support Activities" from the activity_name drop down then the project id field should be mandatory
Django Form
class ActivityTrackerModelForm(forms.ModelForm):
date = forms.DateField(label='', widget=forms.DateInput(attrs={
"placeholder": "Select Date", 'id': 'datepicker', 'class': 'form-control w-100', 'autocomplete': 'off'}))
activity_name = forms.ModelChoiceField(queryset=activity.objects.all().order_by(
'activity_name'), label='', empty_label="Select Activity", widget=forms.Select(attrs={'class': 'form-control w-100'}))
system_name = forms.ModelChoiceField(queryset=system.objects.all().order_by('system_name'), label='', empty_label="Select System", widget=forms.Select(attrs={
'class': 'form-control w-100'}))
client_name = forms.ModelChoiceField(queryset=client.objects.all().order_by(
'client_name'), label='', empty_label="Select Client", widget=forms.Select(attrs={
'class': 'form-control w-100'}))
hour_choice = [('', 'Choose Hours'), (0, 0), (1, 1), (2, 2),(3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8)]
hours = forms.ChoiceField(label='', choices=hour_choice, widget=forms.Select(
attrs={'class': 'form-control w-100'}))
min_choice = [('', 'Choose Mins'), (0, 0), (15, 15), (30, 30), (45, 45)]
mins = forms.ChoiceField(label='', choices=min_choice, widget=forms.Select(attrs={'class': 'form-control w-100'}))
no_of_records = forms.IntegerField(label='', required=False, widget=forms.NumberInput(
attrs={"placeholder": "Enter no. of Records", 'class': 'form-control w-100', 'autocomplete': 'off'}))
project_id = forms.CharField(label='', required=False, widget=forms.TextInput(
attrs={"placeholder": "Project ID", 'class': 'form-control w-100'}))
user_comments = forms.CharField(
label='',
required=False,
widget=forms.Textarea(
attrs={
"placeholder": "Enter Your Comments Here...",
'rows': 6,
'class': 'form-control w-100',
'autocomplete': 'off'
}
)
)
class Meta:
model = activity_tracker
fields = ['date', 'activity_name', 'system_name', 'client_name',
'hours', 'mins', 'no_of_records', 'project_id', 'user_comments']
def clean(self):
cleaned_data = super(ActivityTrackerModelForm, self).clean()
activity = cleaned_data.get('activity_name')
project_1 = cleaned_data.get('project_id')
if re.search("^Project.*Activities$", str(activity)) or project_1 is None:
print('pass') # prints to console this is working
raise forms.ValidationError('Please Add in Project ID')#raise form error this is not working
View :
def MyTask(request):
if request.method == 'POST':
form = ActivityTrackerModelForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
obj.user_name = request.user
obj.approver = tascaty_user.objects.get(
username=request.user).approver
if request.user.is_team_lead:
obj.status = activity_status.objects.get(pk=3)
obj.save()
return redirect('mytask')
queryset1_PA = activity_tracker.objects.filter(
user_name=request.user).filter(status__in=[1, 2, 4]).order_by('-id')
queryset1_AP = activity_tracker.objects.filter(
user_name=request.user).filter(status=3).order_by('-date')
paginator_RA = Paginator(queryset1_AP, 10)
paginator_PA = Paginator(queryset1_PA, 10)
page = request.GET.get('page')
context = {
'title': 'TasCaty|My Task',
'activity_form': ActivityTrackerModelForm(),
'post_page_RA': paginator_RA.get_page(page),
'post_page_PA': paginator_PA.get_page(page),
}
return render(request, "tascaty/mytask.html", context)
Raising the error is working fine. But you always redirect away, even if the form is not valid, so the error will never be displayed.
You should only redirect when is_valid is True, otherwise you should redisplay the form. That means passing the invalid form back to the context - so you should only create a new one when method is not POST. So:
if request.method == 'POST':
form = ActivityTrackerModelForm(request.POST or None)
if form.is_valid():
...
obj.save()
return redirect('mytask') # indented here
else:
ActivityTrackerModelForm() # added this block, note it's aligned with the first if
...
context = {
...
'activity_form': form, # pass the existing form here
...
}
return render(request, "tascaty/mytask.html", context)
Changed MY View as mentioned by #Daniel Roseman and changed form validator
View
if request.method == 'POST':
form = ActivityTrackerModelForm(request.POST or None)
if form.is_valid():
...
obj.save()
return redirect('mytask') # indented here
else:
ActivityTrackerModelForm() # added this block, note it's aligned with the first if
...
context = {
...
'activity_form': form, # pass the existing form here
...
}
return render(request, "tascaty/mytask.html", context)
Form Validator
def clean(self):
cleaned_data = super(ActivityTrackerModelForm, self).clean()
activity = cleaned_data.get('activity_name')
project_1 = cleaned_data.get('project_id')
if re.search("^Project.*Activities$", str(activity)) and project_1 == "":
self.add_error('project_id', "Please Add Project ID")
return cleaned_data

How to create a subform for Django ModelForm

I'm having a problem to add a ManyToMany field with ModelForm, the problem is that I don't know how to create a subform to add this data to my primary form. I want to create a subform to be saved when I click a button, and I want the data that was saved to be selected to use in the primary form.
my model
class Teste(models.Model):
name = models.CharField(max_length=255)
parent_institution_name = models.CharField(max_length=255)
laboratory_departament = models.CharField(max_length=255, null=True,
blank=True, verbose_name="Laboratório")
cep = models.CharField(max_length=255, verbose_name="Cep")
cnpj = models.CharField(max_length=255, verbose_name="CNPJ")
lat = models.FloatField(blank=True, null=True)
lng = models.FloatField(blank=True, null=True)
institution_name = models.CharField(max_length=255, null=False,
verbose_name="Nome da instituição")
parent_institution_name = models.CharField(max_length=255, blank=True,
null=True, verbose_name="Nome da instituição vinculada")
coordinator = models.CharField(max_length=255, verbose_name="Pessoa
Responsavel")
email = models.CharField(max_length=255, verbose_name="E-mail")
website = models.CharField(max_length=255, blank=True, null=True,
verbose_name="Website")
rad_operating_time = models.IntegerField(verbose_name="Tempo de atuação
")
research_line = models.ManyToManyField('researcher.ResearchLines')
my ModelForm
class TestForm(forms.ModelForm):
class Meta:
model = Test
exclude = ('employee_number', ' revenues', 'filter_grade', 'grade', '
knowledge_grade',
'application_grade', 'ie_grade', ' ia_grade', 'final_grade', 'inactive', 'last_coordinator_access', ' hr_count',
'hr_returned', ' match_hr_count', 'general_grade', 'lat', 'lng'
'tokens', 'iso_certification', 'other_certification', 'researchers', 'thematic_network',
)
widgets ={
'name':forms.TextInput(attrs={
'class':'form-control',
'placeholder': 'Nome da UBC'
}),
'parent_institution_name': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Nome da Instituição à qual a UBC é vinculada'
}),
'laboratory_departament': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Laboratório/Departamento'
}),
'cep': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'CEP'
}),
'cnpj': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'CNPJ'
}),
'institution_name': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Nome da instituição'
}),
'coordinator': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Pessoa Responsável'
}),
'email': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'E-mail'
}),
'website': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Website'
}),
'rad_operating_time': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Tempo de atuação em projetos de P&D+I'
}),
'phone': forms.TextInput(attrs={
'class':'form-control',
'placeholder': 'Telefone'
}),
'partner_category': forms.RadioSelect(),
'main_product':forms.CheckboxSelectMultiple( attrs={
'type':'checkbox'
}),
}
How my form looks, the last input shows where the subform goes to add data
Here is an example where I use inline formsets, which is in essence combining two forms into one displayed form. The formset is the service form, and the punches form where my intention is that the punches are the "form within the form".
VIEWS.PY (the most influential part)
def reportcreateview(request):
if request.method == 'POST':
reportform = ServiceReportCreateForm(request.POST)
if reportform.is_valid():
report = reportform.save(commit=False)
report.reported_by = request.user
punchesform = PunchesFormSet(request.POST, request.FILES, instance=report)
if punchesform.is_valid():
report.save()
punchesform.save()
return redirect('service:update-report', pk=report.pk)
else:
punchesform = PunchesFormSet()
reportform = ServiceReportCreateForm()
reportform.reported_by = request.user
context = {
'report': reportform,
'punches': punchesform,
}
return render(request, 'service/report-create.html', context)
FORMS.PY
from django import forms
from django.forms.models import inlineformset_factory, BaseInlineFormSet
from .models import ServiceReportModel, ReportPunchesModel, ServiceRequestModel
class ServiceReportCreateForm(forms.ModelForm):
class Meta:
model = ServiceReportModel
fields = [
'site',
'invoiced',
'paid',
'request_number',
'equipment',
'report_reason',
'actions_taken',
'recommendations',
]
widgets = {
'site': forms.Select(attrs={
'class': 'form-control',
'id': 'inputSite',
}),
'invoiced': forms.CheckboxInput(attrs={
'class': 'form-control',
}),
'paid': forms.CheckboxInput(attrs={
'class': 'form-control',
}),
'request_number': forms.Select(attrs={
'class': 'form-control',
'id': 'inputRequest',
}),
'equipment': forms.Select(attrs={
'class': 'form-control',
'id': 'inputEquipment',
}),
'report_reason': forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Reason for Service Report'}),
'actions_taken': forms.Textarea(attrs={
'class': 'form-control',
'placeholder': 'To the best of your abilities, list all actions taken during service. Please include'
'dates, times, and equipment names'}),
'recommendations': forms.Textarea(attrs={
'class': 'form-control',
'placeholder': 'If any recommendations were made to the customer that'
'require follow-up itemize them here...'}),
}
def __init__(self, *args, **kwargs):
super(ServiceReportCreateForm, self).__init__(*args, **kwargs)
self.fields['request_number'].required = False
class ServiceReportUpdateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ServiceReportUpdateForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.pk:
self.fields['request_number'].required = False
self.fields['report_reason'].widget.attrs['readonly'] = True
class Meta:
model = ServiceReportModel
fields = [
'invoiced',
'paid',
'request_number',
'updated_by',
'report_reason',
'actions_taken',
'recommendations',
]
widgets = {
'invoiced': forms.CheckboxInput(attrs={
'class': 'form-control',
}),
'paid': forms.CheckboxInput(attrs={
'class': 'form-control',
}),
'request_number': forms.Select(attrs={
'class': 'form-control',
'id': 'inputRequest',
}),
'updated_by': forms.Select(attrs={
'class': 'form-control',
'id': 'inputReporter',
}),
'report_reason': forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Reason for Service Report'}),
'actions_taken': forms.Textarea(attrs={
'class': 'form-control',
'placeholder': 'To the best of your abilities, list all actions taken during service. Please include' +
'dates, times, and equipment names'}),
'recommendations': forms.Textarea(attrs={
'class': 'form-control',
'placeholder': 'If any recommendations were made to the customer that'
'require follow-up itemize them here...'}),
}
PunchesFormSet = inlineformset_factory(
ServiceReportModel,
ReportPunchesModel,
fields=('date',
'time_in',
'time_out',
),
widgets={
'date': forms.DateInput(attrs={
'type': 'date'
}),
'time_in': forms.TimeInput(attrs={
'type': 'time'
}),
'time_out': forms.TimeInput(attrs={
'type': 'time'
})},
extra=1,
can_order=True
)
MODELS.PY
class ServiceReportModel(ServiceParent):
report_number = models.UUIDField(
primary_key=True, default=uuid.uuid4, editable=False)
invoiced = models.BooleanField(default=False, null=False)
paid = models.BooleanField(default=False, null=False)
request_number = models.ForeignKey(ServiceRequestModel,
on_delete=models.PROTECT,
null=True,
blank=True,
related_name='s_report_number'
)
reported_by = models.ForeignKey(
main_models.MyUser, related_name='reporter', on_delete=models.PROTECT)
reported_date = models.DateTimeField(auto_now_add=True)
report_reason = models.CharField(max_length=255, null=True)
actions_taken = models.TextField(null=False, blank=False)
recommendations = models.TextField(null=True, blank=True)
def get_absolute_url(self):
return reverse('service-report', kwargs={'pk': self.pk})
def __str__(self):
return '%s - %s, %s' % (self.site.company,
self.reported_date.strftime('%d %B %Y'),
self.equipment.name
)
class Meta:
ordering = ['reported_date', 'updated_date']
verbose_name = 'Service Report'
verbose_name_plural = 'Service Reports'
class ReportPunchesModel(models.Model):
punch_id = models.UUIDField(
primary_key=True, default=uuid.uuid4, editable=False)
added = models.DateTimeField(auto_now_add=True)
report = models.ForeignKey(ServiceReportModel, on_delete=models.CASCADE)
date = models.DateField(blank=True, null=True)
time_in = models.TimeField(blank=True, null=True)
time_out = models.TimeField(blank=True, null=True)
def __str__(self):
return '%s - %s' % (self.time_in,
self.time_out
)
class Meta:
ordering = ['added', 'date', 'time_in']
verbose_name = 'Report Punches'
verbose_name_plural = verbose_name
Jaberwocky Here is my code, I have to say sorry in advance for my code I still learning
class Ubc(models.Model):
""" Table Ubc """
name = models.CharField(verbose_name="Nome da instituição", max_length=255, null=False)
laboratory_departament = models.CharField(max_length=255, null=True, blank=True, verbose_name="Laboratório")
cep = models.CharField(max_length=255, verbose_name="Cep", null=True)
cnpj = models.CharField(max_length=255, verbose_name="CNPJ", null=True)
lat = models.FloatField(blank=True, null=True)
lng = models.FloatField(blank=True, null=True)
street = models.CharField(max_length=255, verbose_name="Endereco", null=True, blank=True)
uf = models.CharField(max_length=255, verbose_name="UF", null=True, blank=True)
city = models.CharField(max_length=255, verbose_name="City", null=True, blank=True)
parent_institution_name = models.CharField(verbose_name="Nome da instituição vinculada", max_length=255, blank=True, null=True)
coordinator = models.CharField(max_length=255, verbose_name="Pessoa Responsavel")
email = models.CharField(max_length=255, verbose_name="E-mail")
website = models.CharField(max_length=255, blank=True, null=True, verbose_name="Website")
rad_operating_time = models.IntegerField(verbose_name="Tempo de atuação em projetos de P&D+I")
phone = models.CharField(max_length=255, verbose_name="Telefone", null=True)
inactive = models.NullBooleanField(verbose_name="Inativo", default=False, null=True)
partner_category = models.ForeignKey('PartnerSubCategory', on_delete=models.CASCADE)
parent = models.ForeignKey('Company', blank=True, null=True, on_delete=models.CASCADE)
general_grade = models.ForeignKey('GeneralGrade', blank=True, null=True, on_delete=models.CASCADE)
main_product = models.ManyToManyField('MainProductUbc', verbose_name="Qual o tipo de produto e/ou servico que a UBC fornece (produto, processo, mudanca organizacional)")
tokens = models.ManyToManyField('ubc.Token', blank=True, related_name='tokens')
activity_branch = models.ForeignKey('ActivityBranch', verbose_name="Ramo de Atividade (CNAE)", null=True, on_delete=models.CASCADE)
researchers = models.ManyToManyField('researcher.Researcher', related_name='researchers', through='researcher.ResearcherUbc', blank=True)
research_line = models.ManyToManyField('researcher.ResearchLines',related_name='ubc_lines', blank=True)
class ResearchLines(models.Model):
title = models.CharField(verbose_name="Descrição da Linha de Pesquisa", max_length=255, blank=True, null=True)
ubc = models.ForeignKey('ubc.Ubc', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
updtaed = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'Research Line'
def __str__(self):
return self.title
views.py
def ubc_register(request):
if request.method == "POST":
form = UbcForm(request.POST or None)
if form.is_valid():
form = form.save(commit=False)
formset = LinesFormSet(request.POST, request.FILES, instance=form)
if formset.is_valid():
form.save()
formset.save()
return HttpResponseRedirect(reverse('index'))
else:
form = UbcForm(prefix="form")
formset = LinesFormSet(prefix="formset")
context = {
'form':form,
'formset':formset
}
return render(request, 'accounts/ubc_form.html', context)
forms.py
class UbcForm(forms.ModelForm):
class Meta:
research_line = forms.ModelMultipleChoiceField(queryset=ResearchLines.objects.all())
model = Ubc
exclude = ('employee_number', ' revenues', 'filter_grade', 'grade',
' knowledge_grade',
'application_grade', 'ie_grade', ' ia_grade', 'final_grade',
'inactive', 'last_coordinator_access', ' hr_count',
'hr_returned', ' match_hr_count', 'general_grade', 'lat', 'lng'
'tokens', 'iso_certification', 'other_certification', 'researchers',
'thematic_network',
)
widgets ={
'name':forms.TextInput(attrs={
'class':'form-control',
'placeholder': 'Nome da UBC'
}),
'parent_institution_name': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Nome da Instituição à qual a UBC é vinculada'
}),
'laboratory_departament': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Laboratório/Departamento'
}),
'cnpj': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'CNPJ'
}),
'institution_name': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Nome da instituição'
}),
'coordinator': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Pessoa Responsável'
}),
'email': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'E-mail'
}),
'website': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Website'
}),
'rad_operating_time': forms.NumberInput(attrs={
'class':'form-control',
'placeholder':'Tempo de atuação em projetos de P&D+I'
}),
'phone': forms.TextInput(attrs={
'class':'form-control',
'placeholder': 'Telefone'
}),
'partner_category': forms.RadioSelect(),
'main_product':forms.CheckboxSelectMultiple( attrs={
'type':'checkbox'
}),
'activity_branch':forms.Select( attrs={
'class':'form-control'
}),
'research_line':forms.TextInput(attrs={
'class':'form-control'
}),
'cep': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'CEP'
}),
'street': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Endereço'
}),
'city': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Cidade'
}),
'uf': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'UF'
}),
}
class ResearchLineForm(forms.ModelForm):
class Meta:
model = ResearchLines
fields = ('title', )
widgets = {
'title':forms.TextInput(attrs={
'class':'form-control'
})
}
class AddressForm(forms.ModelForm):
model = Address
fields = '__all__'
LinesFormSet = inlineformset_factory(
Ubc,
ResearchLines,
fields=('title', ),
extra=1,
widgets = {
'title':forms.TextInput(attrs={
'class':'form-control'
})
}
)
inside of my form.html the formset tag and the script from django-dynamic-formset to generate the new form
{{formset.management_form}}
{% for form in formset %}
<div class="link-formset">
{{ form }}
</div>
{% endfor %}
<script>
$('.link-formset').formset({
addText: 'add link',
deleteText: 'remove'
});
</script>

Creating multiple forms with a single model

I want to create multiple forms using single model. Is it possible?
First I made a model including all the fields I need.
models.py
class AcademicsUpto10(models.Model):
PRE_PRIMARY_SUBJECT_CHOICES = (
('Abacus', 'Abacus'),
('Handwriting Basic', 'Handwriting Basic'),
('English Phonetics', 'English Phonetics'),
('English', 'English'),
('KG Academic Class', 'KG Academic Class'),
)
SUBJECT_1TO5_CHOICES = (
('All subjects', 'All subjects'),
('Vedic Maths', 'Vedic Maths'),
('Mathematics', 'Mathematics'),
('Science', 'Science'),
('English', 'English'),
('Hindi', 'Hindi'),
('Environmental Studies', 'Environmental Studies'),
('Mathematics - Science (Combo)', 'Mathematics - Science (Combo)'),
('Handwriting English/Hindi', 'Handwriting English/Hindi'),
)
SUBJECT_6TO10_CHOICES = (
('Mathematics', 'Mathematics'),
('Science', 'Science'),
('Computer Science', 'Computer Science'),
('English', 'English'),
('Social Science', 'Social Science'),
('Sanskrit', 'Sanskrit'),
('Environmental Studies', 'Environmental Studies'),
('French', 'French'),
('German', 'German'),
('Spanish', 'Spanish'),
('Mathematics - Science (Combo)', 'Mathematics - Science (Combo)'),
('Olympiad Maths/Science', 'Olympiad Maths/Science'),
)
BOARD_CHOICES = (
('CBSE', 'CBSE'),
('ICSE', 'ICSE'),
('State Board', 'State Board'),
('International Board', 'International Board'),
)
GENDER_CHOICES = (
('Male', 'Male'),
('Female', 'Female'),
('Flexible to get the best tutor', 'Flexible to get the best tutor'),
)
DAY_CHOICES = (
('Monday', 'Monday'),
('Tuesday', 'Tuesday'),
('Wednesday', 'Wednesday'),
('Thursday', 'Thursday'),
('Friday', 'Friday'),
('Saturday', 'Saturday'),
('Flexible on days to get the best tutor', 'Flexible on days to get the best tutor'),
)
SLOT_CHOICES = (
('Early Morning (6AM-8AM)', 'Early Morning (6AM-8AM)'),
('Morning (8AM-12AM)', 'Morning (8AM-12AM)'),
('Early Afternoon (12PM-3PM)', 'Early Afternoon (12PM-3PM)'),
('Late Afternoon (3PM-5PM)', 'Late Afternoon (3PM-5PM)'),
('Early Evening (5PM-7PM)', 'Early Evening (5PM-7PM)'),
('Late Evening (7PM-10PM)', 'Late Evening (7PM-10PM)'),
)
unique_id = models.UUIDField(default=uuid.uuid4, unique=True)
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(default=timezone.now)
ticket_size = models.CharField(max_length=30, default=1000, blank=True)
field = models.CharField(max_length=30, blank=True)
standard = models.CharField(max_length=30, blank=True)
pre_primary_subject = MultiSelectField(choices=PRE_PRIMARY_SUBJECT_CHOICES, default='Abacus', blank=False)
subject_1to5 = MultiSelectField(choices=SUBJECT_1TO5_CHOICES, default='All subjects', blank=False)
subject_6to10 = MultiSelectField(choices=SUBJECT_6TO10_CHOICES, default='Mathematics', blank=False)
subject_final = models.CharField(max_length=300, blank = True)
board = models.CharField(max_length=30, choices=BOARD_CHOICES, default='CBSE', blank=True)
day = MultiSelectField(choices=DAY_CHOICES, default='Flexible on days to get the best tutor', blank=False)
slot = MultiSelectField(choices=SLOT_CHOICES, default='Early Morning (6AM-8AM)', blank=False)
gender_preference = models.CharField(max_length=35, choices=GENDER_CHOICES, default='Flexible to get the best tutor', blank=False)
address = models.CharField(max_length=300, blank=True)
plot = models.CharField(max_length=150, blank=False)
street = models.CharField(max_length=150, blank=False)
landmark = models.CharField(max_length=150, blank=True)
name = models.CharField(max_length=150, blank=False)
contact = models.IntegerField(validators=[
MaxValueValidator(9999999999),
MinValueValidator(7000000000)],
blank=False)
email = models.EmailField(max_length=150, blank=False)
def __unicode__(self):
return (self.name)
Then I wrote some forms.py
class AcademicsPrePrimaryForm(forms.ModelForm):
class Meta:
model = AcademicsUpto10
fields = [
'pre_primary_subject', 'day', 'slot', 'gender_preference',
'plot', 'street', 'landmark', 'name', 'contact', 'email'
]
widgets = {
'pre_primary_subject': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'day': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'slot': forms.CheckboxSelectMultiple(attrs={'class': 'for-checkbox'}),
'gender_preference': forms.RadioSelect(),
'plot': forms.TextInput(attrs={'placeholder': 'Plot Number', 'class':'for-field-before'}),
'street': forms.TextInput(attrs={'placeholder': 'Street', 'class': 'for-field-before'}),
'landmark': forms.TextInput(attrs={'placeholder': 'Landmark', 'class': 'for-field-before'}),
'name': forms.TextInput(attrs={'placeholder': 'Name', 'class': 'for-field-before'}),
'contact': forms.TextInput(attrs={'type': 'number', 'placeholder': 'Mobile Number', 'class':'for-field-before'}),
'email': forms.TextInput(attrs={'placeholder': 'Email ID', 'class': 'for-field-before'})
}
class Academics1to5Form(forms.ModelForm):
class Meta:
model = AcademicsUpto10
fields = [
'subject_1to5', 'board', 'day', 'slot', 'gender_preference',
'plot', 'street', 'landmark', 'name', 'contact', 'email'
]
widgets = {
'subject_1to5': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'board': forms.RadioSelect(),
'day': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'slot': forms.CheckboxSelectMultiple(attrs={'class': 'for-checkbox'}),
'gender_preference': forms.RadioSelect(),
'plot': forms.TextInput(attrs={'placeholder': 'Plot Number', 'class':'for-field-before'}),
'street': forms.TextInput(attrs={'placeholder': 'Street', 'class': 'for-field-before'}),
'landmark': forms.TextInput(attrs={'placeholder': 'Landmark', 'class': 'for-field-before'}),
'name': forms.TextInput(attrs={'placeholder': 'Name', 'class': 'for-field-before'}),
'contact': forms.TextInput(attrs={'type': 'number', 'placeholder': 'Mobile Number', 'class':'for-field-before'}),
'email': forms.TextInput(attrs={'placeholder': 'Email ID', 'class': 'for-field-before'})
}
class Academics6to10Form(forms.ModelForm):
class Meta:
model = AcademicsUpto10
fields = [
'subject_6to10', 'board', 'day', 'slot', 'gender_preference',
'plot', 'street', 'landmark', 'name', 'contact', 'email'
]
widgets = {
'subject_6to10': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'board': forms.RadioSelect(),
'day': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'slot': forms.CheckboxSelectMultiple(attrs={'class': 'for-checkbox'}),
'gender_preference': forms.RadioSelect(),
'plot': forms.TextInput(attrs={'placeholder': 'Plot Number', 'class':'for-field-before'}),
'street': forms.TextInput(attrs={'placeholder': 'Street', 'class': 'for-field-before'}),
'landmark': forms.TextInput(attrs={'placeholder': 'Landmark', 'class': 'for-field-before'}),
'name': forms.TextInput(attrs={'placeholder': 'Name', 'class': 'for-field-before'}),
'contact': forms.TextInput(attrs={'type': 'number', 'placeholder': 'Mobile Number', 'class':'for-field-before'}),
'email': forms.TextInput(attrs={'placeholder': 'Email ID', 'class': 'for-field-before'})
}
From here I want to save the subjects in three forms at same place (this subject is to displayed in admin panel), I am not able to figure this out.
Sample view - views.py
def standard8(request):
form = Academics6to10Form(request.POST or None)
if form.is_valid():
form.save(commit=False)
form.save(commit=False).address = request.POST['location']
form.save(commit=False).standard = 'Standard 8'
form.save(commit=False).field = 'Academics'
form.save()
message = "A new query has been added in " + str(form.standard)
message += "Name: " + str(form.name)
message += "Mobile Number: " + str(form.contact)
send_mail(emailSubject, message, emailFrom, emailList, fail_silently=False)
return render(request, 'thanks.html')
else:
return render(request, 'allForms/acadsstandard8.html', {'form': form})