31/5000 how to insert a new user? - django

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

Related

Initializing foriegnkey in CRUD operation

i am working on a project to manage animal farm. The backend is with django and the frot end is with bootstrap. The project has several apps as in django documentation.
views.py
from django.shortcuts import render,redirect, get_object_or_404
from django.http import JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse_lazy
from livestockrecords.models import *
from .models import *
from .forms import *
from .models import *
from .forms import *
def save_feedin_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
form.save()
data['form_is_valid'] = True
livestocks = Livestock.objects.all()
context ={
'livestocks': livestocks
}
data['html_livestock_list'] =
render_to_string('includes/_list_feeding.html', context)
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
def feeding_add(request, pk):
livestocks = get_object_or_404(Livestock, pk=pk)
data = dict()
if request.method == 'POST':
form = FeedingForm(request.POST , initial={'livestock': pk})
else:
form = FeedingForm(initial={'livestock': livestocks})
return save_feedin_form(request, form, 'includes/_add_feeding.html')
models.py
from django.db import models
from livestockrecords.models import Livestock
# Create your models here.
class Addmedication(models.Model):
MEDICATIONTYPE = (
('Drugs', 'Drugs'),
('Vaccination', 'Vaccination'),
)
name = models.CharField(max_length=200, null=True)
medicationType = models.CharField(max_length=200, null=True, choices= MEDICATIONTYPE)
def __str__(self):
return self.name
class Adddisease(models.Model):
name = models.CharField(max_length=200, null=True)
description = models.TextField(null=True)
def __str__(self):
return self.name
class DailyRecords(models.Model):
livestock = models.ForeignKey(Livestock, null=True, on_delete = models.SET_NULL)
dateAdded =models.DateTimeField(auto_now_add=True, null=True)
datepurchased=models.DateField(auto_now_add=False, null=True)
class Meta:
abstract = True
class Mortality(DailyRecords):
qty = models.IntegerField()
cause = models.TextField(null=True)
class Medication(DailyRecords):
medication = models.ForeignKey(Addmedication, null=True, on_delete = models.SET_NULL)
disease = models.ForeignKey(Adddisease, null=True, on_delete = models.SET_NULL)
class Feeding(DailyRecords):
feedname = models.CharField(max_length=200, null=True)
qty = models.FloatField()
forms.py
from django import forms
from django.forms import ModelForm
from .models import *
class FeedingForm(ModelForm):
class Meta:
model = Feeding
fields = ['livestock','datepurchased', 'feedname', 'qty']
labels = {
'livestock':'',
'datepurchased': '',
'feedname': '',
'qty': '',
}
widgets = {
'livestock': forms.HiddenInput(),
'datepurchased':forms.TextInput( attrs={
'placeholder': 'Date Added *',
'class': 'form-control',
'type': 'date',
}),
'feedname':forms.TextInput(attrs = {
'placeholder': 'feed name *',
'class': 'form-control'}),
'qty':forms.TextInput(attrs = {
'placeholder': 'Quantity of feed in kg *',
'class': 'form-control'}),
}
class mortalityForm(ModelForm):
class Meta:
model = Mortality
fields = ['livestock','datepurchased', 'qty', 'cause']
labels = {
'livestock':'',
'datepurchased': '',
'qty': '',
'cause': '',
}
widgets = {
'livestock': forms.HiddenInput(),
'datepurchased':forms.TextInput( attrs={
'placeholder': 'Date Added *',
'class': 'form-control',
'type': 'date',
}),
'cause':forms.TextInput(attrs = {
'placeholder': 'Cause of Mortality *',
'class': 'form-control'}),
'qty':forms.TextInput(attrs = {
'placeholder': 'Number *',
'class': 'form-control'}),
}
class MedicationForm(ModelForm):
class Meta:
model = Medication
fields = ['livestock','datepurchased', 'medication', 'disease']
labels = {
'livestock':'',
'datepurchased': '',
'medication': '',
'disease': '',
}
widgets = {
'livestock': forms.HiddenInput(),
'datepurchased':forms.TextInput( attrs={
'placeholder': 'Date Added *',
'class': 'form-control',
'type': 'date',
}),
'medication':forms.Select(attrs = {
'placeholder': 'Drug name *',
'class': 'form-control'}),
'disease':forms.Select(attrs = {
'placeholder': 'Disease Name *',
'class': 'form-control'}),
}
urls.py
from django.urls import path
from . import views
urlpatterns = [
# livestockrecords
path('', views.daily_home, name = "daily-home"),
path('daily-feeding/<str:pk>/', views.feeding_add, name = "daily-feeding"),
]
In the view.py, the form is an ajax form. it display but when i hit the add button it will not capture the foriegnkey.
When i run the code i get this: error raise e.class(
ValueError: Field 'id' expected a number but got 'None'.
Please i need help

didn't return an HttpResponse

Good morning, when I try to send the form, I get the error, and when I send it, it generates that my view does not return any httpresponse object.
this is the view
class ProductView(View):
template_name = 'products/product.html'
model = Product
form_class = ProductForm
def get_queryset(self):
return self.model.objects.filter(state=True)
def get_context_data(self, **kwargs):
context = {}
context['product'] = self.get_queryset()
context['list_product'] = self.form_class
return context
def get(self, request, *args, **kwargs):
return render(request, self.template_name, self.get_context_data())
def post(self, request, *args, **kwargs):
list_product = self.form_class(request.POST)
if list_product.is_valid():
list_product.save()
return redirect('products:product')
and this is the form
class ProductForm(forms.ModelForm):
name_product = forms.CharField(
max_length=25,
widget=forms.TextInput(
attrs={
'class': 'form-control',
'id': 'name_product',
}
)
)
def clean_name_product(self):
name_product = self.cleaned_data.get('name_product')
if Product.objects.filter(name_product=name_product).exists():
raise forms.ValidationError('El nombre del producto ya existe')
return name_product
class Meta:
model = Product
fields = (
'name_product', 'description', 'price', 'category', 'state', 'image'
)
labels = {
'name_product': 'Nombre del Producto',
'description': 'Descripcion',
'price': 'Precio',
'category': 'Categoria',
'state': 'Estado',
'image': 'Imagen del Producto',
}
widgets = {
'name_product': forms.TextInput(
attrs={
'class': 'form-control',
'id': 'name_product',
}
),
'description': forms.TextInput(
attrs={
'class': 'form-control',
'id': 'description',
}
),
'price': forms.NumberInput(
attrs={
'class': 'form-control',
'id': 'price',
}
),
'category': forms.SelectMultiple(
attrs={
'class': 'custom-select',
'id': 'category',
}
),
'state': forms.CheckboxInput(),
}
when I give send it generates the error.The view products.views.ProductView didn't return an HttpResponse object. It returned None instead.
At the beginning I thought that the error is due to the error lifting in the form, change the code without the validation and it generates the same error
In case the form.is_valid() fails, you do not return anything in the post method, hence the error. That being said, this is basically just a CreateView [Django-doc], so it might be better to use that to reduce the amount of "boilerplate" code:
from django.views.generic.edit import CreateView
class ProductView(CreateView):
template_name = 'products/product.html'
model = Product
form_class = ProductForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update(
product=Product.objects.filter(state=True),
list_product=context['form']
)
return context

Django form field required on condition

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)

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})