Answer the question
In order to leave comments, you need to log in
How to bind objects created in a Django form?
2 forms Objects and Apartments are displayed on the page. How to create and set a link by key when submitting completed forms. Or how to reshape.
In the future, the shape of the Object will be combined with other shapes.
def add_flat(request):
if request.method=='POST':
objform=ObjForm(request.POST)
flatform=FlatForm(request.POST)
#print(objform)
if flatform.is_valid() and objform.is_valid():
#print(objform.cleaned_data)
#flat=flatform.save()
#obj=objform.save(commit=False)
#obj.foreignkeytoA=flat # не работает
#obj.save()
return redirect('obj')
else:
objform=ObjForm(initial={'real':1})
flatform=FlatForm()
return render (request, "firstapp/addflat.html", {'objform':objform , 'flatform':flatform})
class ObjForm (forms.ModelForm):
class Meta:
model=Obj
fields=('real','d_type','r_type','s_type','coast','agent','client','region','district','location','street','apartment','source','comments')
widgets={
'real': forms.Select(attrs={'class':'form-select'}), #,'disabled':'disabled'
'd_type':forms.Select(attrs={'class':'form-select'}),
'r_type':forms.Select(attrs={'class':'form-select'}),
's_type':forms.Select(attrs={'class':'form-select'}),
'coast':forms.NumberInput(attrs={"class":"form-control"}),
'agent': forms.Select(attrs={'class':'form-select'}),
'client':forms.Select(attrs={'class':'form-select'}),
'region':forms.TextInput(attrs={"class":"form-control"}),
'district':forms.TextInput(attrs={"class":"form-control"}),
'location':forms.TextInput(attrs={"class":"form-control"}),
'street':forms.TextInput(attrs={"class":"form-control"}),
'apartment':forms.TextInput(attrs={"class":"form-control"}),
'source':forms.Select(attrs={'class':'form-select'}),
'comments':forms.Textarea(attrs={"class":"form-control"}),
}
#exclude = ('real',)
class FlatForm (forms.ModelForm):
class Meta:
model=Flat
fields='__all__'
widgets={
'room_c':forms.NumberInput(attrs={'class':'form-control'}),
'floor':forms.NumberInput(attrs={'class':'form-control'}),
}
class Flat(models.Model):
re_id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
room_c=models.PositiveSmallIntegerField(verbose_name="Кол-во комнат")
floor=models.PositiveSmallIntegerField(verbose_name="Этаж")
class Home(models.Model):
re_id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
home_area=models.PositiveSmallIntegerField(verbose_name="Площадь дома")
floors=models.PositiveSmallIntegerField(verbose_name="Этажей в доме")
class Obj(models.Model):
agent=models.ForeignKey(Agent, verbose_name="Агент", on_delete=models.DO_NOTHING)
client=models.ForeignKey(Client, verbose_name="Клиент", on_delete=models.DO_NOTHING)
d_type_ch=( #тип сделки
('sale','Продажа'),
('rent','Аренда'),
)
r_type_ch=( #тип родажи или аренды
('day','Посуточно'),
('months','Помесячно'),
('long','Долгосрочная'),
)
s_type_ch=(
('direct','Прямая'),
('alter','Альтернатива'),
)
source_ch=( #Источник лида
(1,'Входяший звонок'),
(2,'Исходящий звонок'),
(3,'Наш сайт'),
(4,'Сторонний сайт'),
(5,'По знакомству'),
(6,'Самостоятельный поиск'),
)
real_ch=( #тип недвижимости
(1,'Квартира'),
(2,'Дом'),
(3,'Земельный участок'),
(4,'Коммерч'),
(5,'Гараж'),
)
real=models.PositiveSmallIntegerField(choices=real_ch,verbose_name="Тип недвижимости")
region=models.CharField(max_length=40,verbose_name="Регион")
district=models.CharField(max_length=60,verbose_name="Район") #район\округ
location=models.CharField(max_length=60,verbose_name="Населенный пункт") # населенный пункт
street=models.CharField(max_length=60,verbose_name="Улица")
apartment=models.CharField(max_length=10,verbose_name="Дом")
comments=models.TextField(verbose_name="Служебный комментарий") #Служебный комментарий
#cadastral_number=models.CharField(max_length=10, null=True, blank=True) #Кадастровый номер
coast=models.PositiveIntegerField(verbose_name="Начальная стоимость") #Стоимость 0=min 1=max
source=models.PositiveSmallIntegerField(choices=source_ch,null=True, blank=True,verbose_name="Источник") #источник
d_type=models.CharField(max_length=20, choices=d_type_ch,verbose_name="Тип сделки") #тип родажа или аренда
r_type=models.CharField(max_length=20,null=True, blank=True, choices=r_type_ch,verbose_name="Тип аренды") #тип Аренды
s_type=models.CharField(max_length=20,null=True, blank=True, choices=s_type_ch,verbose_name="Тип продажи") #тип Продажи
Flat=models.ForeignKey(Flat,null=True, blank=True, verbose_name="Квартира", on_delete=models.DO_NOTHING)
Home=models.ForeignKey(Home, null=True,blank=True, verbose_name="Дом", on_delete=models.DO_NOTHING)
Answer the question
In order to leave comments, you need to log in
I found it difficult to understand your question because the code examples contain a lot of details that are not relevant to the problem. Try creating a minimal reproducible example next time .
Essentially, your actions should be something like this:
if flatform.is_valid() and objform.is_valid():
with transaction.atomic()
flat = flatform.save()
obj = objform.save(commit=False)
obj.Flat = flat
obj.save()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question