How to create a subform for Django ModelForm - django

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>

Related

Django-Shapeshifiter problems

I quite new to django and I'm working in a simple project for the University. I'm trying to use the django-shapeshifter, but just by entering like in the example they provide, I get a syntax error I have one main table connected to tow tables with manytomany relations and would like to work with a single view to deal with the forms.
The models:
class PreciosUnitarios(models.Model):
redimiento = models.ForeignKey(Rendimientos, on_delete=models.CASCADE)
mano_obra = models.ManyToManyField(ManoObra, through='PuManoObra')
material_id = models.ManyToManyField(Materiales, through='Pu_Material')
valor_mo = models.FloatField(
validators=[validate_decimals], blank=True, null=True)
valor_material = models.FloatField(
validators=[validate_decimals], blank=True, null=True)
def __str__(self) -> str:
return self.redimiento.nombre
def get_total(self):
return self.valor_mo+self.valor_material
def get_absolute_url(self):
return reverse('pu_detail', kwargs={'pk': self.pk})
def save(self, *args, **kwargs):
if self.id:
pk = self.id
v = Variables.objects.get(pk=2)
rm = self.redimiento.unidades_jornal
jc = ManoObra.objects.get(cargo='Jefe de Cuadrilla')
pu_m = Pu_Material.objects.filter(pu_id=pk)
pu_mo = PuManoObra.objects.filter(pu_id=pk)
tm = pu_m.aggregate(Sum('subtotal'))['subtotal__sum']
tmo = pu_mo.aggregate(Sum('mo_subtotal'))['mo_subtotal__sum']
tmo = (tmo + (((jc.salario*8)/208) * 0.10))/rm
total_herramientas = tmo * v.herramientas
total_seguridad = tmo * v.seguridad
subtotal = tm+tmo+total_herramientas+total_seguridad
total = subtotal / (1 - v.gastos_admin)
total = total/(1-v.utilidad)
total = total*v.iva
self.valor_mo = total * \
(tmo/(subtotal))
self.valor_material = total * \
(tm/(subtotal))
super().save(*args, **kwargs)
else:
super().save(*args, **kwargs)
class PuManoObra(models.Model):
manoObra_id = models.ForeignKey(ManoObra, on_delete=models.CASCADE)
pu_id = models.ForeignKey(
PreciosUnitarios, on_delete=models.CASCADE, null=True, blank=True)
valor_jornal = models.FloatField(
validators=[validate_decimals], null=True, blank=True)
mo_subtotal = models.FloatField(
validators=[validate_decimals], null=True, blank=True)
ctd = models.PositiveIntegerField(default=1)
def __str__(self) -> str:
return self.pu_id.redimiento.nombre + ", "+self.manoObra_id.cargo
def save(self, *args, **kwargs):
vj = self.manoObra_id.salario/26
self.valor_jornal = vj
self.mo_subtotal = self.ctd*vj
super().save(*args, **kwargs)
class Pu_Material(models.Model):
material_id = models.ForeignKey(Materiales, on_delete=models.CASCADE)
pu_id = models.ForeignKey(
PreciosUnitarios, on_delete=models.CASCADE, null=True, blank=True)
cantidad = models.PositiveIntegerField(default=1)
subtotal = models.FloatField(
validators=[validate_decimals], null=True, blank=True)
class Meta():
unique_together = [['material_id', 'pu_id']]
def __str__(self) -> str:
return self.pu_id.redimiento.nombre + ", Material: "+self.material_id.material_nombre
def save(self, *args, **kwargs):
self.subtotal = self.material_id.precio*self.cantidad
super().save(*args, **kwargs)
my forms:
class PrecioUnitarioForm(forms.ModelForm):
class Meta():
model = PreciosUnitarios
fields = ('redimiento',
# 'mano_obra',
# 'material_id',
# 'valor_mo',
# 'valor_material'
)
labels = {
'redimiento': 'Selecionar Rendimiento',
'mano_obra': 'Selecionar Mano de Obra',
'material_id': '',
'valor_mo': '',
'valor_material': '',
}
widgets = {
'redimiento': forms.Select(attrs={'class': 'form-control'}),
'mano_obra': forms.SelectMultiple(attrs={'class': 'form-control'}),
'material_id': forms.SelectMultiple(attrs={'class': 'form-control'}),
'valor_mo': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Precio del Material'}),
'valor_material': forms.TextInput(attrs={'class': 'form-control'}),
}
class PuMaterialForm(forms.ModelForm):
class Meta():
model = Pu_Material
fields = (
'material_id', 'pu_id', 'cantidad'
)
labels = {
'material_id': 'Material', 'pu_id': 'Preciounitario', 'cantidad': ''
}
widgets = {
'material_id': forms.Select(attrs={'class': 'form-control'}),
'pu_id': forms.Select(attrs={'class': 'form-control'}),
'cantidad': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Cantidad'})
}
class PuManoObraForm(forms.ModelForm):
class Meta():
model = PuManoObra
fields = (
'manoObra_id', 'pu_id', 'ctd'
)
labels = {'manoObra_id': 'Mano de Obra',
'pu_id': 'Precio Unitario',
'ctd': ''
}
widgets = {
'manoObra_id': forms.Select(attrs={'class': 'form-control'}),
'pu_id': forms.Select(attrs={'class': 'form-control'}),
'ctd': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Cantidad'})
}
the shapeshift code:
class PrecioUnitarioFormView(MultiModelFormView):
form_classes = ('PrecioUnitarioForm', 'PuMaterialForm', 'PuManoObraForm')
template_name = 'cotizacion/preciosunitarios.html'
success_url = 'cotizacion/pu_detail.html'
success_message = ''
def get_instances(self):
instances = {
'preciounitariofomr': self.request.preciosunitarios,
'pumaterialform': Pu_Material.objects.filter(
user=self.request.preciosunitarios).first(),
'pumanoobraform': PuManoObra.objects.filter(
user=self.request.preciosunitarios).first()
}
return instances
the error says that "object has no attribute name".
Anyone can help?

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

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

RelatedObjectDoesNotExist at /updateprofile User has no profile

i have one model userprofile which is connected to User by onetoone relationship. i am trying to create combined form for both user and userprofile form but it is showing onetoonedescripter has no attribute _meta.
views.py
'''
def UpdateProfile(request):
if request.method =='POST':
EUF_form = EditUserForm(request.POST, instance=request.user )
EPF_form = EditProfileForm(request.POST, instance=request.user.Profile )
if EUF_form.is_valid() and EPF_form.i_valid():
EUF_form.save()
EPF_form.save()
return HttpResponse("Profile updated succesfully.")
return render(request, 'profile_page.html')
else:
EUF_form = EditUserForm(instance=request.user)
EPF_form = EditProfileForm(instance=request.user.profile)
return render(request, 'edit_profile.html', {'EUF_form':EUF_form, 'EPF_form':EPF_form})
'''
models.py
'''
class Profile(models.Model):
user = models.OneToOneField(User, on_delete= models.CASCADE)
mobile = models.CharField(max_length=20, blank=True)
bio = models.CharField(max_length=300, default='')
avatar = models.ImageField(upload_to='avatars', blank=True)
birthday = models.DateField(blank=True, default='1990-12-01')
website = models.CharField(blank=True, max_length=256)
gender = models.CharField(blank=True, max_length=20, choices=[('M','Male'), ('F','Female'),('O','Other')])
def __str__(self):
return self.user.username
'''
forms.py
'''
class EditUserForm(ModelForm):
first_name = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'text','name': 'first_name'}),
label="First Name")
last_name = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'text','name': 'last_name'}),
label="Last Name")
username = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'text','name': 'username'}),
label="Username")
email = forms.EmailField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'text','name': 'email'}),
label="Email")
class Meta:
model = User
fields = ['first_name','last_name','username','email']
class EditProfileForm(ModelForm):
mobile = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'tel','name': 'mobile'}),
label="Phone number")
bio = forms.CharField(widget=forms.Textarea,
label="Bio")
birthday = forms.DateField(widget=forms.DateInput(
attrs={'class': 'form-control','type':'date','name': 'birthday'}),
label="Username")
website = forms.URLField(widget=forms.URLInput(
attrs={'class': 'form-control','type':'url','name': 'website'}),
label="website")
gender = forms.ChoiceField(choices=[('M','Male'), ('F','Female'),('O','Other')],
widget=forms.Select ,
label="gender")
class Meta:
model = Profile
fields = ['mobile','bio','birthday','website','gender']
'''

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