M
M
maniacus262019-05-08 14:56:54
Django
maniacus26, 2019-05-08 14:56:54

How to link two models (shapes) in DJANGO automatically on creation?

Good afternoon !
There
is a "Request" model There is a "Request" model
After filling in the "Request" form (an entry in the database has appeared, there is an id), it becomes possible to form a "Request". By clicking on the button and filling out the "Request" form, this record in the model should have a connection with the record in the "Contact" model from which the "Request" form was called.
The fact is that there can be many such "Requests" for one "Request" record.
The question is how to pass the "Request" form the ID of the "Contact" record in which the button was pressed?
Adding a manual selection of "Case" to the "Record" form is not a problem - but it's not a solution. The record must itself, without the user, be attached.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2019-05-08
@maniacus26

I will add to Yura Khlyan ,

maniacus26, the simplest solution is to create a request from the contact page. For example:
obrashcenije/2 - a page with information about an appeal
obrashcenije/2/dodat_zapros - a page with a request for a specific appeal.
Then in the request creation view, the self.kwagrs['obr_id'] parameter will be available if the url is set something like this:

that if you need to transfer the object (id) of the call to the form itself, you can in the view class through
class ZaprosCreator(CreateView):
    form_class = ZaprosForm

    def get_initial(self):
        return {'obrashcenije': self.kwagrs['obr_id']}

Or if simple views through functions are used, then
In shape to catch
class ZaprosForm(forms.ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        super(ZaprosForm, self).__init__(*args, **kwargs)
        self.obrashcenije = kwargs.get('initial').get('obrashcenije', None)

Well, as an option in the form, do not process the appeal at all:
class ZaprosForm(forms.ModelForm):
    class Meta:
        model = ZaprosModel
        exclude = ('obrashcenije',)

And already in the view, before saving the form, add
class ZaprosView(CreateView):
    form_class = ZaprosForm

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.obrashcenije_id = self.kwagrs['obr_id']
        obj.save()
        return super(ZaprosView, self).form_valid(form)

PS. avoid Russian names of models/variables/classes, even in transliteration

Y
Yura Khlyan, 2019-05-08
@MAGistr_MTM

On the "Request" button, put an input with the id of the request. Then create a request:

obj = form.save(commit=False)
obj.obrashchenije = request.POS.get('obrashchenije_id')
obj.save()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question