I have 5 forms: MyForm, EducationForm, ExperienceForm, RecommendationForm, OtherDocumentsForm
I want to disply them in one form template. I can not do it with CreateView because it only accepts one form class. How can I create single view for multiple forms?
class MyForm(forms.ModelForm):
class Meta:
model = UserForm_uz
fields = 'all'
class EducationForm(forms.ModelForm):
class Meta:
model = Education_uz
fields = 'all'
class ExperienceForm(forms.ModelForm):
class Meta:
model = Experience_uz
fields = 'all'
class RecommendationForm(forms.ModelForm):
class Meta:
model = Recommendation_uz
fields = 'all'
class OtherDocumentsForm(forms.ModelForm):
class Meta:
model = OtherDocuments
fields = 'all'
I want all the forms to be submitted in a single request and single button. They related with foreignkey to each other EducationForm, ExperienceForm, RecommendationForm, OtherDocumentsForm connected to MyForm with foreignKey
My models:
from django.db import models
language_choices = [('1', 'Билмайман'),
('2', 'Ёмон'),
('3', 'Лугат ёрдамида'),
('4', 'Ўртача'),
('5', 'Яхши'),
('6', 'Жуда яхши'), ]
approve_choices = [('Yes', 'Ха'),
('No', 'Йўк')]
agreement_choices = [('Yes', 'Ха'),
('No', 'Йўк')]
class UserForm_uz(models.Model):
rasm = models.ImageField(upload_to='rasmlar',null=True,blank=True)
lastName = models.CharField(max_length=200)
firstName = models.CharField(max_length=200)
middleName = models.CharField(max_length=200)
birthData = models.DateField()
nation = models.CharField(max_length=50)
birthPlace = models.CharField(max_length=250)
marriage_status = models.CharField(max_length=20)
children = models.CharField(max_length=20)
militaryResp = models.CharField(max_length=150)
language_uzbek = models.CharField(choices=language_choices,max_length=150)
language_russian = models.CharField(choices=language_choices,max_length=150)
language_english = models.CharField(choices=language_choices,max_length=150)
language_boshqa = models.CharField(max_length=50)
computer_literacy = models.CharField(max_length=15)
functional_resp = models.CharField(max_length=250)
work_experience = models.CharField(max_length=200)
yutuqlar = models.CharField(max_length=200)
leaving_work_reason = models.CharField(max_length=200)
main_skills = models.CharField(max_length=300)
expected_salary = models.CharField(max_length=100)
reasontoWork = models.CharField(max_length=300)
relatives_company = models.CharField(max_length=300)
criminal_history = models.CharField(max_length=250)
homeNumber = models.CharField(max_length=15)
phoneNumber = models.CharField(max_length=15)
email = models.EmailField()
additional_info = models.CharField(max_length=300)
approve_info = models.CharField(choices=approve_choices,max_length=20)
agreement = models.CharField(choices=agreement_choices,max_length=20)
passport_file = models.FileField(upload_to='fayllar')
diplom_file = models.FileField(upload_to='fayllar')
trudovoyKnishka = models.FileField(upload_to='fayllar')
fullName = models.CharField(max_length=100)
class Education_uz(models.Model):
form = models.ForeignKey(
UserForm_uz,
on_delete=models.CASCADE,
)
startingDate = models.DateField()
endingDate = models.DateField()
name = models.CharField(max_length=200)
degree = models.CharField(max_length=50)
speciality = models.CharField(max_length=150)
diplomSeriya = models.CharField(max_length=50)
class Experience_uz(models.Model):
form = models.ForeignKey(
UserForm_uz,
on_delete=models.CASCADE,
)
startWorkDate = models.DateField()
endWorkDate = models.DateField()
name = models.CharField(max_length=100)
lavozim = models.CharField(max_length=100)
address = models.CharField(max_length=100)
class Recommendation_uz(models.Model):
form = models.ForeignKey(
UserForm_uz,
on_delete=models.CASCADE,
)
fullName = models.CharField(max_length=150)
workPlace = models.CharField(max_length=150)
phoneAndEmail = models.CharField(max_length=100)
class OtherDocuments(models.Model):
form = models.ForeignKey(
UserForm_uz,
on_delete=models.CASCADE,
)
file = models.FileField(upload_to='fayllar')
comment = models.CharField(max_length=100)
Since MyForm will be submitted at the same time as the other forms you need to exclude the ForeignKey field to UserForm_uz from all the other models, the related object doesn't exist yet so you can't select it
class EducationForm(forms.ModelForm):
class Meta:
model = Education_uz
# Repeated for all four forms
exclude = ['form'] # Whatever the ForeignKey to UserForm_uz is named
Here's an example view that uses three of the forms (I missed out two to save typing). Give each form a prefix, this reduces the risk of having form fields with conflicting names. Validate them all in one go, if any form is invalid the view should not continue. Save MyForm first and use the output to pass to the other forms as the foreign key value
def my_view(request):
if request.method == 'POST':
my_form = MyForm(request.POST, request.FILES, prefix='user')
education_form = EducationForm(request.POST, request.FILES, prefix='education')
experience_form = ExperienceForm(request.POST, request.FILES, prefix='experience')
if all([my_form.is_valid(), education_form.is_valid(), experience_form.is_valid()]):
form = my_form.save()
education = education_form.save(commit=False)
education.form = form
education.save()
experience = experience_form.save(commit=False)
experience.form = form
experience.save()
return redirect('some-view')
else:
my_form = MyForm(prefix='user')
education_form = EducationForm(prefix='education')
experience_form = ExperienceForm(prefix='experience')
return render(request, 'template.html', {'my_form': my_form, 'education_form': education_form, 'experience_form': experience_form})
In your template (template.html) you'll need to render all forms in the same form tag
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ my_form }}
{{ education_form }}
{{ experience_form }}
<input type="submit" />
</form>
Related
I have this error and cant really to identify the error.In dynamic url routing I identify the url predifining the app name(main) then the url.
<a class="btn btn-info" href="{% url 'main:teacher' teacher.fname %}">View</a>
Could this be related with the error of inline form sets?
Models:
class Teacher(models.Model):
teacher_id = models.AutoField(primary_key=True,blank=True)
fname = models.CharField(max_length=200)
lname = models.CharField(max_length=200)
tsc_no = models.CharField(max_length=200,blank=True,unique=True)
email = models.CharField(max_length=200,blank=True,unique=True)
password = models.CharField(max_length=200,blank=True)
profile_picture = models.ImageField(verbose_name='profile_picture',upload_to='photos/%Y/%m/%d',blank=True)
national_id = models.CharField(max_length=200,unique=True)
dob = models.DateField(blank=True)
phone_number = PhoneNumberField()
status = models.CharField(max_length=200)
clas_teacher = models.CharField(max_length=200,blank=True)
date_of_join = models.DateField(blank=True)
timetable_color = models.CharField(max_length=200)
class Course(models.Model):
course_id = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
teacher = models.ManyToManyField(Teacher)
class Meta:
ordering = ['course_name']
def __str__(self):
return self.course_name
The view:
def addmoreteacher(request,pk_test):
teacher = Teacher.objects.get(fname=pk_test)
CourseFormSet = inlineformset_factory(Teacher,Course,fields = ('course_name','description'))
formset = CourseFormSet(instance=teacher)
#form = CourseForm(initial = {'teachers_teaching':teacher})
if request.method == 'POST':
#form = TeacherForm(request.POST)
#print(form)
formset = CourseFormSet(request.POST,instance=teacher)
if formset.is_valid():
formset.save()
print("saved")
return redirect('/')
else:
print(formset.errors)
context = {'formset': formset}
return render(request = request,template_name='main/addmoreteacher_form.html',context=context)
Change models.py's Course class's teacher field,
From,
teacher = models.ManyToManyField(Teacher)
To,
models.ForeignKey(Teacher, on_delete=models.CASCADE)
I have a model defined
class subnet(models.Model):
subnet_id = models.AutoField(primary_key=True)
subnet_pod = models.ForeignKey(pod, null=True, on_delete=models.SET_NULL, verbose_name='Select Pod')
subnet_number = models.IntegerField(verbose_name='VLAN/SVI Number')
subnet_description = models.CharField(max_length=10, verbose_name='Subnet Description')
LAYER_CHOICES = (
('Layer2', 'Layer2'),
('Layer3', 'Layer3'),
)
subnet_layer = models.CharField(max_length=50, choices=LAYER_CHOICES,verbose_name='Layer2/3')
subnet_ip = models.CharField(max_length=50, verbose_name='Gateway IP/Mask')
vrf = models.ForeignKey(vrf,blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Select VRF')
class Meta:
verbose_name = 'Subnet'
verbose_name_plural = 'Subnets'
def __str__(self):
return self.subnet_number
I want to override the subnet_ip and add a label and placeholder to it using a custom form, so I have:
class subnetForm(forms.ModelForm):
class Meta:
model = subnet
fields = ['subnet_number', 'subnet_description', 'subnet_layer', 'vrf']
widgets = {
'subnet_ip': forms.TextInput(attrs={'placeholder': 'e.g,: x.x.x.x/x'}),
}
However the placeholder does not get applied to the model and does not show in front-end.
I also have a admin.py:
class subnetAdmin(admin.ModelAdmin):
list_display = ('subnet_number','subnet_description','subnet_layer','subnet_ip','vrf')
ordering = ('-subnet_number',)
Any help is appreciated!!
Try this !
class subnetForm(forms.ModelForm):
subnet_number = <use same model field datatype> forms.CharField(label = 'subnet_number', widget = forms.TextInput(attrs = {'placeholder' : 'subnet number'}))
class Meta:
model = subnet
fields = ['subnet_number', __other_fields__]
I have been trying to make boat reservation system.
# models.py
class Boat(models.Model):
name = models.CharField (max_length=10, unique=True, blank=False)
type = models.CharField (max_length=10, blank=False)
class Booking(models.Model):
date_from = models.DateField(auto_now=False, auto_now_add=False)
date_to = models.DateField(auto_now=False, auto_now_add=False)
rent = models.DecimalField(max_digits=7, decimal_places=2)
boat = models.ForeignKey(Boat, on_delete=models.CASCADE)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
A new boat is registered through this form:
class newBoatform(forms.Form):
name = forms.CharField(label='Name of the boat: ', max_length=15)
type = forms.CharField(label='Type of the boat: ', max_length=15)
class Meta:
model = Boat
fields = ('name','type',)
A boat is booked through this form:
class bookform(forms.Form):
boat =forms.CharField(label='Select boat',max_length=15)
date_from=forms.DateField(label='Date from', initial=date.today)
date_to=forms.DateField(label='Date to')
rent = forms.DecimalField(label='Pay $ ')
class Meta:
model = Booking
fields = ('date_from','date_to','rent','boat','person',)
To book a boat through the bookform, I am inserting an existing boat name and other field information. Then I am getting the error:
Cannot assign "'Emma'": "Booking.boat" must be a "Boat" instance.
The view function of the bookform:
def bookBoat(request):
if request.method == 'POST':
form = bookform(request.POST)
if form.is_valid():
obj = Booking()
obj.boat = form.cleaned_data['boat']
obj.date_from = form.cleaned_data['date_from']
obj.date_to = form.cleaned_data['date_to']
obj.rent = form.cleaned_data['rent']
obj.save()
return HttpResponseRedirect('/thanks/')
else:
form = bookform()
return render(request, 'booking.html', {'form': form})
I can't understand what is wrong. Other answers on this same error are going over my head.
As I can't comment here's my suggestion: obj.boat = Boat.objects.get(name=form.cleaned_data['boat'])
That should do the job.
I need to populate two combos in a ModelForm, and I would like to initialize them with the current value of each foreign key.
My models are:
class Alumno(models.Model):
idalumno = models.AutoField(primary_key=True)
padre_idpadre = models.ForeignKey('Padre', models.DO_NOTHING, db_column='padre_idpadre', blank=True, null=True)
curso_idcurso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='curso_idcurso')
nombre = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'alumno'
class Curso(models.Model):
idcurso = models.IntegerField(primary_key=True)
nombrecurso = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'curso'
class Padre(models.Model):
idpadre = models.AutoField(primary_key=True)
socio = models.NullBooleanField(blank=True, null=True)
nombre = models.CharField(max_length=45, blank=True, null=True)
primerapellido = models.CharField(max_length=45, blank=True, null=True)
segundoapellido = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'padre'
This is my Form in forms.py:
class AlumnoForm(forms.ModelForm):
padre = PadreModelChoiceField(queryset=Padre.objects.all(), initial=**XXXXXXXXX**) #I would like to init here with the value of the FK
curso = CursoModelChoiceField(queryset=Curso.objects.all(), initial=**XXXXXXXXXX**) #And here too
class Meta:
model = Alumno
fields = ('nombre','padre','curso',)
labels = {
'nombre': 'Nombre',
'padre': 'Padre',
'curso': 'Curso',
}
In views.py
def alumno_editar(request, pk):
alumno = get_object_or_404(Alumno, pk=pk)
if request.method == "POST":
form = AlumnoForm(request.POST, instance=alumno)
if form.is_valid():
alumno = form.save(commit=False)
alumno.save()
return redirect('alumno_listar')
else:
form = AlumnoForm(instance=alumno)
return render(request, 'administration/alumno_editar.html', {'form': form})
What should I write in the part XXXXXXXXXX of the code.
It could be misconception but I'm think is a common operation, althought I don't find it.
Hi, I have this models:
class Mercadoria(models.Model):
idmercadoria = models.IntegerField(verbose_name=u'Código', primary_key=True)
referencia = models.CharField(verbose_name=u'Referência', max_length=30)
descricao = models.CharField(verbose_name=u'Descrição', max_length=250)
status = models.CharField(verbose_name=u'Status', max_length=1)
class Meta:
ordering = ['referencia', 'descricao']
managed = False
db_table = 'mercadoria'
def __unicode__(self):
return self.referencia + ' - ' + self.descricao
class Produto(models.Model):
idproduto = models.IntegerField(verbose_name=u'Código', primary_key=True)
idmercadoria = models.ForeignKey('Mercadoria', db_column='idmercadoria',
verbose_name=u'Mercadoria')
idtamanho = models.ForeignKey('Tamanho', db_column='idtamanho',
verbose_name=u'Tamanho')
idcores = models.ForeignKey('Cores', db_column='idcores',
verbose_name=u'Cores')
estoqueatual = models.DecimalField(u'Estoque Atual', max_digits=18,
decimal_places=4, null=False, default=0)
saldodisponivel = models.DecimalField(u'Saldo Disponível', max_digits=18,
decimal_places=4, null=False, default=0)
codigobarra = models.CharField(verbose_name=u'Código Barras', max_length=13)
tipoproduto = models.CharField(verbose_name=u'Tipo Produto', max_length=1)
class Meta:
ordering = ['idmercadoria']
managed = False
db_table = 'produto'
class ItensPedido(models.Model):
idpedido = models.ForeignKey('Pedido', db_column='idpedido',
primary_key=True, default=-1)
idproduto = models.ForeignKey('Produto', db_column='idproduto')
And I have a problem to get "referencia" fields from "Mercadoria" model, using "ItensPedido" model.
The problem is: this database is legacy database, used by your ERP Delphi software, and the person who design the database, is crazy! In my template, I want to get "Mercadoria" models data.
I try this: {{ itens.idproduto.idmercadoria.descricao.value }} e {{ itens.idproduto__idmercadoria__descricao.value }} but doesn't work.
I try to modify my view to get select_related() work, like this:
def get_field_qs(field, **kwargs):
if field.name == 'idproduto':
field.queryset = Produto.objects.select_related()
return field.formfield(**kwargs)
ItensInlineFormSet = inlineformset_factory(Pedido, ItensPedido, form=PedidoItensForm,
extra=1, fk_name='idpedido', formfield_callback=get_field_qs)
and same problem.. doesn't show me the data from "mercadoria" model.
What`s I'm doing wrong?
Thanks