N
N
nastya_guk2021-12-01 05:50:44
Python
nastya_guk, 2021-12-01 05:50:44

How to create a "Category" and a record in this category through one form?

Good afternoon. There are models "Application" and "Application materials":

class Request(models.Model):
    id_request     = models.AutoField(primary_key=True)
    status         = models.CharField(default="Подписание" , max_length=20)
    nomer_request  = models.IntegerField(blank=True)
    data_request   = models.DateField()
    person_request = models.CharField(max_length=45)
    def __str__(self):
        return str(self.nomer_request)


class Request_material(models.Model):
    id_request     = models.ForeignKey(Request, on_delete=models.CASCADE)
    status         = models.CharField(default="Подписание" , max_length=20)
    name           = models.CharField(max_length=200)
    mnemokod_SAP   = models.IntegerField()
    ed_izm         = models.CharField(max_length=10)
    priznak_rem    = models.BooleanField()
    price          = models.IntegerField()
    colvo_request  = models.IntegerField()
    prihod         = models.DateField(null=True, blank=True)
    spisan         = models.DateField (null=True, blank=True)
    def __str__(self):
        return self.name


I am making an application creation form and I don’t have an understanding of how to make the materials from the form be linked to the application itself, created in the same form

. I didn’t find anything about this or something similar in the documentation, so I’m writing here. There are no ideas at all. I ask for help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philip Schultz, 2021-12-01
@Filipp_SC

Create the forms.py file in the application directory.
Import the models there.
Then you can use the special ModelForm class here you can read more.
Sample code for forms.py:

from .model import Request
from django.forms import ModelForm

class FormRequest(ModelForm):
    class Meta:
        model = Request   # указываем модель с которой будет связанна форма 
        fields = '__all__'  # указываем какие поля из модели перейдут в форму

Next, create a view in views.py
Example code for Views.py:
from django.views import generic

class СreateRequest(generic.CreateView):
    model = Request   
    form_class = FormRequest
    template_name = '.../........html'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question